So I am trying to make my shader efficient by lowing the amount of texture lookups. If I had a line of code with something like.

step(1.0, x) * texture2D(pic1, uv);

Where x is a value that ranges from 0 to 2 based on the fragment position. Would the GPU see when step evaluates to 0 and thus not ever calculate texture2D? Or would it still lookup the texture because the 0 is not constant?

BTW I use the term "short circuit" because I have been told that is what happens when you have false && (bla) the computer sees the false and ignores the right.


There is a difference between being able to determine value at compilation time and at runtime.

false && bla
Gets eliminated because of C/C++ lazy operand evaluation rule which is standardized with left to right order.
The compiler generates no code so the machine has no overhead.

step(1.0, x) * texture2D(pic1, uv);

That will depend if x is coming from a uniform value, in which case the drivers will compile an adjustment of the shader (and put it in a combinator cache). At some point before starting to render.
(this can cause hiccups in framerate when new uniform values are encountered that cause massive shader rebuild)

Now, if x is dependant, which means it comes from a previous calculation that comes from varying values or system values, the compiler will cut your expression in 2 parts, the lerp calculus and the sample call.
It will move the sampling of the texture in the first instructions of the shader. (provided it's unconditional in the shader flow).
So you're basically screwed when it's 0, you'll pay the sampling anyway.

In your case (0-2 wrt frag pos), I would recommend using if (inrect(0,0,1,1)) because this is a low frequency "step" function, which means very good branch elimination in 3 quarters of the screen.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.