Search code examples
structreferenceglsl

How to reference a struct in GLSL?


C++-style references can make code much neater but GLSL doesn't have them.

eg. This code:

for (int i=0; i<numCascades; ++i) {
    if (eyeDistance < shadow.cascade[i].end) {
        vec3 sc = eyePos*shadow.cascade[i].transform;

        // ...many more references to "shadow.cascade[i]" here

    }
}

Would be much neater if I could type this instead:

for (int i=0; i<numCascades; ++i) {
    const ShadowCascade& cascade = shadow.cascade[i];
    if (eyeDistance < cascade.end) {
        vec3 sc = eyePos*cascade.transform;

        // ...many more references to "cascade" here

    }
}

I could type this instead (same as above but no '&'):

for (int i=0; i<numCascades; ++i) {
    const ShadowCascade cascade = shadow.cascade[i];
    if (eyeDistance < cascade.end) {
        vec3 sc = eyePos*cascade.transform;

        // ...many more references to "cascade" here

    }
}

Would there be a performance penalty for that? Will the cascade struct be copied into a local variable (like in C++)?

How do people neaten this sort of code in GLSL? (Use #define? (ugh!))


Solution

  • To answer my own question: I did some informal testing and using #define as shown below gave me a measurable improvement in frame rate.

    for (int i=0; i<numCascades; ++i) {
        #define cascade shadow.cascade[i]
        if (eyeDistance < cascade.end) {
            vec3 sc = eyePos*cascade.transform;
    
            // ... more references to "cascade" here
    
        }
    }
    

    This was on desktop NVIDIA so I guess if they aren't optimizing that pattern then nobody else will be.