<<< Diffuse lighting in vertex shader | Index | Rotating light >>> |
The light calculation can be done in the world space or in the camera space. Using world space is very common. The model matrix mM transforms vertex positions into the world space. We compute it on the CPU side and then pass it to the GPU via uniform variable:
mM = mtx_trans * mtx_all_rot * mtx_scale;
Here, mtx_all_rot includes all rotations. Although it could be used to transform normals from model to world space, scaling of objects also affects the direction of normal vectors. A standard way to transform normals into the world space is to use the transposed inversed model matrix. Its calculation can be done in the vertex shader:
mat4 tiM = transpose( inverse( mM ) ); fN = ( tiM * vNormal ).xyz;
However, the vertex shader recomputes tiM for every vertex, which is inefficient. A better way is to compute the normal rotation matrix mR on the CPU side
myModel->mR = glm::transpose( glm::inverse( myModel->mM ));
and then pass it to the vertex shader as an additional uniform variable:
uniform mat4 mR; // matrix only for rotation of normals out vec3 fN; // interpolated and sent to the fragment shader //... void main () { fN = ( mR * vNormal ).xyz; // transfrom normal vectors //...
<<< Diffuse lighting in vertex shader | Index | Rotating light >>> |