Graphics Reference
In-Depth Information
Example 14-13
Projective Texturing Vertex Shader
(continued)
// Create bias matrix
mat3 biasMatrix = mat3( 0.5, 0.0, 0.5,
0.0, −0.5, 0.5,
0.0, 0.0, 1.0 );
// Compute projective texture coordinates
v_projTexCoord = objPosLight.xyz * biasMatrix;
v_lightDir = normalize(a_vertex.xyz − lightPos);
v_normal = a_normal;
}
The first operation this shader does is to transform the position by the
u_matViewProjection
matrix and output the texture coordinate for the
base map to the
v_texCoord
output variable. Next, the shader computes a
position for the light based on time. This bit of the code can really be ignored,
but it was added to animate the light in the vertex shader. In a typical
application, this step would be done on the CPU and not in the shader.
Based on the position of the light, the vertex shader then computes the
three coordinate axis vectors for the light and places the results into
the
look
,
right
, and
up
variables. Those vectors are used to create a
view matrix for the light in the
lightView
variable using the equations
previously described. The input position for the object is then transformed
by the
lightView
matrix, which transforms the position into light space.
The next step is to use the perspective matrix to transform the light space
position into projected light space. Rather than creating a new perspective
matrix for the light, this example uses the
u_matProjection
matrix for
the camera. Typically, a real application would want to create its own
projection matrix for the light based on how big the cone angle and falloff
distance are.
Once the position is transformed into projective light space, a
biasMatrix
is created to transform the position into a projective texture coordinate.
The final projective texture coordinate is stored in the
vec3
output
variable
v_projTexCoord
. In addition, the vertex shader passes the light
direction and normal vectors into the fragment shader in the
v_lightDir
and
v_normal
variables. These vectors will be used to determine whether a
fragment is facing the light source so as to mask off the projective texture
for fragments facing away from the light.
The fragment shader performs the actual projective texture fetch that
applies the projective spotlight texture to the surface (Example 14-14).