Example 01.02: Phong reflection model – ambient lighting

We’ll start of with what I call an arbitrary ‘smudge’ factor: Ambient lighting.  This represents the light in the scene that is scattered of nearby objects and uniformly lits our object.  We just assume that the light has bounced around so many times that it appears to be coming from everywhere, uniformly distributed.

ambient_lighting

Figure 1. Ambient Lighting

A way to do this right seems to be implementing some form of global illumination , but I’m getting way ahead of myself here as usual.  I have a tendency to start looking something up and end up hours later reading about all kinds of advanced graphics wizardry.  Let’s just get back to the basic Phong reflection model and stick with the simple ambient lighting factor for now :).

In this case we’ll choose a soft blue color to match the wikipedia example image that we’re trying to bring to life.

Before starting with the code I just want to thank digitalerr0r for the great XNA Shader Tutorials on his blog that I used as a basis for these examples.

The Code

The only thing that’s added in our project code is the initialization of the two parameters for ambient lighting: color (Ac) and intensity (Ai).

_effect.Parameters["Ai"].SetValue(0.8f);  
_effect.Parameters["Ac"].SetValue(new Vector4(0.0f, 0.0f, 0.3f, 1.0f));  

Code Snippet 1. Setting the parameters

The vertex shader function stays the same as in the previous example but we change the pixel shader to the following

float4 PixelShaderFunction(VS_OUT input) : COLOR  
{  
  return Ai * Ac;  
}  

Code Snippet 2. Pixel shader function

And in the shader pass we also remove the render state settings from last time so it’s just:

technique DefaultTechnique  
{  
  pass P0  
  {  
   VertexShader = compile vs_2_0 Wireframe_VS();  
   PixelShader = compile ps_2_0 PixelShaderFunction();  
  }  
}  

Code Snippet 3.  Shader pass

Now we have a boring, uniformly colored blob.  Yay!  It doesn’t have much depth to it yet because shading and specular hightlights still need to be added.

Have fun!

previous post – next post

Downloads

Download XNA code
Download MonoGame code
Blob model

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a comment