Aligning structures to std140, CPU side

后端 未结 1 1100
旧巷少年郎
旧巷少年郎 2021-02-09 12:42

I suppose this is a kind-of cross between a pure C++ question and an OpenGL question. I have a uniform buffer and am allocating space in it of sizeof(ShaderData) bytes. I\'m u

1条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-09 12:49

    No, in this way you just waste space. You have to find the optimized layout according to std140 rules.

    • a float needs 4 bytes and it's 4 bytes aligned
    • a vec3 needs 12 bytes and it's 16 bytes aligned
    • a vec4 needs 16 bytes and it's 16 bytes aligned

    This means that you can find a better layout for your struct:

    float Light_Intensity;          X
    float _pad1[3];                  XXX
    Math::Vec3f Light_Position;         XXX
    float _pad2;                           X
    

    As you can see you are wasting 4 bytes and what's worse is the fact that you can just do something like:

    Math::Vec3f Light_Position      XXX
    float Light_Intensity;             X
    

    To have it aligned and without the need to waste a byte. This works because vec3 will be aligned to 16 bytes boundaries while the float will be still aligned to 4 bytes boundaries.

    0 讨论(0)
提交回复
热议问题