Search code examples
gpuglsl

How to avoid GLSL copy by value?


The following code:

layout (set = 0, binding = 0) readonly buffer TestBuffer {
    float[32] probs;
} args;

void main() {
    const float[] ps = args.probs;
}

creates a deep copy of the float array, i.e., it copies all the array members. I would have thought that the const qualifier would make ps just an alias for args.probs, just as when passing it to a function with a const in qualifier.

Copying the array again, like const float[] ps2 = ps, only copies the reference.

Is there any way to do this without runtime overhead? Of course, in the real world args is much larger and contains nested arrays of structs, so being able to reference just a small part of it is useful, but not practical due to a huge performance penalty.


Solution

  • It seems to me that the only thing you want to do here is to create a shorter name for a longer name. That is, if args.probs is something like args.foo[30].bar.whatever, you want to refer to that particular piece of data as ps.

    This is probably best done with a macro: #define ps args.probs. Now obviously, this has downsides. Macros are not lexically scoped for example; you explicitly have to #undef them to prevent those names from leaking out.

    But GLSL doesn't have a reference system like C++, nor does it have actual pointers. So the only choice to avoid a conceptual copy (the implementation could and should have optimized it out) is to use a macro.