### Basic TWGL WebGL Example
Source: https://twgljs.org/docs/index
This example demonstrates the fundamental usage of TWGL to set up a WebGL canvas, compile shaders, create buffers, and render a simple scene. It includes canvas setup, TWGL script inclusion, context retrieval, program info creation, buffer creation, and a render loop with animation.
```html
```
--------------------------------
### Textures Ready Callback Example
Source: https://twgljs.org/docs/module-twgl
Defines a callback function that is executed once multiple textures (e.g., from `twgl.createTextures`) have finished downloading and uploading. It receives an error object, an object of created WebGLTextures, and an object of the source images.
```javascript
function handleTexturesReady(err, textures, sources) {
if (err) {
console.error('Error loading textures:', err);
return;
}
console.log('Textures loaded:', textures, 'from sources:', sources);
}
```
--------------------------------
### TWGL.js Uniforms Example
Source: https://twgljs.org/docs/module-twgl
Demonstrates how to pass uniforms to TWGL.js draw calls. It shows how to combine shared and local uniforms into an array for the uniforms property.
```javascript
var sharedUniforms = {
u_fogNear: 10,
u_projection: ...
};
var localUniforms = {
u_world: ...
u_diffuseColor: ...
};
var drawObj = {
...
uniforms: [sharedUniforms, localUniforms],
};
```
--------------------------------
### Texture Ready Callback Example
Source: https://twgljs.org/docs/module-twgl
Defines a callback function that is executed once a texture has finished downloading and uploading. It receives an error object (if any), the created WebGLTexture, and the source image(s) used.
```javascript
function handleTextureReady(err, texture, source) {
if (err) {
console.error('Error loading texture:', err);
return;
}
console.log('Texture loaded:', texture, 'from source:', source);
}
```
--------------------------------
### TWGL.js Buffer Reuse Example
Source: https://twgljs.org/docs/module-twgl
Illustrates how to reuse a WebGLBuffer between different TWGL.js buffer configurations. This is useful for optimizing buffer management.
```javascript
const bufferInfo1 = twgl.createBufferInfoFromArrays(gl, {
position: [1, 2, 3, ... ],
});
const bufferInfo2 = twgl.createBufferInfoFromArrays(gl, {
position: bufferInfo1.attribs.position, // use the same buffer from bufferInfo1
});
```
--------------------------------
### twgl.createVAOFromBufferInfo
Source: https://twgljs.org/docs/module-twgl_vertexArrays
Creates a Vertex Array Object (VAO) using provided buffer information and program details. This simplifies VAO setup when working with buffer infos.
```APIDOC
## POST /twgl/vertexArrays/createVAOFromBufferInfo
### Description
Creates a vertex array object and then sets the attributes on it using buffer and program information. This is a convenience function for setting up VAOs.
### Method
POST
### Endpoint
/twgl/vertexArrays/createVAOFromBufferInfo
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **gl** (WebGLRenderingContext) - Required - The WebGLRenderingContext to use.
- **programInfo** (module:twgl.ProgramInfo) - Required - Program information, typically as returned from `createProgramInfo` or attribute setters from `createAttributeSetters`.
- **bufferInfo** (module:twgl.BufferInfo) - Required - Buffer information, typically as returned from `createBufferInfoFromArrays` etc.
- **indices** (WebGLBuffer) - Optional - An optional ELEMENT_ARRAY_BUFFER of indices.
### Request Example
```json
{
"gl": "",
"programInfo": {
"program": "",
"attribs": {
"a_position": {
"location": 0
},
"a_texCoord": {
"location": 1
}
},
"uniforms": {
"u_matrix": {
"location": 0
}
}
},
"bufferInfo": {
"attribs": {
"position": {
"buffer": "",
"size": 3,
"offset": 0,
"type": 34962,
"normalized": false,
"stride": 0,
"divisor": 0
},
"texcoord": {
"buffer": "",
"size": 2,
"offset": 12,
"type": 34962,
"normalized": false,
"stride": 0,
"divisor": 0
}
},
"indices": {
"buffer": "",
"numElements": 6
},
"vertexArrayObject": ""
},
"indices": ""
}
```
### Response
#### Success Response (200)
- **vertexArrayObject** (WebGLVertexArrayObject | null) - The created WebGLVertexArrayObject or null if creation failed.
#### Response Example
```json
{
"vertexArrayObject": ""
}
```
```
--------------------------------
### Matrix Multiplication with twgl/m4
Source: https://twgljs.org/docs/module-twgl_m4
Illustrates how to perform matrix multiplication using twgl/m4. This example shows multiplying an identity matrix by a translation matrix and storing the result back into the original matrix.
```javascript
const mat = m4.identity();
const trans = m4.translation([1, 2, 3]);
m4.multiply(mat, trans, mat); // Multiplies mat * trans and puts result in mat.
```
--------------------------------
### Create Framebuffers and Attachments with TWGL and WebGL
Source: https://twgljs.org/docs/index
Demonstrates creating framebuffers with attachments using both TWGL's utility functions and raw WebGL commands. TWGL simplifies the process by abstracting away many low-level details.
```javascript
const attachments = [
{ format: RGBA, type: UNSIGNED_BYTE, min: LINEAR, wrap: CLAMP_TO_EDGE },
{ format: DEPTH_STENCIL, },
];
const fbi = twgl.createFramebufferInfo(gl, attachments);
```
```javascript
const fb = gl.createFramebuffer(gl.FRAMEBUFFER);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.drawingBufferWidth, gl.drawingBufferHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
const rb = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, rb);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, rb);
```
--------------------------------
### Texture Format and Type Utilities
Source: https://twgljs.org/docs/module-twgl_textures
Utility functions to get information about texture formats and components.
```APIDOC
## GET getBytesPerElementForInternalFormat
### Description
Gets the number of bytes per element for a given internalFormat and type.
### Method
GET
### Endpoint
/websites/twgljs/getBytesPerElementForInternalFormat
### Parameters
#### Query Parameters
- **internalFormat** (number) - Required - The internalFormat parameter from texImage2D etc..
- **type** (number) - Required - The type parameter for texImage2D etc..
### Response
#### Success Response (200)
- **bytesPerElement** (number) - The number of bytes per element for the given internalFormat, type combo.
### Response Example
```json
{
"bytesPerElement": 4
}
```
## GET getFormatAndTypeForInternalFormat
### Description
Gets the format and type for a given internalFormat.
### Method
GET
### Endpoint
/websites/twgljs/getFormatAndTypeForInternalFormat
### Parameters
#### Query Parameters
- **internalFormat** (number) - Required - The internal format.
### Response
#### Success Response (200)
- **format** (number) - The texture format.
- **type** (number) - The texture type.
### Response Example
```json
{
"format": 6408,
"type": 5121
}
```
## GET getNumComponentsForFormat
### Description
Gets the number of components for a given image format.
### Method
GET
### Endpoint
/websites/twgljs/getNumComponentsForFormat
### Parameters
#### Query Parameters
- **format** (number) - Required - The format.
### Response
#### Success Response (200)
- **numComponents** (number) - The number of components for the format.
### Response Example
```json
{
"numComponents": 4
}
```
```
--------------------------------
### TWGL Shader Compilation vs. Raw WebGL
Source: https://twgljs.org/docs/index
Compares the concise shader compilation process using TWGL's `createProgramInfo` with the more verbose, multi-step approach required by raw WebGL, which involves manual shader compilation and uniform/attribute location lookups.
```javascript
const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);
```
```javascript
// Note: I'm conceding that you'll likely already have the 30 lines of
// code for compiling GLSL
const program = twgl.createProgramFromScripts(gl, ["vs", "fs"]);
const u_lightWorldPosLoc = gl.getUniformLocation(program, "u_lightWorldPos");
const u_lightColorLoc = gl.getUniformLocation(program, "u_lightColor");
const u_ambientLoc = gl.getUniformLocation(program, "u_ambient");
const u_specularLoc = gl.getUniformLocation(program, "u_specular");
const u_shininessLoc = gl.getUniformLocation(program, "u_shininess");
const u_specularFactorLoc = gl.getUniformLocation(program, "u_specularFactor");
const u_diffuseLoc = gl.getUniformLocation(program, "u_diffuse");
const u_worldLoc = gl.getUniformLocation(program, "u_world");
const u_worldInverseTransposeLoc = gl.getUniformLocation(program, "u_worldInverseTranspose");
const u_viewInverseLoc = gl.getUniformLocation(program, "u_viewInverse");
const positionLoc = gl.getAttribLocation(program, "a_position");
const normalLoc = gl.getAttribLocation(program, "a_normal");
const texcoordLoc = gl.getAttribLocation(program, "a_texcoord");
```
--------------------------------
### Load Textures with WebGL
Source: https://twgljs.org/docs/index
Illustrates the manual process of creating and configuring textures using the WebGL API. This involves creating texture objects, binding them, uploading image or pixel data, generating mipmaps, and setting texture parameters.
```javascript
// Let's assume I already loaded all the images
// a power of 2 image
const hftIconTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, hftIconImg);
gl.generateMipmaps(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
// a non-power of 2 image
const cloverTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, hftIconImg);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
// From a canvas
const cloverTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, ctx.canvas);
gl.generateMipmaps(gl.TEXTURE_2D);
// A cubemap from 6 images
const yokohamaTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_CUBE_MAP, tex);
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, posXImg);
gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, negXImg);
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, posYImg);
gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, negYImg);
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, posZImg);
gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, negZImg);
gl.generateMipmaps(gl.TEXTURE_CUBE_MAP);
// A cubemap from 1 image (can be 1x6, 2x3, 3x2, 6x1)
const goldengateTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_CUBE_MAP, tex);
const size = goldengate.width / 3; // assume it's a 3x2 texture
const slices = [0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1];
const tempCtx = document.createElement("canvas").getContext("2d");
tempCtx.canvas.width = size;
tempCtx.canvas.height = size;
for (let ii = 0; ii < 6; ++ii) {
const xOffset = slices[ii * 2 + 0] * size;
const yOffset = slices[ii * 2 + 1] * size;
tempCtx.drawImage(element, xOffset, yOffset, size, size, 0, 0, size, size);
gl.texImage2D(faces[ii], 0, format, format, type, tempCtx.canvas);
}
gl.generateMipmaps(gl.TEXTURE_CUBE_MAP);
// A 2x2 pixel texture from a JavaScript array
const checkerTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([
255,255,255,255,
192,192,192,255,
192,192,192,255,
255,255,255,255,
]));
gl.generateMipmaps(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
// a 1x8 pixel texture from a typed array.
const stripeTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, 1, 8, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, new Uint8Array([
255,
128,
255,
128,
255,
128,
255,
128,
]));
gl.generateMipmaps(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
```
--------------------------------
### Create Cube Buffers (TWGL vs WebGL)
Source: https://twgljs.org/docs/index
Demonstrates creating vertex attribute arrays and then converting them into WebGL buffers. TWGL's `createBufferInfoFromArrays` simplifies this process by handling array creation and buffer binding.
```javascript
const arrays = {
position: [1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1],
normal: [1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1],
texcoord: [1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1],
indices: [0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23],
};
const bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);
```
```javascript
const positions = [1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1];
const normals = [1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1];
const texcoords = [1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1];
const indices = [0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);
const texcoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcoords), gl.STATIC_DRAW);
const indicesBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indicesBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
```
--------------------------------
### getContext
Source: https://twgljs.org/docs/module-twgl
Gets a WebGL context, attempting to create a WebGL2 context if possible. It also enables Vertex Array Objects and adds WebGL2 entry points for WebGL1 contexts by default.
```APIDOC
## getContext
### Description
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})
### Method
`getContext(canvas, opt_attribs)`
### Parameters
#### Path Parameters
- `canvas` (HTMLCanvasElement) - Required - a canvas element.
- `opt_attribs` (WebGLContextAttributes) - Optional - optional webgl context creation attributes
### Request Example
```json
{
"example": "// No request body for this function"
}
```
### Response
#### Success Response (200)
- `WebGLRenderingContext` - The created context.
#### Response Example
```json
{
"example": "// A WebGLRenderingContext object"
}
```
```
--------------------------------
### createProgramInfoAsync
Source: https://twgljs.org/docs/module-twgl_programs
Same as createProgramInfo but returns a promise. This function compiles and links shaders asynchronously.
```APIDOC
## POST /createProgramInfoAsync
### Description
Compiles and links the provided shader sources to create a WebGL program asynchronously. It returns a promise that resolves with a ProgramInfo object containing the program and setters for uniforms and attributes.
### Method
POST
### Endpoint
/createProgramInfoAsync
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **gl** (WebGLRenderingContext) - Required - The WebGLRenderingContext to use.
- **shaderSources** (Array.) - Required - 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. | 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** (Array. | module:twgl.ErrorCallback) - 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.
### Request Example
```json
{
"gl": "WebGLRenderingContext",
"shaderSources": [
"attribute vec4 position;\nvoid main() { gl_Position = position; }",
"void main() { gl_FragColor = vec4(1.0); }"
],
"opt_attribs": ["position"],
"opt_locations": [0]
}
```
### Response
#### Success Response (200)
- **program** (WebGLProgram) - The compiled and linked WebGL program.
- **uniformSetters** (object) - An object containing setters for the program's uniforms.
- **attribSetters** (object) - An object containing setters for the program's attributes
#### Response Example
```json
{
"program": "WebGLProgram",
"uniformSetters": {},
"attribSetters": {}
}
```
```
--------------------------------
### Set Uniform and UniformBlock Structures and Arrays with TWGL and WebGL
Source: https://twgljs.org/docs/index
Illustrates how to set uniform variables, including structures and arrays, for GLSL shaders. TWGL offers a more concise way to manage complex uniform data compared to individual WebGL calls.
```javascript
const progInfo = twgl.createProgramInfo(gl, [vs, fs]);
...
twgl.setUniforms(progInfo, {
lights: [
{ intensity: 5.0, shininess: 100, color: [1, 0, 0, 1] },
{ intensity: 2.0, shininess: 50, color: [0, 0, 1, 1] },
],
});
```
```javascript
// assuming we already compiled and linked the program
const light0IntensityLoc = gl.getUniformLocation('lights[0].intensity');
const light0ShininessLoc = gl.getUniformLocation('lights[0].shininess');
const light0ColorLoc = gl.getUniformLocation('lights[0].color');
const light1IntensityLoc = gl.getUniformLocation('lights[1].intensity');
const light1ShininessLoc = gl.getUniformLocation('lights[1].shininess');
const light1ColorLoc = gl.getUniformLocation('lights[1].color');
...
gl.uniform1f(light0IntensityLoc, 5.0);
gl.uniform1f(light0ShininessLoc, 100);
gl.uniform4fv(light0ColorLoc, [1, 0, 0, 1]);
gl.uniform1f(light1IntensityLoc, 2.0);
gl.uniform1f(light1ShininessLoc, 50);
gl.uniform4fv(light1ColorLoc, [0, 0, 1, 1]);
```
```javascript
const progInfo = twgl.createProgramInfo(gl, [vs, fs]);
...
twgl.setUniforms(progInfo, {
'lights[1]': { intensity: 5.0, shininess: 100, color: [1, 0, 0, 1] },
});
```
--------------------------------
### Get WebGL Context with TWGL.js
Source: https://twgljs.org/docs/module-twgl
Retrieves a WebGLRenderingContext, prioritizing WebGL2 if available. It can optionally enable Vertex Array Objects and add WebGL2 entry points to a WebGL1 context. Configuration can be done via `twgl.setDefaults`.
```javascript
const gl = twgl.getContext(canvas);
function isWebGL2(gl) { return gl.getParameter(gl.VERSION).indexOf("WebGL 2.0 ") == 0; }
```
--------------------------------
### Create Program Async - twgl.programs
Source: https://twgljs.org/docs/module-twgl_programs
Asynchronously creates a WebGL program using promises. It offers the same flexibility as `createProgram` in terms of input parameters but returns a `Promise` that resolves with the `WebGLProgram` or rejects on error. This is useful for non-blocking shader compilation.
```javascript
twgl.programs.createProgramAsync(gl, [vs, fs]).then(program => {
// Use the program
}).catch(error => {
console.error('Shader compilation failed:', error);
});
```
--------------------------------
### Create a Single WebGL Texture
Source: https://twgljs.org/docs/module-twgl_textures
Creates a single WebGL texture from various sources like images, canvases, or arrays. This function handles texture parameter setup, including options for flipping, premultiplying alpha, and color space conversion. It may reset certain `gl.pixelStorei` settings.
```javascript
/**
* Creates a texture based on the options passed in.
* See `module:twgl.TextureOptions`
* Note: may reset UNPACK_ALIGNMENT, UNPACK_ROW_LENGTH, UNPACK_IMAGE_HEIGHT, UNPACK_SKIP_IMAGES UNPACK_SKIP_PIXELS, and UNPACK_SKIP_ROWS
* UNPACK_FLIP_Y_WEBGL, UNPACK_PREMULTIPLY_ALPHA_WEBGL, UNPACK_COLORSPACE_CONVERSION_WEBGL are left as is though you can pass in options for flipY, premultiplyAlpha, and colorspaceConversion to override them.
* As for the behavior of these settings
* ```
* gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
* t1 = twgl.createTexture({src: someImage }); // flipped
* t2 = twgl.createTexture({src: someImage, flipY: true }); // flipped
* t3 = twgl.createTexture({src: someImage, flipY: false }); // not flipped
* t4 = twgl.createTexture({src: someImage }); // flipped
* ```
*
* * t1 is flipped because UNPACK_FLIP_Y_WEBGL is true
* * t2 is flipped because it was requested
* * t3 is not flipped because it was requested
* * t4 is flipped because UNPACK_FLIP_Y_WEBGL has been restored to true
*
* @param {WebGLRenderingContext} gl the WebGLRenderingContext
* @param {module:twgl.TextureOptions} [options] A TextureOptions object with whatever parameters you want set.
* @param {module:twgl.TextureReadyCallback} [callback] A callback called when an image has been downloaded and uploaded to the texture.
* @returns {WebGLTexture} the created texture.
*/
twgl.createTexture = function(gl, options, callback) {
// Implementation details...
};
```
--------------------------------
### createProgramInfoFromProgram
Source: https://twgljs.org/docs/module-twgl_programs
Creates a ProgramInfo object from an existing WebGLProgram.
```APIDOC
## POST /createProgramInfoFromProgram
### Description
Creates a ProgramInfo object from an existing WebGLProgram. A ProgramInfo contains the program, uniform setters, and attribute setters.
### Method
POST
### Endpoint
/createProgramInfoFromProgram
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **gl** (WebGLRenderingContext) - Required - The WebGLRenderingContext to use.
- **program** (WebGLProgram) - Required - An existing WebGLProgram.
### Request Example
```json
{
"gl": "WebGLRenderingContext",
"program": "WebGLProgram"
}
```
### Response
#### Success Response (200)
- **program** (WebGLProgram) - The WebGLProgram.
- **uniformSetters** (object) - An object containing setters for the program's uniforms.
- **attribSetters** (object) - An object containing setters for the program's attributes
#### Response Example
```json
{
"program": "WebGLProgram",
"uniformSetters": {},
"attribSetters": {}
}
```
```
--------------------------------
### Program Info Creation
Source: https://twgljs.org/docs/module-twgl
Creates a ProgramInfo object from shader sources, handling attributes, locations, and errors.
```APIDOC
## createProgramInfo
### Description
Creates a ProgramInfo object from shader sources. A ProgramInfo contains the WebGL program, uniform setters, and attribute setters. This function supports multiple signatures for flexibility in providing attributes, locations, and error callbacks.
### Method
POST (or similar, function call implies creation)
### Endpoint
N/A (Function call)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **gl** (`WebGLRenderingContext`) - Required - The WebGLRenderingContext to use.
- **shaderSources** (`Array.`) - Required - Array of sources for the shaders or their DOM element IDs. The first is assumed to be the vertex shader, the second the fragment shader.
- **opt_attribs** (`Array.` or `module:twgl.ProgramOptions`) - Optional - An array of attribute names or an object with program options. Locations will be assigned by index if not explicitly provided.
- **opt_locations** (`Array.`) - Optional - A parallel array to `opt_attribs` specifying the locations for the attributes.
- **opt_errorCallback** (`module:twgl.ErrorCallback`) - Optional - A callback function for handling compilation or linking errors. Defaults to logging errors to the console.
### Request Example
```json
{
"gl": "webgl_context",
"shaderSources": [
"attribute vec4 position; void main() { gl_Position = position; }",
"void main() { gl_FragColor = vec4(1.0); }"
],
"opt_attribs": ["position"],
"opt_locations": [0],
"opt_errorCallback": "function(err) { console.error(err); }"
}
```
### Response
#### Success Response (200)
- **ProgramInfo** (`module:twgl.ProgramInfo`) - The created ProgramInfo object containing `program`, `uniformSetters`, and `attribSetters`. Returns `null` if compilation or linking fails.
#### Response Example
```json
{
"program": "WebGLProgram object",
"uniformSetters": {},
"attribSetters": {}
}
```
```
--------------------------------
### createProgramInfo
Source: https://twgljs.org/docs/module-twgl_programs
Compiles and links the provided shader sources to create a WebGL program. It returns a ProgramInfo object containing the program and setters for uniforms and attributes.
```APIDOC
## POST /createProgramInfo
### Description
Compiles and links the provided shader sources to create a WebGL program. It returns a ProgramInfo object containing the program and setters for uniforms and attributes.
### Method
POST
### Endpoint
/createProgramInfo
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **gl** (WebGLRenderingContext) - Required - The WebGLRenderingContext to use.
- **shaderSources** (Array.) - Required - 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. | 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** (Array. | module:twgl.ErrorCallback) - 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.
### Request Example
```json
{
"gl": "WebGLRenderingContext",
"shaderSources": [
"attribute vec4 position;\nvoid main() { gl_Position = position; }",
"void main() { gl_FragColor = vec4(1.0); }"
],
"opt_attribs": ["position"],
"opt_locations": [0]
}
```
### Response
#### Success Response (200)
- **program** (WebGLProgram) - The compiled and linked WebGL program.
- **uniformSetters** (object) - An object containing setters for the program's uniforms.
- **attribSetters** (object) - An object containing setters for the program's attributes
#### Response Example
```json
{
"program": "WebGLProgram",
"uniformSetters": {},
"attribSetters": {}
}
```
```
--------------------------------
### Texture Loading and Initialization
Source: https://twgljs.org/docs/module-twgl_textures
Functions for loading textures from URLs and setting initial texture data.
```APIDOC
## POST loadTextureFromUrl
### Description
Loads a texture from an image URL. Optionally sets a 1x1 pixel color for immediate use and configures filtering. The texture is updated once the image has downloaded.
### Method
POST
### Endpoint
/websites/twgljs/loadTextureFromUrl
### Parameters
#### Path Parameters
- **gl** (WebGLRenderingContext) - Required - The WebGLRenderingContext.
- **tex** (WebGLTexture) - Required - The WebGLTexture to set parameters for.
#### Request Body
- **options** (object) - Optional - A TextureOptions object with parameters like `src`, `color`, `auto`, etc.
- **src** (string) - The URL of the image to load.
- **color** (boolean) - If true, sets a 1x1 pixel color for immediate use (default: true).
- **auto** (boolean) - If true, sets filtering options automatically (default: true).
- **callback** (function) - Optional - A function to be called when the image has finished loading. Receives an error argument if one occurred.
### Request Example
```json
{
"gl": "webglContext",
"tex": "webglTexture",
"options": {
"src": "/path/to/image.png",
"color": true,
"auto": true
},
"callback": "function(err) { ... }"
}
```
### Response
#### Success Response (200)
- **imageElement** (HTMLImageElement) - The image element being downloaded.
#### Response Example
```json
{
"imageElement": "
"
}
```
## POST setEmptyTexture
### Description
Sets a texture with no contents of a specified size by calling `gl.texImage2D` with `null`. Requires `options.width` and `options.height` to be set.
### Method
POST
### Endpoint
/websites/twgljs/setEmptyTexture
### Parameters
#### Path Parameters
- **gl** (WebGLRenderingContext) - Required - The WebGLRenderingContext.
- **tex** (WebGLTexture) - Required - The WebGLTexture to set parameters for.
#### Request Body
- **options** (object) - Required - A TextureOptions object.
- **width** (number) - Required - The width of the texture.
- **height** (number) - Required - The height of the texture.
### Request Example
```json
{
"gl": "webglContext",
"tex": "webglTexture",
"options": {
"width": 128,
"height": 128
}
}
```
```
--------------------------------
### Create WebGL Program Info Asynchronously
Source: https://twgljs.org/docs/module-twgl_programs
Asynchronously creates a ProgramInfo object from shader sources, returning a Promise. This is useful for non-blocking shader compilation and linking. It accepts the same parameters as `createProgramInfo`.
```javascript
twgl.createProgramInfoAsync(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback);
```
--------------------------------
### Load Textures with TWGL
Source: https://twgljs.org/docs/index
Demonstrates using TWGL's `createTextures` function to load various texture types from image files, canvases, and data arrays. TWGL simplifies texture creation by handling WebGL API calls internally.
```javascript
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 1x8 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,
},
});
```
--------------------------------
### Create Plane Vertices and Buffer Info (JavaScript)
Source: https://twgljs.org/docs/module-twgl_primitives
Demonstrates creating vertices for a plane, reorienting them, and then generating a BufferInfo. This is a common workflow for preparing geometry for rendering.
```javascript
const arrays = twgl.primitives.createPlaneVertices(1);
twgl.primitives.reorientVertices(arrays, m4.rotationX(Math.PI * 0.5));
const bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);
```
--------------------------------
### Create and Use 4x4 Matrices with twgl/m4
Source: https://twgljs.org/docs/module-twgl_m4
Demonstrates two common patterns for creating and populating 4x4 matrices using twgl/m4. The first pattern creates a new matrix directly, while the second reuses an existing matrix for better performance.
```javascript
const mat = m4.translation([1, 2, 3]); // Creates a new translation matrix
const mat2 = m4.create();
m4.translation([1, 2, 3], mat2); // Puts translation matrix in mat2.
```
--------------------------------
### createProgramFromScripts
Source: https://twgljs.org/docs/module-twgl_programs
Creates a WebGL program from two script tags containing shader source code. It supports multiple signatures for providing optional attributes, locations, and error callbacks.
```APIDOC
## POST /createProgramFromScripts
### Description
Creates a WebGL program from two script tags. The first script tag is assumed to be the vertex shader, and the second is the fragment shader. This function can accept optional attributes, locations, and an error callback.
### Method
POST
### Endpoint
/createProgramFromScripts
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **gl** (WebGLRenderingContext) - Required - The WebGLRenderingContext to use.
- **shaderScriptIds** (Array.) - Required - Array of IDs of the script tags for the shaders.
- **opt_attribs** (Array. | module:twgl.ErrorCallback) - Optional - Options for the program or an array of attribute names, or an error callback.
- **opt_locations** (Array. | module:twgl.ErrorCallback) - Optional - The locations for the attributes, or an error callback.
- **opt_errorCallback** (module:twgl.ErrorCallback) - Optional - Callback for errors. By default, it prints an error to the console.
### Request Example
```json
{
"gl": "",
"shaderScriptIds": ["vertex-shader-id", "fragment-shader-id"],
"opt_attribs": ["a_position", "a_color"],
"opt_locations": [0, 1],
"opt_errorCallback": "function(error) { console.error(error); }"
}
```
### Response
#### Success Response (200)
- **program** (WebGLProgram) - The created WebGLProgram object.
#### Response Example
```json
{
"program": ""
}
```
```
--------------------------------
### Create Multiple WebGL Programs (Asynchronous)
Source: https://twgljs.org/docs/module-twgl_programs
The `createProgramsAsync` function provides an asynchronous way to create multiple WebGL programs, suitable for scenarios where shader loading might be involved. It uses `async/await` syntax and accepts the same parameters as `createPrograms`. This allows for non-blocking program creation, improving the responsiveness of your application.
```javascript
const programs = await twgl.createProgramsAsync(gl, {
lambert: [lambertVS, lambertFS],
phong: [phongVS, phoneFS],
particles: {
shaders: [particlesVS, particlesFS],
transformFeedbackVaryings: ['position', 'velocity'],
},
});
```