Real-Time Shader Programming

In mathematics you don't understand things. You just get used to them.
-- Johann von NeumannNothing is really work unless you would rather be doing something else.
-- James M. BarrieOne of the nice things about shaders is that you can create your own for whatever special effects you are looking for In fact, one of the reasons that shaders have finally made it into mainstream 3D computer graphics is the flexibility that they provide, which can finally be realized in real time on consumer grade hardware. Unfortunately, with power comes responsibility the responsibility to understand how lighting and shading in computer graphics is traditionally done and how you can do it yourself (or do it differently) in a shader. But first, you'll need an understanding of the mathematics behind lighting and shading.
In order to understand how an object's color is determined, you'll need to understand the parts that come into play to create the final color. First, you need a source of illumination, typically in the form of a light source in your scene. A light has the properties of color (an rgb value) and intensity. Typically, these are multiplied to give scaled rgb values. Lights can also have attenuation, which means that their intensity is a function of the distance from the light to the surface. Lights can additionally be given other properties such as a shape (e.g., spotlights) and position (local or directional), but that's more in the implementation rather than the math of lighting effects.
Given a source of illumination, we'll need a surface...