The main TWGL module.
Methods
-
createAttribsFromArrays(gl, arrays) → {Object.<string, AttribInfo>}
-
Creates a set of attribute data and WebGLBuffers from set of arrays
Given
var arrays = { position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], }, texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], }, normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], }, color: { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, }, indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], }, };returns something like
var attribs = { position: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, }, texcoord: { numComponents: 2, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, }, normal: { numComponents: 3, type: gl.FLOAT, normalize: false, buffer: WebGLBuffer, }, color: { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true, buffer: WebGLBuffer, }, };notes:
Arrays can take various forms
Bare JavaScript Arrays
var arrays = { position: [-1, 1, 0], normal: [0, 1, 0], ... }Bare TypedArrays
var arrays = { position: new Float32Array([-1, 1, 0]), color: new Uint8Array([255, 128, 64, 255]), ... }Will guess at
numComponentsif not specified based on name.If
coordis in the name assumesnumComponents = 2If
coloris in the name assumesnumComponents = 4otherwise assumes
numComponents = 3
Parameters:
Name Type Description glWebGLRenderingContext The webgl rendering context.
arraysArrays The arrays
Returns:
the attribs
- Type
- Object.<string, AttribInfo>
-
createAttributeSetters(program) → {Object.<string, function()>}
-
Creates setter functions for all attributes of a shader program. You can pass this to
setBuffersAndAttributesto set all your buffers and attributes.Parameters:
Name Type Description programWebGLProgram the program to create setters for.
- See:
-
setAttributesfor example
Returns:
an object with a setter for each attribute by name.
- Type
- Object.<string, function()>
-
createAugmentedTypedArray(numComponents, numElements, opt_type) → {ArrayBuffer}
-
creates a typed array with a
pushfunction attached so that you can easily push values.pushcan take multiple arguments. If an argument is an array each element of the array will be added to the typed array.Example:
var array = createAugmentedTypedArray(3, 2); // creates a Float32Array with 6 values array.push(1, 2, 3); array.push([4, 5, 6]); // array now contains [1, 2, 3, 4, 5, 6]Also has
numComponentsandnumElementsproperties.Parameters:
Name Type Description numComponentsnumber number of components
numElementsnumber number of elements. The total size of the array will be
numComponents * numElements.opt_typeconstructor A constructor for the type. Default =
Float32Array.Returns:
A typed array.
- Type
- ArrayBuffer
-
createBufferInfoFromArrays(gl, arrays) → {BufferInfo}
-
Creates a BufferInfo from an object of arrays.
This can be passed to
setBuffersAndAttributesand tomodule:twgl:drawBufferInfo.Given an object like
var arrays = { position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], }, texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], }, normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], }, indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], }, };Creates an BufferInfo like this
bufferInfo = { numElements: 4, // or whatever the number of elements is indices: WebGLBuffer, // this property will not exist if there are no indices attribs: { a_position: { buffer: WebGLBuffer, numComponents: 3, }, a_normal: { buffer: WebGLBuffer, numComponents: 3, }, a_texcoord: { buffer: WebGLBuffer, numComponents: 2, }, }, };The properties of arrays can be JavaScript arrays in which case the number of components will be guessed.
var arrays = { position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], texcoord: [0, 0, 0, 1, 1, 0, 1, 1], normal: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], indices: [0, 1, 2, 1, 2, 3], };They can also by TypedArrays
var arrays = { position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]), texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]), normal: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]), indices: new Uint16Array([0, 1, 2, 1, 2, 3]), };Or augmentedTypedArrays
var positions = createAugmentedTypedArray(3, 4); var texcoords = createAugmentedTypedArray(2, 4); var normals = createAugmentedTypedArray(3, 4); var indices = createAugmentedTypedArray(3, 2, Uint16Array); positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]); texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]); normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]); indices.push([0, 1, 2, 1, 2, 3]); var arrays = { position: positions, texcoord: texcoords, normal: normals, indices: indices, };For the last example it is equivalent to
var bufferInfo = { attribs: { a_position: { numComponents: 3, buffer: gl.createBuffer(), }, a_texcoods: { numComponents: 2, buffer: gl.createBuffer(), }, a_normals: { numComponents: 3, buffer: gl.createBuffer(), }, }, indices: gl.createBuffer(), numElements: 6, }; gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_position.buffer); gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_texcoord.buffer); gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_normal.buffer); gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);Parameters:
Name Type Description glWebGLRenderingContext A WebGLRenderingContext
arraysArrays Your data
Returns:
A BufferInfo
- Type
- BufferInfo
-
createBuffersFromArrays({WebGLRenderingContext), arrays) → {Object.<string, WebGLBuffer>}
-
Creates buffers from typed arrays
Given something like this
var arrays = { positions: [1, 2, 3], normals: [0, 0, 1], }returns something like
buffers = { positions: WebGLBuffer, normals: WebGLBuffer, }If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.
Parameters:
Name Type Description {WebGLRenderingContext)gl A WebGLRenderingContext.
arraysArrays Returns:
returns an object with one WebGLBuffer per array
- Type
- Object.<string, WebGLBuffer>
-
createFramebufferInfo(gl, attachments, width, height) → {FramebufferInfo}
-
Creates a framebuffer and attachments.
This returns a
FramebufferInfobecause it needs to return the attachments as well as the framebuffer.The simplest usage
// create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer var fbi = twgl.createFramebuffer(gl);More complex usage
// create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer var attachments = [ { format: RGB565, mag: NEAREST }, { format: STENCIL_INDEX8 }, ] var fbi = twgl.createFramebuffer(gl, attachments);Passing in a specific size
var width = 256; var height = 256; var fbi = twgl.createFramebuffer(gl, attachments, width, height);Note!! It is up to you to check if the framebuffer is renderable by calling
gl.checkFramebufferStatus. WebGL only guarantees 3 combinations of attachments work.Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
attachmentsAttachmentOptions[] <optional>
which attachments to create. If not provided the default is a framebuffer with an
RGBA,UNSIGNED_BYTEtextureCOLOR_ATTACHMENT0and aDEPTH_STENCILrenderbufferDEPTH_STENCIL_ATTACHMENT.widthnumber <optional>
the width for the attachments. Default = size of drawingBuffer
heightnumber <optional>
the height for the attachments. Defautt = size of drawingBuffer
Returns:
the framebuffer and attachments.
- Type
- FramebufferInfo
-
createProgram(shaders, opt_attribs, opt_locations, opt_errorCallback) → {WebGLProgram}
-
Creates a program, attaches shaders, binds attrib locations, links the program and calls useProgram.
Parameters:
Name Type Argument Description shadersWebGLShader[] The shaders to attach
opt_attribsstring[] <optional>
An array of attribs names. Locations will be assigned by index if not passed in
opt_locationsnumber[] <optional>
The locations for the. A parallel array to opt_attribs letting you assign locations.
opt_errorCallbackErrorCallback <optional>
callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message.
Returns:
the created program or null if error.
- Type
- WebGLProgram
-
createProgramFromScripts(gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) → {WebGLProgram}
-
Creates a program from 2 script tags.
Parameters:
Name Type Argument Description glWebGLRenderingContext The WebGLRenderingContext to use.
shaderScriptIdsstring[] Array of ids of the script tags for the shaders. The first is assumed to be the vertex shader, the second the fragment shader.
opt_attribsstring[] <optional>
An array of attribs names. Locations will be assigned by index if not passed in
opt_locationsnumber[] <optional>
The locations for the. A parallel array to opt_attribs letting you assign locations.
opt_errorCallbackErrorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message.
Returns:
The created program.
- Type
- WebGLProgram
-
createProgramFromSources(gl, shaderSourcess, opt_attribs, opt_locations, opt_errorCallback) → {WebGLProgram}
-
Creates a program from 2 sources.
Parameters:
Name Type Argument Description glWebGLRenderingContext The WebGLRenderingContext to use.
shaderSourcessstring[] Array of sources for the shaders. The first is assumed to be the vertex shader, the second the fragment shader.
opt_attribsstring[] <optional>
An array of attribs names. Locations will be assigned by index if not passed in
opt_locationsnumber[] <optional>
The locations for the. A parallel array to opt_attribs letting you assign locations.
opt_errorCallbackErrorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message.
Returns:
The created program.
- Type
- WebGLProgram
-
createProgramInfo(gl, shaderSourcess, opt_attribs, opt_locations, opt_errorCallback) → {ProgramInfo}
-
Creates a ProgramInfo from 2 sources.
A ProgramInfo contains
programInfo = { program: WebGLProgram, uniformSetters: object of setters as returned from createUniformSetters, attribSetters: object of setters as returned from createAttribSetters, }Parameters:
Name Type Argument Description glWebGLRenderingContext The WebGLRenderingContext to use.
shaderSourcessstring[] Array of sources for the shaders or ids. The first is assumed to be the vertex shader, the second the fragment shader.
opt_attribsstring[] <optional>
An array of attribs names. Locations will be assigned by index if not passed in
opt_locationsnumber[] <optional>
The locations for the. A parallel array to opt_attribs letting you assign locations.
opt_errorCallbackErrorCallback callback for errors. By default it just prints an error to the console on error. If you want something else pass an callback. It's passed an error message.
Returns:
The created program.
- Type
- ProgramInfo
-
createTexture(gl, options, callback) → {WebGLTexture}
-
Creates a texture based on the options passed in.
Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
optionsTextureOptions <optional>
A TextureOptions object with whatever parameters you want set.
callbackTextureReadyCallback <optional>
A callback called when an image has been downloaded and uploaded to the texture.
Returns:
the created texture.
- Type
- WebGLTexture
-
createTextures(gl, options, callback)
-
Creates a bunch of textures based on the passed in options.
Example:
var textures = twgl.createTextures(gl, { // a power of 2 image hftIcon: { src: "images/hft-icon-16.png", mag: gl.NEAREST }, // a non-power of 2 image clover: { src: "images/clover.jpg" }, // From a canvas fromCanvas: { src: ctx.canvas }, // A cubemap from 6 images yokohama: { target: gl.TEXTURE_CUBE_MAP, src: [ 'images/yokohama/posx.jpg', 'images/yokohama/negx.jpg', 'images/yokohama/posy.jpg', 'images/yokohama/negy.jpg', 'images/yokohama/posz.jpg', 'images/yokohama/negz.jpg', ], }, // A cubemap from 1 image (can be 1x6, 2x3, 3x2, 6x1) goldengate: { target: gl.TEXTURE_CUBE_MAP, src: 'images/goldengate.jpg', }, // A 2x2 pixel texture from a JavaScript array checker: { mag: gl.NEAREST, min: gl.LINEAR, src: [ 255,255,255,255, 192,192,192,255, 192,192,192,255, 255,255,255,255, ], }, // a 1x2 pixel texture from a typed array. stripe: { mag: gl.NEAREST, min: gl.LINEAR, format: gl.LUMINANCE, src: new Uint8Array([ 255, 128, 255, 128, 255, 128, 255, 128, ]), width: 1, }, });Now
textures.hftIconwill be a 2d texturetextures.cloverwill be a 2d texturetextures.fromCanvaswill be a 2d texturetextures.yohohamawill be a cubemap texturetextures.goldengatewill be a cubemap texturetextures.checkerwill be a 2d texturetextures.stripewill be a 2d texture
Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
optionsObject.<string, TextureOptions> A object of TextureOptions one per texture.
callbackTexturesReadyCallback <optional>
A callback called when all textures have been downloaded.
Returns:
{Object.
) the created textures by name -
createUniformSetters(program) → {Object.<string, function()>}
-
Creates setter functions for all uniforms of a shader program.
Parameters:
Name Type Description programWebGLProgram the program to create setters for.
- See:
Returns:
an object with a setter by name for each uniform
- Type
- Object.<string, function()>
-
drawBufferInfo(gl, type, bufferInfo, count, offset)
-
Calls
gl.drawElementsorgl.drawArrays, whichever is appropriatenormally you'd call
gl.drawElementsorgl.drawArraysyourself but calling this means if you switch from indexed data to non-indexed data you don't have to remember to update your draw call.Parameters:
Name Type Argument Description glWebGLRenderingContext A WebGLRenderingContext
typeenum eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...)
bufferInfoBufferInfo as returned from createBufferInfoFromArrays
countnumber <optional>
An optional count. Defaults to bufferInfo.numElements
offsetnumber <optional>
An optional offset. Defaults to 0.
-
drawObjectList(objectsToDraw)
-
Draws a list of objects
Parameters:
Name Type Description objectsToDrawDrawObject[] an array of objects to draw.
-
getWebGLContext(canvas, opt_attribs)
-
Gets a WebGL context.
Parameters:
Name Type Argument Description canvasHTMLCanvasElement a canvas element.
opt_attribsWebGLContextCreationAttirbutes <optional>
optional webgl context creation attributes
-
loadCubemapFromUrls(gl, tex, options, callback)
-
Loads a cubemap from 6 urls as specified in
options.src. Will set the cubemap to a 1x1 pixel color so that it is usable immediately unlessoption.color === false.Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
optionsTextureOptions A TextureOptions object with whatever parameters you want set.
callbackCubemapReadyCallback <optional>
A function to be called when all the images have finished loading. err will be non null if there was an error.
-
loadTextureFromUrl(gl, tex, options, callback) → {HTMLImageElement}
-
Loads a texture from an image from a Url as specified in
options.srcIfoptions.color !== falsewill set the texture to a 1x1 pixel color so that the texture is immediately useable. It will be updated with the contents of the image once the image has finished downloading. Filtering options will be set as approriate for image unlessoptions.auto === false.Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
optionsTextureOptions <optional>
A TextureOptions object with whatever parameters you want set.
callbackTextureReadyCallback <optional>
A function to be called when the image has finished loading. err will be non null if there was an error.
Returns:
the image being downloaded.
- Type
- HTMLImageElement
-
resizeCanvasToDisplaySize(canvas, a) → {boolean}
-
Resize a canvas to match the size it's displayed.
Parameters:
Name Type Argument Description canvasHTMLCanvasElement The canvas to resize.
anumber <optional>
multiplier. So you can pass in
window.devicePixelRatioif you want to.Returns:
true if the canvas was resized.
- Type
- boolean
-
resizeFramebufferInfo(gl, framebufferInfo, attachments, width, height)
-
Resizes the attachments of a framebuffer.
You need to pass in the same
attachmentsas you passed increateFramebufferbecause TWGL has no idea the format/type of each attachment.The simplest usage
// create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer var fbi = twgl.createFramebuffer(gl); ... function render() { if (twgl.resizeCanvasToDisplaySize(gl.canvas)) { // resize the attachments twgl.resizeFramebufferInfo(gl, fbi); }More complex usage
// create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer var attachments = [ { format: RGB565, mag: NEAREST }, { format: STENCIL_INDEX8 }, ] var fbi = twgl.createFramebuffer(gl, attachments); ... function render() { if (twgl.resizeCanvasToDisplaySize(gl.canvas)) { // resize the attachments to match twgl.resizeFramebufferInfo(gl, fbi, attachments); }Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
framebufferInfoFramebufferInfo a framebufferInfo as returned from
createFramebuffer.attachmentsAttachmentOptions[] <optional>
the same attachments options as passed to
createFramebuffer.widthnumber <optional>
the width for the attachments. Default = size of drawingBuffer
heightnumber <optional>
the height for the attachments. Defautt = size of drawingBuffer
-
resizeTexture(gl, tex, options, width, height)
-
Resizes a texture based on the options passed in.
Note: This is not a generic resize anything function. It's mostly used by
resizeFramebufferInfoIt will useoptions.srcif it exists to try to determine atypeotherwise it will assumegl.UNSIGNED_BYTE. No data is provided for the texture. Texture parameters will be set accordinglyParameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the texture to resize
optionsTextureOptions A TextureOptions object with whatever parameters you want set.
widthnumber <optional>
the new width. If not passed in will use
options.widthheightnumber <optional>
the new height. If not passed in will use
options.height -
setAttributePrefix(prefix)
-
Sets the default attrib prefix
When writing shaders I prefer to name attributes with
a_, uniforms withu_and varyings withv_as it makes it clear where they came from. But, when building geometry I prefer using unprefixed names.In otherwords I'll create arrays of geometry like this
var arrays = { position: ... normal: ... texcoord: ... };But need those mapped to attributes and my attributes start with
a_.Parameters:
Name Type Description prefixstring prefix for attribs
-
setAttributes(setters, buffers)
-
Sets attributes and binds buffers (deprecated... use
setBuffersAndAttributes)Example:
var program = createProgramFromScripts( gl, ["some-vs", "some-fs"); var attribSetters = createAttributeSetters(program); var positionBuffer = gl.createBuffer(); var texcoordBuffer = gl.createBuffer(); var attribs = { a_position: {buffer: positionBuffer, numComponents: 3}, a_texcoord: {buffer: texcoordBuffer, numComponents: 2}, }; gl.useProgram(program);This will automatically bind the buffers AND set the attributes.
setAttributes(attribSetters, attribs);Properties of attribs. For each attrib you can add properties:
- type: the type of data in the buffer. Default = gl.FLOAT
- normalize: whether or not to normalize the data. Default = false
- stride: the stride. Default = 0
- offset: offset into the buffer. Default = 0
For example if you had 3 value float positions, 2 value float texcoord and 4 value uint8 colors you'd setup your attribs like this
var attribs = { a_position: {buffer: positionBuffer, numComponents: 3}, a_texcoord: {buffer: texcoordBuffer, numComponents: 2}, a_color: { buffer: colorBuffer, numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true, }, };Parameters:
Name Type Description settersObject.<string, function()> Attribute setters as returned from createAttributeSetters
buffersObject.<string, AttribInfo> AttribInfos mapped by attribute name.
- Deprecated:
-
setBuffersAndAttributes(gl, setters, buffers)
-
Sets attributes and buffers including the
ELEMENT_ARRAY_BUFFERif appropriateExample:
var programInfo = createProgramInfo( gl, ["some-vs", "some-fs"); var arrays = { position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], }, texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], }, }; var bufferInfo = createBufferInfoFromArrays(gl, arrays); gl.useProgram(programInfo.program);This will automatically bind the buffers AND set the attributes.
setBuffersAndAttributes(gl, programInfo, bufferInfo);For the example above it is equivilent to
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.enableVertexAttribArray(a_positionLocation); gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer); gl.enableVertexAttribArray(a_texcoordLocation); gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);Parameters:
Name Type Description glWebGLRenderingContext A WebGLRenderingContext.
settersProgramInfo| Object.<string, function()> A
ProgramInfoas returned fromcreateProgrmaInfoAttribute setters as returned fromcreateAttributeSettersbuffersBufferInfo a BufferInfo as returned from
createBufferInfoFromArrays. -
setDefaultTextureColor(color)
-
Sets the default texture color.
The default texture color is used when loading textures from urls. Because the URL will be loaded async we'd like to be able to use the texture immediately. By putting a 1x1 pixel color in the texture we can start using the texture before the URL has loaded.
Parameters:
Name Type Description colornumber[] Array of 4 values in the range 0 to 1
-
setEmptyTexture(gl, tex, options)
-
Sets a texture with no contents of a certain size. In other words calls
gl.texImage2Dwithnull. You must setoptions.widthandoptions.height.Parameters:
Name Type Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
optionsTextureOptions A TextureOptions object with whatever parameters you want set.
-
setTextureFilteringForSize(gl, tex, options, width, height)
-
Sets filtering or generates mips for texture based on width or height If width or height is not passed in uses
options.widthand//oroptions.heightParameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
optionsTextureOptions <optional>
A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.
widthnumber <optional>
width of texture
heightnumber <optional>
height of texture
-
setTextureFromArray(gl, tex, src, options)
-
Sets a texture from an array or typed array. If the width or height is not provided will attempt to guess the size. See
TextureOptions.Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
srcArray.<number>| ArrayBuffer An array or typed arry with texture data.
optionsTextureOptions <optional>
A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.
-
setTextureFromElement(gl, tex, element, options)
-
Set a texture from the contents of an element. Will also set texture filtering or generate mips based on the dimensions of the element unless
options.auto === false. Iftarget === gl.TEXTURE_CUBE_MAPwill attempt to slice image into 1x6, 2x3, 3x2, or 6x1 images, one for each face.Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
elementHTMLElement a canvas, img, or video element.
optionsTextureOptions <optional>
A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.
-
setTextureParameters(gl, tex, options)
-
Sets the texture parameters of a texture.
Parameters:
Name Type Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
optionsTextureOptions A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.
-
setTextureTo1PixelColor(gl, tex, options)
-
Sets a texture to a 1x1 pixel color. If
options.color === falseis nothing happens. If it's not set the default texture color is used which can be set by callingsetDefaultTextureColor.Parameters:
Name Type Argument Description glWebGLRenderingContext the WebGLRenderingContext
texWebGLTexture the WebGLTexture to set parameters for
optionsTextureOptions <optional>
A TextureOptions object with whatever parameters you want set. This is often the same options you passed in when you created the texture.
-
setUniforms(setters, values)
-
Set uniforms and binds related textures.
example:
var programInfo = createProgramInfo( gl, ["some-vs", "some-fs"); var tex1 = gl.createTexture(); var tex2 = gl.createTexture(); ... assume we setup the textures with data ... var uniforms = { u_someSampler: tex1, u_someOtherSampler: tex2, u_someColor: [1,0,0,1], u_somePosition: [0,1,1], u_someMatrix: [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,0, ], }; gl.useProgram(program);This will automatically bind the textures AND set the uniforms.
setUniforms(programInfo, uniforms);For the example above it is equivalent to
var texUnit = 0; gl.activeTexture(gl.TEXTURE0 + texUnit); gl.bindTexture(gl.TEXTURE_2D, tex1); gl.uniform1i(u_someSamplerLocation, texUnit++); gl.activeTexture(gl.TEXTURE0 + texUnit); gl.bindTexture(gl.TEXTURE_2D, tex2); gl.uniform1i(u_someSamplerLocation, texUnit++); gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]); gl.uniform3fv(u_somePositionLocation, [0, 1, 1]); gl.uniformMatrix4fv(u_someMatrix, false, [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,0, ]);Note it is perfectly reasonable to call
setUniformsmultiple times. For examplevar uniforms = { u_someSampler: tex1, u_someOtherSampler: tex2, }; var moreUniforms { u_someColor: [1,0,0,1], u_somePosition: [0,1,1], u_someMatrix: [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,0, ], }; setUniforms(programInfo, uniforms); setUniforms(programInfo, moreUniforms);Parameters:
Name Type Description settersProgramInfo| Object.<string, function()> a
ProgramInfoas returned fromcreateProgramInfoor the setters returned fromcreateUniformSetters.valuesObject.<string, ?> an object with values for the uniforms. You can pass multiple objects by putting them in an array or by calling with more arguments.For example
var sharedUniforms = { u_fogNear: 10, u_projection: ... ... }; var localUniforms = { u_world: ... u_diffuseColor: ... }; twgl.setUniforms(programInfo, sharedUniforms, localUniforms); // is the same as twgl.setUniforms(programInfo, [sharedUniforms, localUniforms]); // is the same as twgl.setUniforms(programInfo, sharedUniforms); twgl.setUniforms(programInfo, localUniforms};
Type Definitions
-
Arrays
-
This is a JavaScript object of arrays by name. The names should match your shader's attributes. If your attributes have a common prefix you can specify it by calling
setAttributePrefix.Bare JavaScript Arrays var arrays = { position: [-1, 1, 0], normal: [0, 1, 0], ... } Bare TypedArrays var arrays = { position: new Float32Array([-1, 1, 0]), color: new Uint8Array([255, 128, 64, 255]), ... }Will guess at
numComponentsif not specified based on name.If
coordis in the name assumesnumComponents = 2If
coloris in the name assumesnumComponents = 4otherwise assumes
numComponents = 3
Objects with various fields. See
FullArraySpec.var arrays = { position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], }, texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1], }, normal: { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], }, indices: { numComponents: 3, data: [0, 1, 2, 1, 2, 3], }, };Type:
- Object.<string, ArraySpec>
-
ArraySpec
-
An individual array in
ArraysWhen passed to
createBufferInfoFromArraysif an ArraySpec isnumber[]orArrayBufferthe types will be guessed based on the name.indiceswill beUint16Array, everything else will beFloat32ArrayType:
- Array.<number>| ArrayBuffer| FullArraySpec
-
AttachmentOptions
-
The options for a framebuffer attachment.
Note: For a
formatthat is a texture include all the texture options fromTextureOptionsfor examplemin,mag,clamp, etc... Note that unlikeTextureOptionsautodefaults tofalsefor attachment texturesType:
- Object
Properties:
Name Type Argument Description attachnumber <optional>
The attachment point. Defaults to
gl.COLOR_ATTACTMENT0 + ndxunless type is a depth or stencil type then it's gl.DEPTH_ATTACHMENT orgl.DEPTH_STENCIL_ATTACHMENTdepending on the format or attachment type.formatnumber <optional>
The format. If one of
gl.RGBA4,gl.RGB565,gl.RGB5_A1,gl.DEPTH_COMPONENT16,gl.STENCIL_INDEX8orgl.DEPTH_STENCILthen will create a renderbuffer. Otherwise will create a texture. Default =gl.RGBAtypenumber <optional>
The type. Used for texture. Default =
gl.UNSIGNED_BYTE.targetnumber <optional>
The texture target for
gl.framebufferTexture2D. Defaults togl.TEXTURE_2D. Set to appropriate face for cube maps.levelnumber <optional>
level for
gl.framebufferTexture2D. Defaults to 0.attachmentWebGLObject <optional>
An existing renderbuffer or texture. If provided will attach this Object. This allows you to share attachemnts across framebuffers.
-
AttribInfo
-
The info for an attribute. This is effectively just the arguments to
gl.vertexAttribPointerplus the WebGLBuffer for the attribute.Type:
- Object
Properties:
Name Type Argument Description numComponentsnumber <optional>
the number of components for this attribute.
sizenumber <optional>
synonym for
numComponents.typenumber <optional>
the type of the attribute (eg.
gl.FLOAT,gl.UNSIGNED_BYTE, etc...) Default =gl.FLOATnormalizedboolean <optional>
whether or not to normalize the data. Default = false
offsetnumber <optional>
offset into buffer in bytes. Default = 0
stridenumber <optional>
the stride in bytes per element. Default = 0
bufferWebGLBuffer the buffer that contains the data for this attribute
drawTypenumber <optional>
the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW
-
BufferInfo
-
Type:
- Object
Properties:
Name Type Argument Description numElementsnumber The number of elements to pass to
gl.drawArraysorgl.drawElements.indicesWebGLBuffer <optional>
The indices
ELEMENT_ARRAY_BUFFERif any indices exist.attribsObject.<string, AttribInfo> The attribs approriate to call
setAttributes -
CubemapReadyCallback(err, tex, imgs)
-
A callback for when an image finished downloading and been uploaded into a texture
Parameters:
Name Type Description err* If truthy there was an error.
texWebGLTexture the texture.
imgsHTMLImageElement[] the images for each face.
-
DrawObject
-
Type:
- Object
Properties:
Name Type Argument Description activeboolean <optional>
whether or not to draw. Default =
true(must befalseto be not true). In otherwordsundefined=truetypenumber <optional>
type to draw eg.
gl.TRIANGLES,gl.LINES, etc...programInfoProgramInfo A ProgramInfo as returned from createProgramInfo
bufferInfoBufferInfo A BufferInfo as returned from createBufferInfoFromArrays
uniformsObject.<string, ?> The values for the uniforms. You can pass multiple objects by putting them in an array. For example
var sharedUniforms = { u_fogNear: 10, u_projection: ... ... }; var localUniforms = { u_world: ... u_diffuseColor: ... }; var drawObj = { ... uniforms: [sharedUniforms, localUniforms], };offsetnumber <optional>
the offset to pass to
gl.drawArraysorgl.drawElements. Defaults to 0.countnumber <optional>
the count to pass to
gl.drawArraysorgl.drawElemnts. Defaults to bufferInfo.numElements. -
ErrorCallback(msg)
-
Error Callback
Parameters:
Name Type Description msgstring error message.
-
FramebufferInfo
-
Type:
- Object
Properties:
Name Type Description framebufferWebGLFramebuffer The WebGLFramebuffer for this framebufferInfo
attachmentsWebGLObject[] The created attachments in the same order as passed in to
createFramebufferInfo. -
FullArraySpec
-
Use this type of array spec when TWGL can't guess the type or number of compoments of an array
Type:
- Object
Properties:
Name Type Argument Description dataArray.<number>| ArrayBuffer The data of the array.
numComponentsnumber <optional>
number of components for
vertexAttribPointer. Default is based on the name of the array. Ifcoordis in the name assumesnumComponents = 2. Ifcoloris in the name assumesnumComponents = 4. otherwise assumesnumComponents = 3typeconstructor The type. This is only used if
datais a JavaScript array. It is the constructor for the typedarray. (eg.Uint8Array). For example if you want colors in aUint8Arrayyou might have aFullArraySpeclike{ type: Uint8Array, data: [255,0,255,255, ...], }.sizenumber <optional>
synonym for
numComponents.normalizeboolean <optional>
normalize for
vertexAttribPointer. Default is true if type isInt8ArrayorUint8Arrayotherwise false.stridenumber <optional>
stride for
vertexAttribPointer. Default = 0offsetnumber <optional>
offset for
vertexAttribPointer. Default = 0attribstring <optional>
name of attribute this array maps to. Defaults to same name as array prefixed by the defaultAttribPrefix.
namestring <optional>
synonym for
attrib.attribNamestring <optional>
synonym for
attrib. -
ProgramInfo
-
Type:
- Object
Properties:
Name Type Description programWebGLProgram A shader program
uniformSettersObject.<string, function()> object of setters as returned from createUniformSetters,
attribSettersObject.<string, function()> object of setters as returned from createAttribSetters,
-
TextureFunc(gl, options) → {*}
-
A function to generate the source for a texture.
Parameters:
Name Type Description glWebGLRenderingContext A WebGLRenderingContext
optionsTextureOptions the texture options
Returns:
Returns any of the things documentented for
srcforTextureOptions.- Type
- *
-
TextureOptions
-
Texture options passed to most texture functions. Each function will use whatever options are appropriate for its needs. This lets you pass the same options to all functions.
Type:
- Object
If neither
widthnorheightare specified andsqrt(numElements)is an integer width and height are set tosqrt(numElements). Otherwisewidth = numElementsandheight = 1.If only one of
widthorheightis specified then the other equalsnumElements / specifiedDimension.
Properties:
Name Type Argument Description targetnumber <optional>
the type of texture
gl.TEXTURE_2Dorgl.TEXTURE_CUBE_MAP. Defaults togl.TEXTURE_2D.widthnumber <optional>
the width of the texture. Only used if src is an array or typed array or null.
heightnumber <optional>
the height of a texture. Only used if src is an array or typed array or null.
minnumber <optional>
the min filter setting (eg.
gl.LINEAR). Defaults togl.NEAREST_MIPMAP_LINEARor if texture is not a power of 2 on both dimensions then defaults togl.LINEAR.magnumber <optional>
the mag filter setting (eg.
gl.LINEAR). Defaults togl.LINEARformatnumber <optional>
format for texture. Defaults to
gl.RGBA.typenumber <optional>
type for texture. Defaults to
gl.UNSIGNED_BYTEunlesssrcis ArrayBuffer. Ifsrcis ArrayBuffer defaults to type that matches ArrayBuffer type.wrapnumber <optional>
Texture wrapping for both S and T. Defaults to
gl.REPEATfor 2D andgl.CLAMP_TO_EDGEfor cubewrapSnumber <optional>
Texture wrapping for S. Defaults to
gl.REPEATandgl.CLAMP_TO_EDGEfor cube. If set takes precedence overwrap.wrapTnumber <optional>
Texture wrapping for T. Defaults to 'gl.REPEAT
andgl.CLAMP_TO_EDGEfor cube. If set takes precedence overwrap`.unpackAlignmentnumber <optional>
The
gl.UNPACK_ALIGNMENTused when uploading an array. Defaults to 1.premultiplyAlphanumber <optional>
Whether or not to premultiply alpha. Defaults to whatever the current setting is. This lets you set it once before calling
twgl.createTextureortwgl.createTexturesand only override the current setting for specific textures.flipYnumber <optional>
Whether or not to flip the texture vertically on upload. Defaults to whatever the current setting is. This lets you set it once before calling
twgl.createTextureortwgl.createTexturesand only override the current setting for specific textures.colorspaceConversionnumber <optional>
Whether or not to let the browser do colorspace conversion of the texture on upload. Defaults to whatever the current setting is. This lets you set it once before calling
twgl.createTextureortwgl.createTexturesand only override the current setting for specific textures.colorArray.<number>| ArrayBuffer color used as temporary 1x1 pixel color for textures loaded async when src is a string. If it's a JavaScript array assumes color is 0 to 1 like most GL colors as in [1, 0, 0, 1] = red=1, green=0, blue=0, alpha=0. Defaults to [0.5, 0.75, 1, 1]. See
setDefaultTextureColor. Iffalsetexture is set. Can be used to re-load a textureautoboolean <optional>
If not
falsethen texture working filtering is set automatically for non-power of 2 images and mips are generated for power of 2 images.cubeFaceOrdernumber[] <optional>
The order that cube faces are pull out of an img or set of images. The default is
[gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]srcArray.<number>| ArrayBuffer| HTMLCanvasElement| HTMLImageElement| HTMLVideoElement| string| Array.<string>| TextureFunc <optional>
source for texture
If
stringthen it's assumed to be a URL to an image. The image will be downloaded async. A usable 1x1 pixel texture will be returned immediatley. The texture will be updated once the image has downloaded. Iftargetisgl.TEXTURE_CUBE_MAPwill attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3. The pieces will be uploaded incubeFaceOrderIf
string[]then it must have 6 entries, one for each face of a cube map. Target must begl.TEXTURE_CUBE_MAP.If
HTMLElementthen it wil be used immediately to create the contents of the texture. ExamplesHTMLImageElement,HTMLCanvasElement,HTMLVideoElement.If
number[]orArrayBufferit's assumed to be data for a texture. Ifwidthorheightis not specified it is guessed as follows. First the number of elements is computed bysrc.length / numComponetswherenumComponentsis derived fromformat. Iftargetisgl.TEXTURE_CUBE_MAPthennumElementsis divided by 6. ThenIf
number[]will be converted totype.If
srcis a function it will be called with aWebGLRenderingContextand these options. Whatever it returns is subject to these rules. So it can return a string url, anHTMLElementan array etc...If
srcis undefined then an empty texture will be created of sizewidthbyheight. -
TextureReadyCallback(err, tex, img)
-
A callback for when an image finished downloading and been uploaded into a texture
Parameters:
Name Type Description err* If truthy there was an error.
texWebGLTexture the texture.
imgHTMLImageElement the image element.
-
TexturesReadyCallback(err, tex, options)
-
A callback for when all images have finished downloading and been uploaded into their respective textures
Parameters:
Name Type Description err* If truthy there was an error.
texWebGLTexture the texture.
optionsObject.<string, TextureOptions> A object of TextureOptions one per texture.