WebGL API getUniformLocation(WebGLProgram,String) - WebGL Textures & Vertices: Beginner's Guide (2015)

WebGL Textures & Vertices: Beginner's Guide (2015)

WebGL API getUniformLocation(WebGLProgram,String)

The WebGL API method getUniformLocation(WebGLProgram,String) returns the location of a uniform from a shader. The first parameter to getUniformLocation(WebGLProgram,String) is a WebGLProgram with linked shaders. The second parameter to getUniformLocation(WebGLProgram,String) is the name of the uniform within quotation marks. The following listing demonstrates how the method getProgramVariables() obtains the location of um4_pmatrixfrom the book's vertex shader. gl is the WebGLContext and program is a reference to the compiled and linked WebGLProgram.

var uMP = gl.getUniformLocation

(

program,

"um4_pmatrix"

);

Listing 47: WebGL API getUniformLocation(WebGLProgram,String)

The following JavaScript array functions as a perspective projection matrix. The matrix gives the illusion of one point perspective with approximately 450 field of view. Cast the JavaScript array to type Float32Array, for use within WebGL. A Float32Array means every entry represents a floating point number with 32 bits of precision.

var aMP = new Float32Array(

[

2.4,0,0,0,

0,2.4,0,0,

0,0,-1,-1,

0,0,-0.2,0]

);

Listing 48: JavaScript Perspective Projection Matrix

WebGL API uniformMatrix4fv(WebGLUniformLocation, Boolean, Float32Array)

Use the WebGL API method uniformMatrix4fv(WebGLUniformLocation, Boolean, Float32Array) to upload a Float32Array of data to a shader's uniform. In other words copy our JavaScript array of numbers to the shader's uniform named um4_pmatrix. The Float32Array must represent a 4 x 4 matrix. The Boolean parameter must equal gl.FALSE.

gl.uniformMatrix4fv

(

uMP,

gl.FALSE,

aMP

);

Listing 49: WebGL API uniformMatrix4fv(WebGLUniformLocation, Boolean, Float32Array)

Perspective Projection Summary

This section briefly described how the book applies perspective projection and what perspective projection accomplishes. Perspective projection provides the illusion of depth and volume. Mesh elements in the distance appear smaller and closer together. Lines converge toward the center of projection.

Method getProgramVariables() prepares a JavaScript 4 x 4 matrix for perspective projection, then uploads the matrix to the vertex shader's uniform named um4_pmatrix. The vertex shader multiplies every vertex in a mesh by the matrix.