GLSL/C++: Arrays of Uniforms?

2019-01-13 03:42发布

问题:

I would like to leave OpenGL's lights and make my own. I would like my shaders to allow for a variable number of lights.

Can we declare an array of uniforms in GLSL shaders? If so, how would we set the values of those uniforms?

回答1:

Yes this is possible. You declare uniform arrays similar to how you'd do it in C, e.g.

uniform float v[10];

Then you can set their values using glUniform{1,2,3,4}{f,i}v

GLfloat v[10] = {...};
glUniform1fv(glGetUniformLocation(program, "v"), 10, v);


回答2:

Yes it is possible to declare an array of uniforms in GLSL shaders. Just google "glsl uniform array" for some examples (edit: or see datenwolf's example). There are however limitations on how many uniforms can be sent to different graphics cards (at least on older ones, I'm not sure about current ones (although I imagine there still would be)).

If you do decide to go down the route of uniforms, i would suggest using uniform buffers. According to http://www.opengl.org/wiki/Uniform_Buffer_Object, "Switching between uniform buffer bindings is typically faster than switching dozens of uniforms in a program".

If you have large numbers of lights and parameters, you could also send the data as float buffers.