Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shader switch v conditional inside shader

Is it better to create two shaders, one for each side of a branch, or to put a branch inside pixel shader code, in terms of performance? For example, if I have a Gaussian blur shader, that decides between performing a horizontal or vertical pass, would it be better for me to split it out into two separate shaders, binding one and then the other, or keep the branch inside the shader code itself, meaning I don't have to switch shaders for the second pass?

void main(void)
{
    ...

    if (uniform_Orientation == 0)
    {
        // Horizontal blur
    }
    else
    {
        // Vertical blur
    }
}

My instinct tells me I should split it out into two separate shaders, but then I'm not sure what the performance implications are for switching shaders.

Anyone have any thoughts on this?

like image 583
Robinson Avatar asked May 06 '26 19:05

Robinson


1 Answers

there are two types of branches in shader:

  • static branch: when using if with condition based on uniform variable for instance. The branch ca be ealuated before shader is started.
  • dynamic branch: based on variables inside shader, for instance condition based on varying variable. This has some cost because pixels can use different paths.

Your problem falls into static branching. Static branching is of course much better and faster then dynamic.

the answer to the question: it is not so obvious if static branch is faster than actual switching of shaders. It depends of course. But in your example you will probably not see any performance differences.

See more info about 'uber shaders' that have a lot of static branching just to keep shader switching to minimum. http://wiki.gametheorylabs.com/groups/judgementengine/wiki/4c55c/Uber_Shader.html

like image 156
fen Avatar answered May 08 '26 14:05

fen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!