Sometimes, you want the same shader to do different things under different circumstances. For example, you might want to configure different settings for different materials, define functionality for different hardware, or dynamically change the behavior of shaders at runtime. You might also want to avoid executing computationally expensive code when it’s not needed, such as texture reads, vertex inputs, interpolators, or loops.
You can use conditionals to define behavior that the GPU only executes under certain conditions.
To use conditionals in your shader, you can use the following approaches:
There is no “one size fits all” approach to conditionals in shaders, and you should consider the advantages and disadvantages of each approach for a given shader, in a given project.
Bear in mind the following information:
In general, the best approach is to profile the performance of your application and carefully consider your decisions case-by-case. For example, if you can afford the slightly increased GPU cost, it might be best to use dynamic branching to achieve “good enough” GPU performance and reduce the risk of introducing more variants. However, if GPU performance is the primary concern for this shader and you have already accounted for the cost of additional variants, you might choose to use variants.