Game Development Reference
In-Depth Information
In the preceding code, in the vertex shader, we pass the material ambient
color, light ambient color, material diffuse color, and light diffuse color in
the
materialAmbientColor
,
uAmbientColor
,
materialDiffuseColor
, and
uDirectionalColor
uniforms respectively. In the first line, we calculate the new
transformed vertices and store them in the
gl_position
variable. Then, we calculate
transformedNormal
. The transformed normal is derived by multiplying the normal
matrix with the vertex normal. The normal matrix (
nMatrix
) is the transpose of
the inverse of the ModelView matrix. Then, we derive
normal
, the unit vector of
transformedNormal
, using the normalize function. From the
normal
vector and
uniform light direction, we get the
Lambert
term. Then, the final vertex color is
calculated from the ambient and diffuse colors and is passed to the fragment shader.
In the preceding code, we first calculate the transformed normal, and from the
transformed normal and light direction, we get the Lambert term:
Lambert term = Vertex normal - Light direction
The control code for the Gouraud shading for the Lambertian reflection model
is as follows:
function loadModel(url){
rotateZ=0.0;
rotateY=0.0;
$.getJSON(url,function(data){
vertices = data.vertices;
var faces=parseJSON(data);
indices = getIndicesFromFaces(faces);
if(data.materials.length>0){
diffuseColor=data.materials[0].colorDiffuse;
ambientColor=data.materials[0].colorAmbient;
}
normals=calculateVertexNormals(vertices,indices);
initScene();
});
}
The
loadModel(url)
function parses the JSON file, retrieves the vertices data, and
gets indices data using the
parseJSON()
function. We also retrieve the ambient and
diffuse colors of the model defined in the parse JSON file. We calculate the vertex
normals
array using the
calculateNormals(vertices,indices)
function defined
in the utils.js library.
function initShaders() {
...
shaderProgram.vertexNormalAttribute =
gl.getAttribLocation(shaderProgram, "aVertexNormal");