For-cycles and lighting contributions

For-next cycles?

Hi everyone!

Here’s a little (part of) shader:

uniform int numLights // ?

void main()
{

    ....

    // Light 0:

float LightAttenuation0 = clamp(1.0 - dot(g_light0Vec, g_light0Vec), 0.0, 1.0);
vec3  light0Vec = normalize(g_light0Vec);
float diffuse0  = clamp(dot(light0Vec, bump), 0.0, 1.0);
float specular0 = pow(clamp(dot(reflect(-viewVec, bump), light0Vec), 0.0, 1.0), 16.0);

float l0 = gl_LightSource[0].diffuse * (diffuse0 * base + 0.3 * specular0)
		   * LightAttenuation0;

    // Light 1 (the same as for Light 0, just place 1 instead of 0):

float LightAttenuation1 = clamp(1.0 - dot(g_light1Vec, g_light1Vec), 0.0, 1.0);
vec3  light1Vec = normalize(g_light1Vec);
float diffuse1  = clamp(dot(light1Vec, bump), 0.0, 1.0);
float specular1 = pow(clamp(dot(reflect(-viewVec, bump), light1Vec), 0.0, 1.0), 16.0);

float l1 = gl_LightSource[1].diffuse * (diffuse1 * base + 0.3 * specular1)
		   * LightAttenuation1;

    // Light 2 (the same as for Light 0, just place 2 instead of 0):

float LightAttenuation2 = clamp(1.0 - dot(g_light2Vec, g_light2Vec), 0.0, 1.0);
vec3  light2Vec = normalize(g_light2Vec);
float diffuse2  = clamp(dot(light2Vec, bump), 0.0, 1.0);
float specular2 = pow(clamp(dot(reflect(-viewVec, bump), light2Vec), 0.0, 1.0), 16.0);

float l2 = gl_LightSource[2].diffuse * (diffuse2 * base + 0.3 * specular2)
		   * LightAttenuation2;

// Result:
gl_FragColor = color_base * (l0 + l1 + l2);

}

Two questions here:

  1. How can I avoid repeating code blocks for different lights? Can I use arrays(are there any in GLSL?) and for-cycles?
    All I wish is to control the shader with numLights variable.

  2. The result line:

    gl_FragColor = color_base * (l0 + l1 + l2);

Is it ok to add light contribuitions that way?

Thanks in advance,

 Dmitry.

I have a bit the ‘same’ problems like you.

  1. You can use arrays. For cycles (I guess you mean loops), there seem not supported on my graphic card/driver (I tried for but the linker complained I can’t use it). Maybe try the do loop instead.

  2. You can add light contributions this way if all your calculations are correct and make sense. Generally a light is not only a factor of illumination (as you’ve done), but much more. However your way seems interresting and has a surely fast execution compared to models like Blinn that require many complex and slow calculations.

Hope that helps.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.