Search code examples
c++arraysopenglglslshading

How to pass an array of size changing structures into a glsl shader


In order to add dynamic lighting to my application, I was thinking that I could represent each shadow casting object as an array of floats (every 3 floats is a vector and so every 9 floats is a triangle). And so, in order to cast ALL possible shadows, I need an array of these arrays (if this was C++ I would have done an array of vectors).

Is there a way to construct somehting similar in a glsl shader, throught either SSBOs or uniforms?

And if not, how could I pass this information. The problem here is that I don't know how big the number of triangles per shading object is, so I have no way of determining a constant sized structure to make my array of solid objects.


Solution

  • You're thinking simultaneously too high-level and too low-level. You say that you need a bunch of arrays, but you don't. What you need is a way to get the vertex data for a particular object in the scene. This doesn't have to be encoded as "an array of these arrays" at all.

    Instead, encode it as a single massive array of vertex data. Each object has indices that specifies the location in this array for the vertex data.

    layout(std430) buffer obj_data
    {
      uvec2 objects[];
    };
    
    layout(std430) buffer vertex_data
    {
      vec4 vertices[]; //NEVER use `vec3`s in storage blocks
    };
    

    objects is an array, where each uvec2 represents a specific object. The x component of that uvec2 is the offset into vertices where its vertex data starts. And y is the number of vertices to read, starting at x.

    So vertices[objects[10].x] is the first vertex of the data for the object with index 10.

    And BTW:

    if this was C++ I would have done an array of vectors

    If this were C++, I'd encode it more or less like I would for GLSL: store all of the vertex data in a single array, and have each object reference its contiguous slice of that array. It's more efficient to access than an array of vector, and requires far fewer allocations.