Search code examples
c++openglglsl

OpenGL shaders uniforms optimization


I want to optimize my shaders and I'm wondering how calculations on uniforms are treated by shaders. To be precise, I'm wondering if I should rather calculate such things on the CPU and send ready-made results as uniforms, or can I calculate it on shaders without major losses in terms of performance.

For example I have simple shader like this:

uniform vec2 screenSize;
vec2 pixelSize = vec2(1.0, 1.0) / screenSize;

void main()
{
//... some code that is using pixelSize, for example for reading something from sampler2D
}

How many times pixelSize will be calculated in the shader per one OpenGL draw call, for example for full screen size quad (post processing effects)?

Maybe it depends on what is it vertex shader or fragment shader?


Solution

  • At the end of the day, this will all be implementation-defined. An implementation could find every possible case of expressions derived entirely from uniform values and pre-compute them on the CPU when you render with that shader and those uniforms. Essentially, it could invent another uniform value that gets computed prior to rendering calls.

    However, I would not rely on that. At the same time... I probably wouldn't care all that much. Any shader that is non-trivial is going to be spending most of its time doing work processing non-uniform data. Like, if your shader is fetching half-a-dozen textures (or even just one), the cost of doing a reciprocal operation on a uniform will be a rounding error.

    Just use reasonable judgment. Don't do a lot of obviously expensive operations on uniform variables because it's easier to code than you computing them on the CPU. At the same time, don't worry about doing a few minor operations unless you have actual performance problems.