twgl

The main TWGL module.

For most use cases you shouldn't need anything outside this module.
Exceptions between the stuff added to twgl-full (v3, m4, primitives)

Methods

(static) addExtensionsToContext(gl)

Attempts to enable all of the following extensions
and add their functions and constants to the
WebGLRenderingContext using their normal non-extension like names.

 ANGLE_instanced_arrays
 EXT_blend_minmax
 EXT_color_buffer_float
 EXT_color_buffer_half_float
 EXT_disjoint_timer_query
 EXT_disjoint_timer_query_webgl2
 EXT_frag_depth
 EXT_sRGB
 EXT_shader_texture_lod
 EXT_texture_filter_anisotropic
 OES_element_index_uint
 OES_standard_derivatives
 OES_texture_float
 OES_texture_float_linear
 OES_texture_half_float
 OES_texture_half_float_linear
 OES_vertex_array_object
 WEBGL_color_buffer_float
 WEBGL_compressed_texture_atc
 WEBGL_compressed_texture_etc1
 WEBGL_compressed_texture_pvrtc
 WEBGL_compressed_texture_s3tc
 WEBGL_compressed_texture_s3tc_srgb
 WEBGL_depth_texture
 WEBGL_draw_buffers

For example if ANGLE_instanced_arrays exists then the functions
drawArraysInstanced, drawElementsInstanced, vertexAttribDivisor
and the constant VERTEX_ATTRIB_ARRAY_DIVISOR are added to the
WebGLRenderingContext.

Note that if you want to know if the extension exists you should
probably call gl.getExtension for each extension. Alternatively
you can check for the existence of the functions or constants that
are expected to be added. For example

if (gl.drawBuffers) {
// Either WEBGL_draw_buffers was enabled OR you're running in WebGL2
....

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext

(static) bindFramebufferInfo(gl, framebufferInfoopt, targetopt)

Binds a framebuffer

This function pretty much solely exists because I spent hours
trying to figure out why something I wrote wasn't working only
to realize I forget to set the viewport dimensions.
My hope is this function will fix that.

It is effectively the same as

gl.bindFramebuffer(gl.FRAMEBUFFER, someFramebufferInfo.framebuffer);
gl.viewport(0, 0, someFramebufferInfo.width, someFramebufferInfo.height);
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

the WebGLRenderingContext

framebufferInfo module:twgl.FramebufferInfo | null <optional>

a framebufferInfo as returned from module:twgl.createFramebufferInfo.
If falsy will bind the canvas.

target number <optional>

The target. If not passed gl.FRAMEBUFFER will be used.

(static) bindTransformFeedbackInfo(gl, transformFeedbackInfo, bufferInfoopt)

Binds buffers for transform feedback.

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

The WebGLRenderingContext to use.

transformFeedbackInfo module:twgl.ProgramInfo | Object.<string, module:twgl.TransformFeedbackInfo>

A ProgramInfo or TransformFeedbackInfo.

bufferInfo module:twgl.BufferInfo | Object.<string, module:twgl.AttribInfo> <optional>

A BufferInfo or set of AttribInfos.

(static) bindUniformBlock(gl, programInfo, uniformBlockInfo) → {bool}

Binds a uniform block to the matching uniform block point.
Matches by blocks by name so blocks must have the same name not just the same
structure.

If you have changed any values and you upload the values into the corresponding WebGLBuffer
call module:twgl.setUniformBlock instead.

Parameters:
Name Type Description
gl WebGL2RenderingContext

A WebGL 2 rendering context.

programInfo module:twgl.ProgramInfo | module:twgl.UniformBlockSpec

a ProgramInfo
as returned from module:twgl.createProgramInfo or or UniformBlockSpec as
returned from module:twgl.createUniformBlockSpecFromProgram.

uniformBlockInfo module:twgl.UniformBlockInfo

a UniformBlockInfo as returned from
module:twgl.createUniformBlockInfo.

Returns:
Type:
bool

true if buffer was bound. If the programInfo has no block with the same block name
no buffer is bound.

(static) createBufferInfoFromArrays(gl, arrays, srcBufferInfoopt) → {module:twgl.BufferInfo}

Creates a BufferInfo from an object of arrays.

This can be passed to module:twgl.setBuffersAndAttributes and to
module: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: {
    position: { buffer: WebGLBuffer, numComponents: 3, },
    normal:   { buffer: WebGLBuffer, numComponents: 3, },
    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 be 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: {
    position: { numComponents: 3, buffer: gl.createBuffer(), },
    texcoord: { numComponents: 2, buffer: gl.createBuffer(), },
    normal: { numComponents: 3, buffer: gl.createBuffer(), },
  },
  indices: gl.createBuffer(),
  numElements: 6,
};

gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.position.buffer);
gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.texcoord.buffer);
gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.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 Attributes Description
gl WebGLRenderingContext

A WebGLRenderingContext

arrays module:twgl.Arrays

Your data

srcBufferInfo module:twgl.BufferInfo <optional>

An existing
buffer info to start from. WebGLBuffers etc specified
in the srcBufferInfo will be used in a new BufferInfo
with any arrays specified overriding the ones in
srcBufferInfo.

Returns:
Type:
module:twgl.BufferInfo

A BufferInfo

(static) createFramebufferInfo(gl, attachmentsopt, widthopt, heightopt) → {module:twgl.FramebufferInfo}

Creates a framebuffer and attachments.

This returns a module:twgl.FramebufferInfo because it needs to return the attachments as well as the framebuffer.
It also leaves the framebuffer it just created as the currently bound FRAMEBUFFER.
Note: If this is WebGL2 or if you called module:twgl.addExtensionsToContext then it will set the drawBuffers
to [COLOR_ATTACHMENT0, COLOR_ATTACHMENT1, ...] for how ever many color attachments were created.

The simplest usage

// create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer
const fbi = twgl.createFramebufferInfo(gl);

More complex usage

// create an RGB565 renderbuffer and a STENCIL_INDEX8 renderbuffer
const attachments = [
  { format: RGB565, mag: NEAREST },
  { format: STENCIL_INDEX8 },
]
const fbi = twgl.createFramebufferInfo(gl, attachments);

Passing in a specific size

const width = 256;
const height = 256;
const fbi = twgl.createFramebufferInfo(gl, attachments, width, height);

Note!! It is up to you to check if the framebuffer is renderable by calling gl.checkFramebufferStatus.
WebGL1 only guarantees 3 combinations of attachments work.

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

the WebGLRenderingContext

attachments Array.<module:twgl.AttachmentOptions> <optional>

which attachments to create. If not provided the default is a framebuffer with an
RGBA, UNSIGNED_BYTE texture COLOR_ATTACHMENT0 and a DEPTH_STENCIL renderbuffer DEPTH_STENCIL_ATTACHMENT.

width number <optional>

the width for the attachments. Default = size of drawingBuffer

height number <optional>

the height for the attachments. Default = size of drawingBuffer

Returns:
Type:
module:twgl.FramebufferInfo

the framebuffer and attachments.

(static) createProgramInfo(gl, shaderSources, opt_attribsopt, opt_errorCallbackopt) → (nullable) {module:twgl.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,
}

NOTE: There are 4 signatures for this function

twgl.createProgramInfo(gl, [vs, fs], options);
twgl.createProgramInfo(gl, [vs, fs], opt_errFunc);
twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_errFunc);
twgl.createProgramInfo(gl, [vs, fs], opt_attribs, opt_locations, opt_errFunc);
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

The WebGLRenderingContext
to use.

shaderSources Array.<string>

Array of sources for the
shaders or ids. The first is assumed to be the vertex shader,
the second the fragment shader.

opt_attribs module:twgl.ProgramOptions | Array.<string> | module:twgl.ErrorCallback <optional>

Options for the program or an array of attribs names or an error callback. Locations will be assigned by index if not passed in

opt_locations|module:twgl.ErrorCallback Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations or an error callback.

opt_errorCallback module:twgl.ErrorCallback <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:
Type:
module:twgl.ProgramInfo

The created ProgramInfo or null if it failed to link or compile

(static) createTexture(gl, optionsopt, callbackopt) → {WebGLTexture}

Creates a texture based on the options passed in.

Note: may reset UNPACK_ALIGNMENT, UNPACK_ROW_LENGTH, UNPACK_IMAGE_HEIGHT, UNPACK_SKIP_IMAGES
UNPACK_SKIP_PIXELS, and UNPACK_SKIP_ROWS

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

the WebGLRenderingContext

options module:twgl.TextureOptions <optional>

A TextureOptions object with whatever parameters you want set.

callback module:twgl.TextureReadyCallback <optional>

A callback called when an image has been downloaded and uploaded to the texture.

Returns:
Type:
WebGLTexture

the created texture.

(static) createTextures(gl, options, callbackopt) → {Object.<string, WebGLTexture>}

Creates a bunch of textures based on the passed in options.

Example:

const 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.hftIcon will be a 2d texture
  • textures.clover will be a 2d texture
  • textures.fromCanvas will be a 2d texture
  • textures.yohohama will be a cubemap texture
  • textures.goldengate will be a cubemap texture
  • textures.checker will be a 2d texture
  • textures.stripe will be a 2d texture
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

the WebGLRenderingContext

options Object.<string, module:twgl.TextureOptions>

A object of TextureOptions one per texture.

callback module:twgl.TexturesReadyCallback <optional>

A callback called when all textures have been downloaded.

Returns:
Type:
Object.<string, WebGLTexture>

the created textures by name

(static) createTransformFeedback(gl, programInfo, bufferInfoopt) → {WebGLTransformFeedback}

Creates a transform feedback and sets the buffers

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

The WebGLRenderingContext to use.

programInfo module:twgl.ProgramInfo

A ProgramInfo as returned from module:twgl.createProgramInfo

bufferInfo module:twgl.BufferInfo | Object.<string, module:twgl.AttribInfo> <optional>

A BufferInfo or set of AttribInfos.

Returns:
Type:
WebGLTransformFeedback

the created transform feedback

(static) createTransformFeedbackInfo(gl, program) → {Object.<string, module:twgl.TransformFeedbackInfo>}

Create TransformFeedbackInfo for passing to bindTransformFeedbackInfo.

Parameters:
Name Type Description
gl WebGLRenderingContext

The WebGLRenderingContext to use.

program WebGLProgram

an existing WebGLProgram.

Returns:
Type:
Object.<string, module:twgl.TransformFeedbackInfo>

(static) createUniformBlockInfo(gl, programInfo, blockName) → {module:twgl.UniformBlockInfo}

Creates a UniformBlockInfo for the specified block

Note: If the blockName matches no existing blocks a warning is printed to the console and a dummy
UniformBlockInfo is returned
. This is because when debugging GLSL
it is common to comment out large portions of a shader or for example set
the final output to a constant. When that happens blocks get optimized out.
If this function did not create dummy blocks your code would crash when debugging.

Parameters:
Name Type Description
gl WebGL2RenderingContext

A WebGL2RenderingContext

programInfo module:twgl.ProgramInfo

a ProgramInfo
as returned from module:twgl.createProgramInfo

blockName string

The name of the block.

Returns:
Type:
module:twgl.UniformBlockInfo

The created UniformBlockInfo

(static) drawBufferInfo(gl, bufferInfo, typeopt, countopt, offsetopt, instanceCountopt)

Calls gl.drawElements or gl.drawArrays, whichever is appropriate

normally you'd call gl.drawElements or gl.drawArrays yourself
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 Attributes Description
gl WebGLRenderingContext

A WebGLRenderingContext

bufferInfo module:twgl.BufferInfo | module:twgl.VertexArrayInfo

A BufferInfo as returned from module:twgl.createBufferInfoFromArrays or
a VertexArrayInfo as returned from module:twgl.createVertexArrayInfo

type number <optional>

eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...). Defaults to gl.TRIANGLES

count number <optional>

An optional count. Defaults to bufferInfo.numElements

offset number <optional>

An optional offset. Defaults to 0.

instanceCount number <optional>

An optional instanceCount. if set then drawArraysInstanced or drawElementsInstanced will be called

(static) drawObjectList(gl, objectsToDraw)

Draws a list of objects

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext

objectsToDraw Array.<DrawObject>

an array of objects to draw.

(static) getContext(canvas, opt_attribsopt) → {WebGLRenderingContext}

Gets a WebGL context. Will create a WebGL2 context if possible.

You can check if it's WebGL2 with

function isWebGL2(gl) {
return gl.getParameter(gl.VERSION).indexOf("WebGL 2.0 ") == 0;
}

Note: For a WebGL1 context will attempt to enable Vertex Array Objects
and add WebGL2 entry points. (unless you first set defaults with
twgl.setDefaults({enableVertexArrayObjects: false});

Parameters:
Name Type Attributes Description
canvas HTMLCanvasElement

a canvas element.

opt_attribs WebGLContextAttributes <optional>

optional webgl context creation attributes

Returns:
Type:
WebGLRenderingContext

The created context.

(static) glEnumToString(gl, value) → {string}

Gets a string for WebGL enum

Note: Several enums are the same. Without more
context (which function) it's impossible to always
give the correct enum. As it is, for matching values
it gives all enums. Checking the WebGL2RenderingContext
that means

 0     = ZERO | POINT | NONE | NO_ERROR
 1     = ONE | LINES | SYNC_FLUSH_COMMANDS_BIT
 32777 = BLEND_EQUATION_RGB | BLEND_EQUATION_RGB
 36662 = COPY_READ_BUFFER | COPY_READ_BUFFER_BINDING
 36663 = COPY_WRITE_BUFFER | COPY_WRITE_BUFFER_BINDING
 36006 = FRAMEBUFFER_BINDING | DRAW_FRAMEBUFFER_BINDING

It's also not useful for bits really unless you pass in individual bits.
In other words

const bits = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;
twgl.glEnumToString(gl, bits);  // not going to work

Note that some enums only exist on extensions. If you
want them to show up you need to pass the extension at least
once. For example

const ext = gl.getExtension('WEBGL_compressed_texture_s3tc');
if (ext) {
   twgl.glEnumToString(ext, 0);  // just prime the function

   ..later..

   const internalFormat = ext.COMPRESSED_RGB_S3TC_DXT1_EXT;
   console.log(twgl.glEnumToString(gl, internalFormat));

Notice I didn't have to pass the extension the second time. This means
you can have place that generically gets an enum for texture formats for example.
and as long as you primed the function with the extensions

If you're using twgl.addExtensionsToContext to enable your extensions
then twgl will automatically get the extension's enums.

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext or any extension object

value number

the value of the enum you want to look up.

Returns:
Type:
string

enum string or hex value

(static) isWebGL1(gl) → {bool}

Check if context is WebGL 1.0

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext

Returns:
Type:
bool

true if it's WebGL 1.0

(static) isWebGL2(gl) → {bool}

Check if context is WebGL 2.0

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext

Returns:
Type:
bool

true if it's WebGL 2.0

(static) resizeCanvasToDisplaySize(canvas, multiplieropt) → {boolean}

Resize a canvas to match the size it's displayed.

Parameters:
Name Type Attributes Description
canvas HTMLCanvasElement

The canvas to resize.

multiplier number <optional>

So you can pass in window.devicePixelRatio or other scale value if you want to.

Returns:
Type:
boolean

true if the canvas was resized.

(static) resizeFramebufferInfo(gl, framebufferInfo, attachmentsopt, widthopt, heightopt)

Resizes the attachments of a framebuffer.

You need to pass in the same attachments as you passed in module:twgl.createFramebufferInfo
because TWGL has no idea the format/type of each attachment.

The simplest usage

// create an RGBA/UNSIGNED_BYTE texture and DEPTH_STENCIL renderbuffer
const fbi = twgl.createFramebufferInfo(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
const attachments = [
  { format: RGB565, mag: NEAREST },
  { format: STENCIL_INDEX8 },
]
const fbi = twgl.createFramebufferInfo(gl, attachments);

...

function render() {
  if (twgl.resizeCanvasToDisplaySize(gl.canvas)) {
    // resize the attachments to match
    twgl.resizeFramebufferInfo(gl, fbi, attachments);
  }
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

the WebGLRenderingContext

framebufferInfo module:twgl.FramebufferInfo

a framebufferInfo as returned from module:twgl.createFramebufferInfo.

attachments Array.<module:twgl.AttachmentOptions> <optional>

the same attachments options as passed to module:twgl.createFramebufferInfo.

width number <optional>

the width for the attachments. Default = size of drawingBuffer

height number <optional>

the height for the attachments. Default = size of drawingBuffer

(static) resizeTexture(gl, tex, options, widthopt, heightopt, depthopt)

Resizes a texture based on the options passed in.

Note: This is not a generic resize anything function.
It's mostly used by module:twgl.resizeFramebufferInfo
It will use options.src if it exists to try to determine a type
otherwise it will assume gl.UNSIGNED_BYTE. No data is provided
for the texture. Texture parameters will be set accordingly

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the texture to resize

options module:twgl.TextureOptions

A TextureOptions object with whatever parameters you want set.

width number <optional>

the new width. If not passed in will use options.width

height number <optional>

the new height. If not passed in will use options.height

depth number <optional>

the new depth. If not passed in will use options.depth

(static) setAttribInfoBufferFromArray(gl, attribInfo, array, offsetopt)

Sets the contents of a buffer attached to an attribInfo

This is helper function to dynamically update a buffer.

Let's say you make a bufferInfo

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]),
};
var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);

And you want to dynamically update the positions. You could do this

// assuming arrays.position has already been updated with new data.
twgl.setAttribInfoBufferFromArray(gl, bufferInfo.attribs.position, arrays.position);
Parameters:
Name Type Attributes Description
gl WebGLRenderingContext
attribInfo AttribInfo

The attribInfo who's buffer contents to set. NOTE: If you have an attribute prefix
the name of the attribute will include the prefix.

array ArraySpec

Note: it is arguably inefficient to pass in anything but a typed array because anything
else will have to be converted to a typed array before it can be used by WebGL. During init time that
inefficiency is usually not important but if you're updating data dynamically best to be efficient.

offset number <optional>

an optional offset into the buffer. This is only an offset into the WebGL buffer
not the array. To pass in an offset into the array itself use a typed array and create an ArrayBufferView
for the portion of the array you want to use.

   var someArray = new Float32Array(1000); // an array with 1000 floats
   var someSubArray = new Float32Array(someArray.buffer, offsetInBytes, sizeInUnits); // a view into someArray

Now you can pass someSubArray into setAttribInfoBufferFromArray`

(static) setBlockUniforms(uniformBlockInfo, values)

Sets values of a uniform block object

Parameters:
Name Type Description
uniformBlockInfo module:twgl.UniformBlockInfo

A UniformBlockInfo as returned by module:twgl.createUniformBlockInfo.

values Object.<string, ?>

A uniform name to value map where the value is correct for the given
type of uniform. So for example given a block like

  uniform SomeBlock {
    float someFloat;
    vec2 someVec2;
    vec3 someVec3Array[2];
    int someInt;
  }

You can set the values of the uniform block with

  twgl.setBlockUniforms(someBlockInfo, {
     someFloat: 12.3,
     someVec2: [1, 2],
     someVec3Array: [1, 2, 3, 4, 5, 6],
     someInt: 5,
  }

Arrays can be JavaScript arrays or typed arrays

You can also fill out structure and array values either via
shortcut. Example

// -- in shader --
struct Light {
  float intensity;
  vec4 color;
  float nearFar[2];
};
uniform Lights {
  Light lights[2];
};

// in JavaScript

twgl.setBlockUniforms(someBlockInfo, {
  lights: [
    { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },
    { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },
  ],
});

or the more traditional way

twgl.setBlockUniforms(someBlockInfo, {
  "lights[0].intensity": 5.0,
  "lights[0].color": [1, 0, 0, 1],
  "lights[0].nearFar": [0.1, 10],
  "lights[1].intensity": 2.0,
  "lights[1].color": [0, 0, 1, 1],
  "lights[1].nearFar": [0.2, 15],
});

You can also specify partial paths

twgl.setBlockUniforms(someBlockInfo, {
  'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },
});

But you can not specify leaf array indices.

twgl.setBlockUniforms(someBlockInfo, {
  'lights[1].nearFar[1]': 15,     // BAD! nearFar is a leaf
  'lights[1].nearFar': [0.2, 15], // GOOD
});

IMPORTANT!, packing in a UniformBlock is unintuitive.
For example the actual layout of someVec3Array above in memory
is 1, 2, 3, unused, 4, 5, 6, unused. twgl takes in 6 values
as shown about and copies them, skipping the padding. This might
be confusing if you're already familiar with Uniform blocks.

If you want to deal with the padding yourself you can access the array
buffer views directly. eg:

 someBlockInfo.someVec3Array.set([1, 2, 3, 0, 4, 5, 6, 0]);

Any name that doesn't match will be ignored

(static) setBuffersAndAttributes(gl, setters, buffers)

Sets attributes and buffers including the ELEMENT_ARRAY_BUFFER if appropriate

Example:

const programInfo = createProgramInfo(
    gl, ["some-vs", "some-fs");

const 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],                 },
};

const 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 equivalent 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
gl WebGLRenderingContext

A WebGLRenderingContext.

setters module:twgl.ProgramInfo | Object.<string, function()>

A ProgramInfo as returned from module:twgl.createProgramInfo or Attribute setters as returned from module:twgl.createAttributeSetters

buffers module:twgl.BufferInfo | module:twgl.VertexArrayInfo

a BufferInfo as returned from module:twgl.createBufferInfoFromArrays.
or a VertexArrayInfo as returned from module:twgl.createVertexArrayInfo

(static) setDefaults(newDefaults)

Sets various defaults for twgl.

In the interest of terseness which is kind of the point
of twgl I've integrated a few of the older functions here

Parameters:
Name Type Description
newDefaults module:twgl.Defaults

The default settings.

(static) setTextureFromArray(gl, tex, src, optionsopt)

Sets a texture from an array or typed array. If the width or height is not provided will attempt to
guess the size. See module:twgl.TextureOptions.

Parameters:
Name Type Attributes Description
gl WebGLRenderingContext

the WebGLRenderingContext

tex WebGLTexture

the WebGLTexture to set parameters for

src Array.<number> | ArrayBufferView

An array or typed arry with texture data.

options module:twgl.TextureOptions <optional>

A TextureOptions object with whatever parameters you want set.
This is often the same options you passed in when you created the texture.

(static) setUniformBlock(gl, programInfo, uniformBlockInfo)

Uploads the current uniform values to the corresponding WebGLBuffer
and binds that buffer to the program's corresponding bind point for the uniform block object.

If you haven't changed any values and you only need to bind the uniform block object
call module:twgl.bindUniformBlock instead.

Parameters:
Name Type Description
gl WebGL2RenderingContext

A WebGL 2 rendering context.

programInfo module:twgl.ProgramInfo | module:twgl.UniformBlockSpec

a ProgramInfo
as returned from module:twgl.createProgramInfo or or UniformBlockSpec as
returned from module:twgl.createUniformBlockSpecFromProgram.

uniformBlockInfo module:twgl.UniformBlockInfo

a UniformBlockInfo as returned from
module:twgl.createUniformBlockInfo.

(static) setUniforms(setters, values)

Set uniforms and binds related textures.

example:

const programInfo = createProgramInfo(
    gl, ["some-vs", "some-fs"]);

const tex1 = gl.createTexture();
const tex2 = gl.createTexture();

... assume we setup the textures with data ...

const 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(programInfo.program);

This will automatically bind the textures AND set the
uniforms.

twgl.setUniforms(programInfo, uniforms);

For the example above it is equivalent to

let 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 setUniforms multiple times. For example

const uniforms = {
  u_someSampler: tex1,
  u_someOtherSampler: tex2,
};

const 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,
  ],
};

twgl.setUniforms(programInfo, uniforms);
twgl.setUniforms(programInfo, moreUniforms);

You can also add WebGLSamplers to uniform samplers as in

const uniforms = {
  u_someSampler: {
    texture: someWebGLTexture,
    sampler: someWebGLSampler,
  },
};

In which case both the sampler and texture will be bound to the
same unit.

Parameters:
Name Type Description
setters module:twgl.ProgramInfo | Object.<string, function()>

a ProgramInfo as returned from createProgramInfo or the setters returned from
createUniformSetters.

values Object.<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

const sharedUniforms = {
  u_fogNear: 10,
  u_projection: ...
  ...
};

const 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};

You can also fill out structure and array values either via
shortcut. Example

// -- in shader --
struct Light {
  float intensity;
  vec4 color;
  float nearFar[2];
};
uniform Light lights[2];

// in JavaScript

twgl.setUniforms(programInfo, {
  lights: [
    { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.1, 10] },
    { intensity: 2.0, color: [0, 0, 1, 1], nearFar[0.2, 15] },
  ],
});

or the more traditional way

twgl.setUniforms(programInfo, {
  "lights[0].intensity": 5.0,
  "lights[0].color": [1, 0, 0, 1],
  "lights[0].nearFar": [0.1, 10],
  "lights[1].intensity": 2.0,
  "lights[1].color": [0, 0, 1, 1],
  "lights[1].nearFar": [0.2, 15],
});

You can also specify partial paths

twgl.setUniforms(programInfo, {
  'lights[1]': { intensity: 5.0, color: [1, 0, 0, 1], nearFar[0.2, 15] },
});

But you can not specify leaf array indices

twgl.setUniforms(programInfo, {
  'lights[1].nearFar[1]': 15,     // BAD! nearFar is a leaf
  'lights[1].nearFar': [0.2, 15], // GOOD
});

(inner) createContext(canvas) → {WebGLRenderingContext}

Creates a webgl context.

Will return a WebGL2 context if possible.

You can check if it's WebGL2 with

twgl.isWebGL2(gl);
Parameters:
Name Type Description
canvas HTMLCanvasElement

The canvas tag to get
context from. If one is not passed in one will be
created.

Returns:
Type:
WebGLRenderingContext

The created context.

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 module:twgl.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 numComponents if not specified based on name.

    If coord is in the name assumes numComponents = 2

    If color is in the name assumes numComponents = 4

    otherwise assumes numComponents = 3

Objects with various fields. See module:twgl.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:

ArraySpec

An individual array in module:twgl.Arrays

When passed to module:twgl.createBufferInfoFromArrays if an ArraySpec is number[] or ArrayBufferView
the types will be guessed based on the name. indices will be Uint16Array, everything else will
be Float32Array. If an ArraySpec is a number it's the number of floats for an empty (zeroed) buffer.

Type:

AttachmentOptions

The options for a framebuffer attachment.

Note: For a format that is a texture include all the texture
options from module:twgl.TextureOptions for example
min, mag, clamp, etc... Note that unlike module:twgl.TextureOptions
auto defaults to false for attachment textures but min and mag default
to gl.LINEAR and wrap defaults to CLAMP_TO_EDGE

Properties:
Name Type Attributes Description
attachmentPoint number <optional>

The attachment point. Defaults
to gl.COLOR_ATTACHMENT0 + ndx unless type is a depth or stencil type
then it's gl.DEPTH_ATTACHMENT or gl.DEPTH_STENCIL_ATTACHMENT depending
on the format or attachment type.

format number <optional>

The format. If one of gl.RGBA4,
gl.RGB565, gl.RGB5_A1, gl.DEPTH_COMPONENT16,
gl.STENCIL_INDEX8 or gl.DEPTH_STENCIL then will create a
renderbuffer. Otherwise will create a texture. Default = gl.RGBA

type number <optional>

The type. Used for texture. Default = gl.UNSIGNED_BYTE.

target number <optional>

The texture target for gl.framebufferTexture2D.
Defaults to gl.TEXTURE_2D. Set to appropriate face for cube maps.

samples number <optional>

The number of samples. Default = 1

level number <optional>

level for gl.framebufferTexture2D. Defaults to 0.

layer number <optional>

layer for gl.framebufferTextureLayer. Defaults to undefined.
If set then gl.framebufferTextureLayer is called, if not then gl.framebufferTexture2D

attachment WebGLRenderbuffer | WebGLTexture <optional>

An existing renderbuffer or texture.
If provided will attach this Object. This allows you to share
attachments across framebuffers.

Mixes In:
Type:
  • Object

AttribInfo

The info for an attribute. This is effectively just the arguments to gl.vertexAttribPointer plus the WebGLBuffer
for the attribute.

Properties:
Name Type Attributes Description
value Array.<number> | ArrayBufferView <optional>

a constant value for the attribute. Note: if this is set the attribute will be
disabled and set to this constant value and all other values will be ignored.

numComponents number <optional>

the number of components for this attribute.

size number <optional>

synonym for numComponents.

type number <optional>

the type of the attribute (eg. gl.FLOAT, gl.UNSIGNED_BYTE, etc...) Default = gl.FLOAT

normalize boolean <optional>

whether or not to normalize the data. Default = false

offset number <optional>

offset into buffer in bytes. Default = 0

stride number <optional>

the stride in bytes per element. Default = 0

divisor number <optional>

the divisor in instances. Default = 0.
Requires WebGL2 or the ANGLE_instanced_arrays extension.
and, if you're using WebGL1 you must have called module:twgl.addExtensionsToContext

buffer WebGLBuffer

the buffer that contains the data for this attribute

drawType number <optional>

the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW

Type:
  • Object

BlockSpec

The specification for one UniformBlockObject

Properties:
Name Type Description
index number

The index of the block.

size number

The size in bytes needed for the block

uniformIndices Array.<number>

The indices of the uniforms used by the block. These indices
correspond to entries in a UniformData array in the module:twgl.UniformBlockSpec.

usedByVertexShader bool

Self explanatory

usedByFragmentShader bool

Self explanatory

used bool

Self explanatory

Type:
  • Object

BufferInfo

Properties:
Name Type Attributes Description
numElements number

The number of elements to pass to gl.drawArrays or gl.drawElements.

elementType number <optional>

The type of indices UNSIGNED_BYTE, UNSIGNED_SHORT etc..

indices WebGLBuffer <optional>

The indices ELEMENT_ARRAY_BUFFER if any indices exist.

attribs Object.<string, module:twgl.AttribInfo> <optional>

The attribs appropriate to call setAttributes

Type:
  • Object

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.

tex WebGLTexture

the texture.

imgs Array.<HTMLImageElement>

the images for each face.

Defaults

Various default settings for twgl.

Note: You can call this any number of times. Example:

twgl.setDefaults({ textureColor: [1, 0, 0, 1] });
twgl.setDefaults({ attribPrefix: 'a_' });

is equivalent to

twgl.setDefaults({
  textureColor: [1, 0, 0, 1],
  attribPrefix: 'a_',
});
Properties:
Name Type Attributes Description
attribPrefix string <optional>

The prefix to stick on attributes

When writing shaders I prefer to name attributes with a_, uniforms with u_ and varyings with v_
as it makes it clear where they came from. But, when building geometry I prefer using un-prefixed names.

In other words I'll create arrays of geometry like this

  const arrays = {
    position: ...
    normal: ...
    texcoord: ...
  };

But need those mapped to attributes and my attributes start with a_.

Default: ""

textureColor Array.<number> <optional>

Array of 4 values in the range 0 to 1

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.

Default: [0.5, 0.75, 1, 1]

crossOrigin string <optional>

If not undefined sets the crossOrigin attribute on images
that twgl creates when downloading images for textures.

Also see module:twgl.TextureOptions.

addExtensionsToContext bool <optional>

If true, then, when twgl will try to add any supported WebGL extensions
directly to the context under their normal GL names. For example
if ANGLE_instances_arrays exists then twgl would enable it,
add the functions vertexAttribDivisor, drawArraysInstanced,
drawElementsInstanced, and the constant VERTEX_ATTRIB_ARRAY_DIVISOR
to the WebGLRenderingContext.

Type:
  • Object

DrawObject

A DrawObject is useful for putting objects in to an array and passing them to module:twgl.drawObjectList.

You need either a BufferInfo or a VertexArrayInfo.

Properties:
Name Type Attributes Description
active boolean <optional>

whether or not to draw. Default = true (must be false to be not true). In other words undefined = true

type number <optional>

type to draw eg. gl.TRIANGLES, gl.LINES, etc...

programInfo module:twgl.ProgramInfo

A ProgramInfo as returned from module:twgl.createProgramInfo

bufferInfo module:twgl.BufferInfo <optional>

A BufferInfo as returned from module:twgl.createBufferInfoFromArrays

vertexArrayInfo module:twgl.VertexArrayInfo <optional>

A VertexArrayInfo as returned from module:twgl.createVertexArrayInfo

uniforms Object.<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],
};
offset number <optional>

the offset to pass to gl.drawArrays or gl.drawElements. Defaults to 0.

count number <optional>

the count to pass to gl.drawArrays or gl.drawElements. Defaults to bufferInfo.numElements.

instanceCount number <optional>

the number of instances. Defaults to undefined.

Type:
  • Object

ErrorCallback(msg, lineOffsetopt)

Error Callback

Parameters:
Name Type Attributes Description
msg string

error message.

lineOffset number <optional>

amount to add to line number

FramebufferInfo

Properties:
Name Type Description
framebuffer WebGLFramebuffer

The WebGLFramebuffer for this framebufferInfo

attachments Array.<(WebGLRenderbuffer|WebGLTexture)>

The created attachments in the same order as passed in to module:twgl.createFramebufferInfo.

width number

The width of the framebuffer and its attachments

height number

The width of the framebuffer and its attachments

Type:
  • Object

FullArraySpec

Use this type of array spec when TWGL can't guess the type or number of components of an array

Properties:
Name Type Attributes Description
value Array.<number> | ArrayBufferView <optional>

a constant value for the attribute. Note: if this is set the attribute will be
disabled and set to this constant value and all other values will be ignored.

data number | Array.<number> | ArrayBufferView <optional>

The data of the array. A number alone becomes the number of elements of type.

numComponents number <optional>

number of components for vertexAttribPointer. Default is based on the name of the array.
If coord is in the name assumes numComponents = 2.
If color is in the name assumes numComponents = 4.
otherwise assumes numComponents = 3

type number | TypedArrayConstructor <optional>

type. This is used if data is a JavaScript array, or buffer is passed in, or data is a number.
It can either be the constructor for a typedarray. (eg. Uint8Array) OR a WebGL type, (eg gl.UNSIGNED_BYTE).
For example if you want colors in a Uint8Array you might have a FullArraySpec like { type: gl.UNSIGNED_BYTE, data: [255,0,255,255, ...], }.

size number <optional>

synonym for numComponents.

normalize boolean <optional>

normalize for vertexAttribPointer. Default is true if type is Int8Array or Uint8Array otherwise false.

stride number <optional>

stride for vertexAttribPointer. Default = 0

offset number <optional>

offset for vertexAttribPointer. Default = 0

divisor number <optional>

divisor for vertexAttribDivisor. Default = 0.
Requires WebGL2 or the ANGLE_instanced_arrays extension.
and, if you using WebGL1 you must have called module:twgl.addExtensionsToContext

attrib string <optional>

name of attribute this array maps to. Defaults to same name as array prefixed by the default attribPrefix.

name string <optional>

synonym for attrib.

attribName string <optional>

synonym for attrib.

buffer WebGLBuffer <optional>

Buffer to use for this attribute. This lets you use your own buffer
but you will need to supply numComponents and type. You can effectively pass an AttribInfo
to provide this. Example:

    const bufferInfo1 = twgl.createBufferInfoFromArrays(gl, {
      position: [1, 2, 3, ... ],
    });
    const bufferInfo2 = twgl.createBufferInfoFromArrays(gl, {
      position: bufferInfo1.attribs.position,  // use the same buffer from bufferInfo1
    });
drawType number <optional>

the draw type passed to gl.bufferData. Default = gl.STATIC_DRAW

Type:
  • Object

FullProgramSpec

Properties:
Name Type Attributes Description
shaders Array.<string>

the shader source or element ids.

errorCallback function <optional>

callback for errors

attribLocations Object.<string, number> | Array.<string> <optional>

a attribute name to location map, or array of attribute names where index = location.

transformFeedbackVaryings module:twgl.BufferInfo | Object.<string, module:twgl.AttribInfo> | Array.<string> <optional>

If passed
a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise
you can pass an array of names.

transformFeedbackMode number <optional>

the mode to pass gl.transformFeedbackVaryings. Defaults to SEPARATE_ATTRIBS.

callback ProgramCallback <optional>

callback for async program compilation.

Type:
  • Object

ProgramInfo

Properties:
Name Type Attributes Description
program WebGLProgram

A shader program

uniformSetters Object.<string, function()>

object of setters as returned from createUniformSetters,

attribSetters Object.<string, function()>

object of setters as returned from createAttribSetters,

uniformBlockSpec module:twgl.UniformBlockSpec <optional>

a uniform block spec for making UniformBlockInfos with createUniformBlockInfo etc..

transformFeedbackInfo Object.<string, module:twgl.TransformFeedbackInfo> <optional>

info for transform feedbacks

Type:
  • Object

ProgramOptions

Properties:
Name Type Attributes Description
errorCallback function <optional>

callback for errors

attribLocations Object.<string, number> | Array.<string> <optional>

a attribute name to location map, or array of attribute names where index = location.

transformFeedbackVaryings module:twgl.BufferInfo | Object.<string, module:twgl.AttribInfo> | Array.<string> <optional>

If passed
a BufferInfo will use the attribs names inside. If passed an object of AttribInfos will use the names from that object. Otherwise
you can pass an array of names.

transformFeedbackMode number <optional>

the mode to pass gl.transformFeedbackVaryings. Defaults to SEPARATE_ATTRIBS.

callback ProgramCallback <optional>

callback for async program compilation.

Type:
  • Object

ProgramSpec

Type:

TextureFunc(gl, options) → {*}

A function to generate the source for a texture.

Parameters:
Name Type Description
gl WebGLRenderingContext

A WebGLRenderingContext

options module:twgl.TextureOptions

the texture options

Returns:
Type:
*

Returns any of the things documented for src for module:twgl.TextureOptions.

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.

Note: A TexImageSource is defined in the WebGL spec as a HTMLImageElement, HTMLVideoElement,
HTMLCanvasElement, ImageBitmap, or ImageData.

Properties:
Name Type Attributes Description
target number <optional>

the type of texture gl.TEXTURE_2D or gl.TEXTURE_CUBE_MAP. Defaults to gl.TEXTURE_2D.

level number <optional>

the mip level to affect. Defaults to 0. Note, if set auto will be considered false unless explicitly set to true.

width number <optional>

the width of the texture. Only used if src is an array or typed array or null.

height number <optional>

the height of a texture. Only used if src is an array or typed array or null.

depth number <optional>

the depth of a texture. Only used if src is an array or type array or null and target is TEXTURE_3D .

min number <optional>

the min filter setting (eg. gl.LINEAR). Defaults to gl.NEAREST_MIPMAP_LINEAR
or if texture is not a power of 2 on both dimensions then defaults to gl.LINEAR.

mag number <optional>

the mag filter setting (eg. gl.LINEAR). Defaults to gl.LINEAR

minMag number <optional>

both the min and mag filter settings.

internalFormat number <optional>

internal format for texture. Defaults to gl.RGBA

format number <optional>

format for texture. Defaults to gl.RGBA.

type number <optional>

type for texture. Defaults to gl.UNSIGNED_BYTE unless src is ArrayBufferView. If src
is ArrayBufferView defaults to type that matches ArrayBufferView type.

wrap number <optional>

Texture wrapping for both S and T (and R if TEXTURE_3D or WebGLSampler). Defaults to gl.REPEAT for 2D unless src is WebGL1 and src not npot and gl.CLAMP_TO_EDGE for cube

wrapS number <optional>

Texture wrapping for S. Defaults to gl.REPEAT and gl.CLAMP_TO_EDGE for cube. If set takes precedence over wrap.

wrapT number <optional>

Texture wrapping for T. Defaults to gl.REPEAT and gl.CLAMP_TO_EDGE for cube. If set takes precedence over wrap.

wrapR number <optional>

Texture wrapping for R. Defaults to gl.REPEAT and gl.CLAMP_TO_EDGE for cube. If set takes precedence over wrap.

minLod number <optional>

TEXTURE_MIN_LOD setting

maxLod number <optional>

TEXTURE_MAX_LOD setting

baseLevel number <optional>

TEXTURE_BASE_LEVEL setting

maxLevel number <optional>

TEXTURE_MAX_LEVEL setting

compareFunc number <optional>

TEXTURE_COMPARE_FUNC setting

compareMode number <optional>

TEXTURE_COMPARE_MODE setting

unpackAlignment number <optional>

The gl.UNPACK_ALIGNMENT used when uploading an array. Defaults to 1.

color Array.<number> | ArrayBufferView <optional>

Color to initialize this texture with if loading an image asynchronously.
The default use a blue 1x1 pixel texture. You can set another default by calling twgl.setDefaults
or you can set an individual texture's initial color by setting this property. Example: [1, .5, .5, 1] = pink

premultiplyAlpha number <optional>

Whether or not to premultiply alpha. Defaults to whatever the current setting is.
This lets you set it once before calling twgl.createTexture or twgl.createTextures and only override
the current setting for specific textures.

flipY number <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.createTexture or twgl.createTextures and only override
the current setting for specific textures.

colorspaceConversion number <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.createTexture or twgl.createTextures and only override
the current setting for specific textures.

auto boolean <optional>

If undefined or true, in WebGL1, texture filtering is set automatically for non-power of 2 images and
mips are generated for power of 2 images. In WebGL2 mips are generated if they can be. Note: if level is set above
then then auto is assumed to be false unless explicity set to true.

cubeFaceOrder Array.<number> <optional>

The order that cube faces are pulled 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]
src Array.<number> | ArrayBufferView | TexImageSource | Array.<TexImageSource> | string | Array.<string> | module:twgl.TextureFunc <optional>

source for texture

If string then it's assumed to be a URL to an image. The image will be downloaded async. A usable
1x1 pixel texture will be returned immediately. The texture will be updated once the image has downloaded.
If target is gl.TEXTURE_CUBE_MAP will attempt to divide image into 6 square pieces. 1x6, 6x1, 3x2, 2x3.
The pieces will be uploaded in cubeFaceOrder

If string[] or TexImageSource[] and target is gl.TEXTURE_CUBE_MAP then it must have 6 entries, one for each face of a cube map.

If string[] or TexImageSource[] and target is gl.TEXTURE_2D_ARRAY then each entry is a slice of the a 2d array texture
and will be scaled to the specified width and height OR to the size of the first image that loads.

If TexImageSource then it wil be used immediately to create the contents of the texture. Examples HTMLImageElement,
HTMLCanvasElement, HTMLVideoElement.

If number[] or ArrayBufferView it's assumed to be data for a texture. If width or height is
not specified it is guessed as follows. First the number of elements is computed by src.length / numComponents
where numComponents is derived from format. If target is gl.TEXTURE_CUBE_MAP then numElements is divided
by 6. Then

  • If neither width nor height are specified and sqrt(numElements) is an integer then width and height
    are set to sqrt(numElements). Otherwise width = numElements and height = 1.

  • If only one of width or height is specified then the other equals numElements / specifiedDimension.

If number[] will be converted to type.

If src is a function it will be called with a WebGLRenderingContext and these options.
Whatever it returns is subject to these rules. So it can return a string url, an HTMLElement
an array etc...

If src is undefined then an empty texture will be created of size width by height.

crossOrigin string <optional>

What to set the crossOrigin property of images when they are downloaded.
default: undefined. Also see module:twgl.setDefaults.

Type:
  • Object

TextureReadyCallback(err, texture, source)

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.

texture WebGLTexture

the texture.

source module:twgl.TextureSrc

image(s) used to as the src for the texture

TextureSrc

The src image(s) used to create a texture.

When you call module:twgl.createTexture or module:twgl.createTextures
you can pass in urls for images to load into the textures. If it's a single url
then this will be a single HTMLImageElement. If it's an array of urls used for a cubemap
this will be a corresponding array of images for the cubemap.

Type:
  • HTMLImageElement | Array.<HTMLImageElement>

TexturesReadyCallback(err, textures, sources)

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.

textures Object.<string, WebGLTexture>

the created textures by name. Same as returned by module:twgl.createTextures.

sources Object.<string, module:twgl.TextureSrc>

the image(s) used for the texture by name.

ThreeDReadyCallback(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.

tex WebGLTexture

the texture.

imgs Array.<HTMLImageElement>

the images for each slice.

TransformFeedbackInfo

Properties:
Name Type Description
index number

index of transform feedback

type number

GL type

size number

1 - 4

Type:
  • Object

UniformBlockInfo

Represents a UniformBlockObject including an ArrayBuffer with all the uniform values
and a corresponding WebGLBuffer to hold those values on the GPU

Properties:
Name Type Attributes Description
name string

The name of the block

array ArrayBuffer

The array buffer that contains the uniform values

asFloat Float32Array

A float view on the array buffer. This is useful
inspecting the contents of the buffer in the debugger.

buffer WebGLBuffer

A WebGL buffer that will hold a copy of the uniform values for rendering.

offset number <optional>

offset into buffer

uniforms Object.<string, ArrayBufferView>

A uniform name to ArrayBufferView map.
each Uniform has a correctly typed ArrayBufferView into array at the correct offset
and length of that uniform. So for example a float uniform would have a 1 float Float32Array
view. A single mat4 would have a 16 element Float32Array view. An ivec2 would have an
Int32Array view, etc.

setters Object.<string, function()>

A setter for this uniform.
The reason to use setters is elements of arrays are padded to vec4 sizes which
means if you want to set an array of 4 floats you'd need to set 16 values
(or set elements 0, 4, 8, 12). In other words
someBlockInfo.uniforms.some4FloatArrayUniform.set([0, , , , 1, , , , 2, , , , 3])
where as the setter handles just passing in [0, 1, 2, 3] either directly as in
someBlockInfo.setter.some4FloatArrayUniform.set([0, 1, 2, 3]) (not recommended)
or via module:twgl.setBlockUniforms

Type:
  • Object

UniformBlockSpec

A UniformBlockSpec represents the data needed to create and bind
UniformBlockObjects for a given program

Properties:
Name Type Description
blockSpecs Object.<string, module:twgl.BlockSpec>

The BlockSpec for each block by block name

uniformData Array.<UniformData>

An array of data for each uniform by uniform index.

Type:
  • Object

UniformData

Properties:
Name Type Description
name string

The name of the uniform

type number

The WebGL type enum for this uniform

size number

The number of elements for this uniform

blockNdx number

The block index this uniform appears in

offset number

The byte offset in the block for this uniform's value

Type:
  • Object

VertexArrayInfo

Properties:
Name Type Attributes Description
numElements number

The number of elements to pass to gl.drawArrays or gl.drawElements.

elementType number <optional>

The type of indices UNSIGNED_BYTE, UNSIGNED_SHORT etc..

vertexArrayObject WebGLVertexArrayObject <optional>

a vertex array object

Type:
  • Object