Game Development Reference
In-Depth Information
Coloring using the vertex color
Open the 02-SqaureDrawIndexArrayColor.html file in your favorite text editor.
The shader code for the vertex color is as follows:
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec4 aVertexColor;
//Attribute hold color for each vertex
varying lowp vec4 vColor;
//Varying qualifier to pass vertex color to fragment shader
void main(void) {
vColor = aVertexColor; //Assign attribute value to varying to
be used in shader
}
</script>
<script id="shader-fs" type="x-shader/x-fragment">
precision mediump float;
varying lowp vec4 vColor;//Varying qualifier to get values from
vertex shader
void main(void) {
gl_FragColor = vColor;//Assign value to be used in shader
}
</script>
The preceding code denotes changes to the vertex and fragment shaders used
previously in our examples. Three changes in the vertex shader are as follows:
• We create an attribute ( aVertexColor ) to get the vertex color value from the
control JavaScript code.
We create a varying variable to pass this color value to the fragment shader.
You might wonder why we did not create a uniform qualifier and pass it
directly to the fragment shader from the control code. We will do this in cases
where the whole primitive has the same color value. In our case, the primitive
is the triangle, and each vertex has a different value. We only use the uniform
qualifier for variables whose value does not change across a primitive
(across the face of a triangle). Therefore, in our case, we created an attribute
which received each value of the vertex from the buffer. Then, we passed this
value to the fragment shader using the varying variable. Remember, varying
is the only qualifier used to pass values from the vertex shader to the fragment
shader. The varying values are interpolated by the hardware, as explained in
Chapter 1 , Getting Started with WebGL Game Development .
 
Search WWH ::




Custom Search