Module: webgl-utils

webgl-utils

Methods

createAttribsFromArrays(gl, arrays, opt_mapping) → {Object.<string, module:webgl-utils.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 = {
   a_position: { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   a_texcoord: { numComponents: 2, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   a_normal:   { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   a_color:    { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true,  buffer: WebGLBuffer, },
 };
Parameters:
Name Type Argument Description
gl WebGLRenderingContext

The webgl rendering context.

arrays Object.<string, (array|typedarray)>

The arrays

opt_mapping Object.<string, string> <optional>

mapping from attribute name to array name.
if not specified defaults to "a_name" -> "name".

Returns:

the attribs

Type
Object.<string, module:webgl-utils.AttribInfo>

createAttributeSetters(program) → {Object.<string, function()>}

Creates setter functions for all attributes of a shader
program. You can pass this to module:webgl-utils.setBuffersAndAttributes to set all your buffers and attributes.

Parameters:
Name Type Description
program WebGLProgram

the program to create setters for.

See:
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 push function attached
so that you can easily push values.

push can 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 numComponents and numElements properties.

Parameters:
Name Type Description
numComponents number

number of components

numElements number

number of elements. The total size of the array will be numComponents * numElements.

opt_type constructor

A constructor for the type. Default = Float32Array.

Returns:

A typed array.

Type
ArrayBuffer

createBufferInfoFromArrays(gl, arrays, opt_mapping) → {module:webgl-utils.BufferInfo}

Creates a BufferInfo from an object of arrays.

This can be passed to module:webgl-utils.setBuffersAndAttributes and to
module:webgl-utils: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 Argument Description
gl WebGLRenderingContext

A WebGLRenderingContext

arrays Object.<string, (array|object|typedarray)>

Your data

opt_mapping Object.<string, string> <optional>

an optional mapping of attribute to array name.
If not passed in it's assumed the array names will be mapped to an attibute
of the same name with "a_" prefixed to it. An other words.

   var arrays = {
      position: ...,
      texcoord: ...,
      normal:   ...,
      indices:  ...,
   };

   bufferInfo = createBufferInfoFromArrays(gl, arrays);

Is the same as

   var arrays = {
      position: ...,
      texcoord: ...,
      normal:   ...,
      indices:  ...,
   };

   var mapping = {
     a_position: "position",
     a_texcoord: "texcoord",
     a_normal:   "normal",
   };

   bufferInfo = createBufferInfoFromArrays(gl, arrays, mapping);
Returns:

A BufferInfo

Type
module:webgl-utils.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.

arrays Object.<string, (array|typedarray)>
Returns:

returns an object with one WebGLBuffer per array

Type
Object.<string, WebGLBuffer>

createProgram(shaders, opt_attribs, opt_locations, opt_errorCallback)

Creates a program, attaches shaders, binds attrib locations, links the
program and calls useProgram.

Parameters:
Name Type Argument Description
shaders Array.<WebGLShader>

The shaders to attach

opt_attribs Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.ErrorCallback

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.

createProgramFromScripts(gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) → {WebGLProgram}

Creates a program from 2 script tags.

Parameters:
Name Type Argument Description
gl WebGLRenderingContext

The WebGLRenderingContext
to use.

shaderScriptIds Array.<string>

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_attribs Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.ErrorCallback

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

The WebGLRenderingContext
to use.

shaderSourcess Array.<string>

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

opt_attribs Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.ErrorCallback

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) → {module:webgl-utils.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
gl WebGLRenderingContext

The WebGLRenderingContext
to use.

shaderSourcess 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 Array.<string> <optional>

An array of attribs names. Locations will be assigned by index if not passed in

opt_locations Array.<number> <optional>

The locations for the. A parallel array to opt_attribs letting you assign locations.

opt_errorCallback module:webgl-utils.ErrorCallback

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
module:webgl-utils.ProgramInfo

createUniformSetters(program) → {Object.<string, function()>}

Creates setter functions for all uniforms of a shader
program.

Parameters:
Name Type Description
program WebGLProgram

the program to create setters for.

See:
Returns:

an object with a setter by name for each uniform

Type
Object.<string, function()>

drawBufferInfo(gl, bufferInfo, primitiveType, count, offset)

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 Argument Description
gl WebGLRenderingContext

A WebGLRenderingContext

bufferInfo module:webgl-utils.BufferInfo

as returned from createBufferInfoFromArrays

primitiveType enum <optional>

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

count number <optional>

An optional count. Defaults to bufferInfo.numElements

offset number <optional>

An optional offset. Defaults to 0.

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.

getExtensionWithKnownPrefixes(name) → {WebGLExtension}

Given an extension name like WEBGL_compressed_texture_s3tc
returns the supported version extension, like
WEBKIT_WEBGL_compressed_teture_s3tc

Parameters:
Name Type Description
name string

Name of extension to look for

Returns:

The extension or undefined if not
found.

Type
WebGLExtension

resizeCanvasToDisplaySize(canvas, multiplier) → {boolean}

Resize a canvas to match the size its displayed.

Parameters:
Name Type Argument Description
canvas HTMLCanvasElement

The canvas to resize.

multiplier number <optional>

amount to multiply by.
Pass in window.devicePixelRatio for native pixels.

Returns:

true if the canvas was resized.

Type
boolean

setAttributes(setters, attribs)

Sets attributes and binds buffers (deprecated... use module:webgl-utils.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
setters Object.<string, function()>| model:webgl-utils.ProgramInfo

Attribute setters as returned from createAttributeSetters or a ProgramInfo as returned module:webgl-utils.createProgramInfo

attribs Object.<string, module:webgl-utils.AttribInfo>

AttribInfos mapped by attribute name.

Deprecated:

setBuffersAndAttributes(gl, setters, buffers)

Sets attributes and buffers including the ELEMENT_ARRAY_BUFFER if appropriate

Example:

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(programInfo.attribSetters, 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
gl WebGLRenderingContext

A WebGLRenderingContext.

setters Object.<string, function()>

Attribute setters as returned from createAttributeSetters

buffers module:webgl-utils.BufferInfo

a BufferInfo as returned from createBufferInfoFromArrays.

setUniforms(setters, an)

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

var 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.uniformSetters, uniforms);
setUniforms(programInfo.uniformSetters, moreUniforms);
Parameters:
Name Type Description
setters Object.<string, function()>| module:webgl-utils.ProgramInfo

the setters returned from
createUniformSetters or a ProgramInfo from module:webgl-utils.createProgramInfo.

an Object.<string, value>

object with values for the
uniforms.

Type Definitions

AttribInfo

Type:
  • Object
Properties:
Name Type Argument Description
numComponents number <optional>

the number of components for this attribute.

size number <optional>

the number of components for this attribute.

type number <optional>

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

normalized 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

buffer WebGLBuffer

the buffer that contains the data for this attribute

BufferInfo

Type:
  • Object
Properties:
Name Type Argument Description
numElements number

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

indices WebGLBuffer <optional>

The indices ELEMENT_ARRAY_BUFFER if any indices exist.

attribs Object.<string, module:webgl-utils.AttribInfo>

The attribs approriate to call setAttributes

DrawObject

Type:
  • Object
Properties:
Name Type Description
programInfo module:webgl-utils.ProgramInfo

A ProgramInfo as returned from createProgramInfo

bufferInfo module:webgl-utils.BufferInfo

A BufferInfo as returned from createBufferInfoFromArrays

uniforms Object.<string, ?>

The values for the uniforms

ErrorCallback(msg)

Error Callback

Parameters:
Name Type Description
msg string

error message.

ProgramInfo

Type:
  • Object
Properties:
Name Type 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,

Setters

Type:
  • Object.<string, function()>
copyright Gregg Tavares