Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant float values in GLSL shaders - any reason to use uniforms?

I'm looking at the source of an OpenGL application that uses shaders. One particular shader looks like this:

uniform float someConstantValue;
void main()
{
    // Use someConstantValue
}

The uniform is set once from code and never changes throughout the application run-time.

In what cases would I want to declare someConstantValue as a uniform and not as const float?

Edit: Just to clarify, the constant value is a physical constant.

like image 503
kshahar Avatar asked Jul 01 '13 09:07

kshahar


2 Answers

Huge reason:

Error: Loop index cannot be compared with non-constant expression.

If I use:

uniform float myfloat;
...
for (float i = 0.0; i < myfloat; i++)

I get an error because myfloat isn't a constant expression.


However this is perfectly valid:

const float myfloat = 10.0;
...
for (float i = 0.0; i < myfloat; i++)

Why?

When GLSL (and HLSL for that matter) are compiled to GPU assembly instructions, loops are unrolled in a very verbose (yet optimized using jumps, etc) way. Meaning the myfloat value is used during compile time to unroll the loop; if that value is a uniform (ie. can change each render call) then that loop cannot be unrolled until run time (and GPUs don't do that kind of JustInTime compilation, at least not in WebGL).

like image 170
Adrian Seeley Avatar answered Oct 04 '22 22:10

Adrian Seeley


First off, the performance difference between using a uniform or a constant is probably negligible. Secondly, just because a value is always constant in nature doesn't mean that you will always want it be constant in your program. Programmers will often tweak physical values to produce the best looking result, even when that doesn't match reality. For instance, the acceleration due to gravity is often increased in certain types of games to make them more fast paced.

If you don't want to have to set the uniform in your code you could provide a default value in GLSL:

uniform float someConstantValue = 12.5;

That said, there is no reason not to use const for something like pi where there would be little value in modifying it....

like image 23
fintelia Avatar answered Oct 04 '22 21:10

fintelia