GLSL Float Multiply By Zero

#1

Hi all, I’m working on a lighting post-processor and have a piece of code that does this float multiplication, where light and strength are floats:

light += strength * max(0, dot(normalize(light_pos - fragment_pos), normal))

If strength is 0, will the floating point multiplication instantly be evaluated to 0? Or is it worth doing something like this to avoid the expensive dot and normalize calculations:

if (strength > 0)
    light += strength * max(0, dot(normalize(light_pos - fragment_pos), normal))```
#2

Are you asking if the implementation is going to insert that condition in there? Almost certainly not. Conditional tests are not cheap in GPUs; it would be far more efficient to just execute the whole thing.

1 Like
#3

Ah I’m asking if I should add the if condition myself.

Are conditional tests not cheap as they add a possibility of some warps stalling others?

#4

The main issue with dynamic conditions is that everything except the assignment will be executed if the condition is true for any of the threads. So unless strength is a uniform or it will frequently be zero for every fragment in a workgroup, the test doesn’t have any benefit.

And on older hardware, the code will be executed regardless of the test (unless the condition was uniform, in which case it would be converted to a compile-time condition, with the appropriate shader variant selected for each draw call). The above would be translated to something along the lines of

float light_new = light + strength * max(0, dot(normalize(light_pos - fragment_pos), normal));
light = mix(light, light_new, strength > 0 ? 1 : 0);
1 Like