problem with uniform int and for loop

I have declared a uniform variable in both vertex and fragment shaders:
uniform int numLights;

I use the following code in my application to send the number of numLights to the shader:
glUniform1i(glGetUniformLocation( g_render.m_shaderProgram , “numLights”), 1 );

when I use numLights in a for loop in my fragment shader,It seems that I get an endless loop:
for( int i = 0; i < numLights; i++ )


even if I use the following code before the for loop:

int numberOfLights = numLights;
if( numberOfLights > 1 )
numberOfLights = 1;
for( int i = 0; i < numberOfLights ; i++ )


however if I define the value of for loop inside the fragment shader, I don’t get any logical bugs:

int numberOfLights = 1;
for( int i = 0; i < numberOfLights ; i++ )


My graphics card is Geforce 9600 and I have downloaded and installed the latest driver.

Without a predetermined number of lights the compiler cannot unroll the code, this has serious implications for hardware which must then support dynamic branching in the shader because the range is unbounded and unknown at compile time. This can also have a serious performance impact on some architectures.

A quick search shows that the 9600GT was supposed to support dynamic branching, and of course the version of OpenGL you use & the driver’s shader compiler must support it. Dunno about the 9600.

So the key phrase here is “dynamic branching support”

P.S. at least now you have a first hand lesson on where dynamic branching support is useful.

I have built similar shaders using code stitching/redacting for both for number of lights and specific light features like spotlight and specular. This is the way to build optimized shaders on architectures with limited or expensive flow control.

Thanks, So I should use OpenGL 3.0 ?
Note that My graphics card is 9600 GT :)( I didn’t know that “GT” is important ). I currently use GLSL #version 110.
I still don’t know anything about dynamic branching :frowning: