Adding Realism Using Shading


You don't need to be a graphics designer to realize that doesn't look all that great. It's just a big white blob that vaguely resembles a go-kart. The problem here is that your shader returned 1.0f (pure white) for every vertex, so naturally the entire model is colored pure white. You need to fix this problem, which you do by emulating a directional light from the fixed-function pipeline.

You've been using directional lights throughout this book as a way of making things appear more realistic, and now you implement the same directional light using a shader and the programmable pipeline. Back in the KartRacers.fx file, replace the transform function with the one in Listing 20.4.

Listing 20.4. Directional Lighting Shader
 float4 Transform(in float4 pos : POSITION, in float3 normal : NORMAL, out float4 Position : POSITION) : COLOR0 {     // Transform position     Position = mul(pos, worldViewProjection);     // Transform the normal     float4 transformedNormal = mul(normal, worldViewProjection);     return dot(transformedNormal, lightDirection); } 

You'll notice here the parameters have changed. Rather than a single in parameter that is the position, now a second parameter is the normal of the vertex. This parameter is required for the directional light calculation. The first part of the shader code is the same; the position is transformed and returned via the out parameter. However, you are not simply returning a solid white color from this function. First, you take the normal of the vertex, transform it just as you did the position, and store that in a new local parameter transformedNormal. You then return the dot product of the transformed normal and a light direction variable you haven't yet defined. You should define it in your .fx file with the rest of your variables:

 float4 lightDirection;  // Direction of the light 

Now, you just update your C# code to take advantage of this new shader. The only change required is a call to set the value of the light direction variable. To make it easier, first, declare a new "constant" to hold the light direction:

 // Light direction private static readonly Vector4 LightDirection = new Vector4(0, 0.1f,     -1.5f, 1.0f); 

Then, find the two calls to SetValue in the OnFrameRender method and add the new one directly after that:

 effect.SetValue("lightDirection", LightDirection); 

Running the application now and selecting the new game will show you a shaded version of the go-kart, much as you see in Figure 20.2.

Figure 20.2. Shading added.




Beginning 3D Game Programming
Beginning 3D Game Programming
ISBN: 0672326612
EAN: 2147483647
Year: 2003
Pages: 191
Authors: Tom Miller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net