Game Development Reference
In-Depth Information
In the
StageObject
class, earlier we created two Vertex Buffer Objects (
vertices
and
normals
) and one Index Buffer Object (indices). Now, we will create another
Vertex Buffer Object for UV coordinates (
this.verticesTextureBuffer
) as shown
in the following code:
StageObject.prototype.createBuffers=function(gl){
...
if(this.materialFile!=null){
this.verticesTextureBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.verticesTextureBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this.geometry.
uvs[0]),gl.STATIC_DRAW);
}
...
}
Open
06-Loading-Scene-With-Textures.html
in your favorite text editor. First,
we will understand the changes that we need to perform in shaders in order to
support both diffuse color and textures for different types of objects.
Implementing the vertex shader code
We have added three variables to our vertex shader:
attribute
(
aTextureCoord
)
that references the texture coordinate array,
varying
(
vTextureCoord
) that passes
these coordinates to fragment shader, and
uniform
(
hasTexture
) that sets the
varying
only if its value is true. Basically, the same vertex shader will be used for
objects that use a texture as well as for objects that use only a diffuse color. We set
the value of this uniform based on the value of the
materialFile
property of each
StageObject
as shown in the following code:
<script id="shader-vs" type="x-shader/x-vertex">
...
attribute vec2 aTextureCoord;
varying highp vec2 vTextureCoord;
uniform bool hasTexture;
void main(void) {
...
if(hasTexture){
vTextureCoord = aTextureCoord;
}
}
</script>