pceccon
pceccon

Reputation: 9844

Declaring array in GLSL based on uniform int

In the program that I'm coding, I have to generate multiple lights sources and pass is to the shader. As this number is defined outside the shader, I though to pass it through an uniform int and use this to declare the arrays size.

uniform int numLights;
uniform vec4 ambientColor;
uniform vec4 specularColor;
uniform vec3 diffuseColor[numLights];
uniform vec3 vLightPosition[numLights];

However, I'm getting a lot of errors now:

enter image description here

Can't I do that? The thing is that I was thinking of the possibility of changing the number of predefined lights and to forget to update the shader, for example. My attempt was to prevent that to happen.

Upvotes: 0

Views: 960

Answers (1)

Tommy
Tommy

Reputation: 100612

GLSL follows the C rule there, that array sizes must be known at compile time.

GLSL has a preprocessor but no means to supply preprocessor values other than as source code. So you'll need to generate the suitable #define statements as strings and supply them to glShaderSource prior to supplying the source for that shader — the calls to glShaderSource accumulate all text passed to them prior to compilation so that's the same as prefixing the extra strings to your source file.

You'll then need to recompile each time you change the number of lights, not just supply a uniform.

Upvotes: 1

Related Questions