GLSL Programming/Blender/Multiple Lights

This tutorial covers lighting by multiple light sources.

This tutorial is an extension of the tutorial on smooth specular highlights. If you haven't read that tutorial, you should read it first.

Multiple Lights
In the previous tutorials on diffuse reflection, etc., we have only used one light source, which was specified by the uniform. However,  is actually an array of up to   light sources.

Here, we take a certain number of these lights (up to ) into account and add their contributions to the total lighting. This can be computed with a for-loop in the fragment shader of the tutorial on smooth specular highlights. The structure is this:

The total lighting by all lights is accumulated in  by initializing it to the ambient lighting and then adding the diffuse and specular reflection of each light to the previous value of   at the end of the for-loop. A for-loop should be familiar to any C/C++/Java/JavaScript programmer. Note that for-loops are sometimes severely limited. Specifically, sometimes you cannot even use uniforms to determine the limits. (The technical reason for the limitation is that the limits have to be known at compile time in order to “un-roll” the loop.  is an exception to the rule that uniforms are not allowed as limits because it is one of the built-in uniforms that is constant for all shaders on a certain GPU, i.e. its value is known if the shader is compiled for a specific GPU.)

Complete Shader Code
The vertex shader is the same as in the tutorial on smooth specular highlights: The only tricky thing about the fragment shader is that the nesting of loops and conditionals appears to be limited on some GPUs and/or graphics drivers. In fact, I had to reduce the nesting by avoiding if-else-statements in order to compile the shader on my computer (the OpenGL API reported an internal error). In principle, nesting of conditionals and loops is allowed in GLSL; however, it is probably a good idea to test shaders that make extensive use of nested loops and conditionals on several systems.

Be sure to disable as many default lights through the Preferences within Blender. This will prevent confusion when using less than three light sources.

Summary
Congratulations, you have reached the end of this tutorial. We have seen:
 * How a for-loop can be used in GLSL to compute the lighting of multiple lights in a fragment shader.