Search code examples
openglglsl

OpenGL how to get offset of array element in shared layout uniform block?


I have a shared layout uniform block in shader:

layout(shared) uniform TestBlock
{
    int test[5];
};

How to get offset of test[3]?
When I try to use glGetUniformIndices to get index of test[3], it will return the same number of test[0]'s index.
So I cannot use glGetActiveUniformsiv to get offset of index of test[3].
Then, how to get offset of test[3]?
(Note that I don't want to use layout std140.)


Solution

  • Arrays of basic types like ints are treated as a single value. You can't get the offset of an individual element in the array. You can however query the array stride, the number of bytes from one element in the array to the next. Then you can just do the multiplication.

    Using the new program introspection API:

    auto ix = glGetProgramResourceIndex(prog, GL_UNIFORM, "test");
    GLenum props[] = {GL_ARRAY_STRIDE, GL_OFFSET};
    GLint values[2] = {};
    glGetProgramResourceiv(prog, GL_UNIFORM, ix, 2, &props, 2, NULL, &values);
    
    auto byteOffset = values[1] + (3 * values[0]);