Game Development Reference
In-Depth Information
Note
More information on the RGBA color format can be found on Wikipedia at
Our final function of the example is
drawScene
, shown in Listing 7-9.
Listing 7-9.
The drawScene Function
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT);
mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0,
pMatrix);
mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [0, 0.0, -7.0]);
setMatrixUniforms();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0,
0);
gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesColorBuffer);
gl.vertexAttribPointer(vertexColorAttribute, 4, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
function setMatrixUniforms() {
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}
In Listing 7-9, we set the viewport, which are the dimensions of the WebGL drawing area, and then clear
the drawing area. We then set our perspective matrix attributes and store it in the
pMatrix
variable. We set
our modelview matrix to be seven units back on the z-axis. Since our square is drawn when z=0, we need
to move the camera back from the origin in order to see it. To inform our shader program the matrix values
to use for modelview and projection, we call
uniformMatrix4fv
and pass our
pMatrix
and
mvMatrix
values
to the shader program.
Now it is time to render our scene. We set our position and color buffers to the vertex position and vertex
color attributes respectively. Finally, we call
drawArrays
with a type of
TRIANGLE_STRIP
. This means that
our square is actually composed of four triangles, each with one vertex at the center of the square. After
the triangle primitives are processed by the fragment shader, the final result is shown in Figure 7-8.