Game Development Reference
In-Depth Information
Listing 4-41. Building the Normal Matrix in the GenerateMatrices() Function
// Create Normal Matrix for lighting
Matrix.multiplyMM(m_NormalMatrix, 0, Cam.GetViewMatrix(), 0, m_ModelMatrix, 0);
Matrix.invertM(m_NormalMatrixInvert, 0, m_NormalMatrix, 0);
Matrix.transposeM(m_NormalMatrix, 0, m_NormalMatrixInvert, 0);
This normal matrix is then sent to the vertex shader and is placed in the NormalMatrix shader
variable, which is a 4-by-4 matrix (see Listing 4-42).
Listing 4-42. Using the Normal Matrix in the Vertex Shader
uniform mat4 NormalMatrix; // Normal Matrix
attribute vec3 aNormal;
// Put Vertex Normal Into Eye Coords
vec3 EcNormal = normalize(vec3(NormalMatrix * vec4(aNormal,1)));
The eye coordinates of the vertex normal is then calculated by multiplying the input vertex normal
aNormal by NormalMatrix , then converting it to a vec3 vector and then normalizing the resulting
vector to length 1. The variable EcNormal , which now contains the vertex normal in eye coordinates,
can now be used to calculate diffuse and specular lighting.
Lighting in the Vertex Shader
I will now turn to how lighting is done in the vertex shader. For the purposes of our simulation, light
will be composed of ambient, diffuse, and specular components.
Ambient
Ambient lighting is the same across the entire object and, thus, the same at all vertices. Because the
lighting is the same for all of the object's vertices, ambient lighting can be handled in the fragment
shader. There is no unique value that has to be calculated for a specific vertex for ambient lighting in
the vertex shader.
Diffuse
The value of the diffuse lighting for the vertex is the maximum value of either 0 or the Vertex Normal
Vector dot product with the Light Vector.
Recall that the value of the dot product of two vectors is the product of their magnitudes times the
cosine of the angle between them. If the vectors have been normalized to length 1, the dot product
is just the cosine of the angle between the vectors.
If the Normal Vector and the Light Vector are perpendicular, the cosine between the vectors is 0, and
thus the dot product and the diffuse lighting is 0 (see Figure 4-22 ).
 
Search WWH ::




Custom Search