在 glsl 结构中,我是否需要为 vec2 类型进行填充(使用布局 std430)

In glsl struct do I need to do padding for vec2 types (using layout std430)

我有 glsl 代码:

struct PStruct{
  vec2 P1;
  vec2 P2;
}
layout(std430) buffer MyList 
  {
    PStruct list[];
  }

我是否需要在每个 vec2 P1 声明之后进行填充以获得正确的对齐,在 C 语言中:

struct PStruct{
  float P1[2];
  float padding1[2];
  float P2[2];
  float padding2[2];
}

Do i need to do padding after each vec2 P1 declaration to get proper alignment, in C language:

不,你不能那样做。

在 GLSL 中,结构 PStruct 的大小是 16 个字节,P1P2 对齐到 8 个字节:

struct PStruct{
    vec2 P1;
    vec2 P2;
}

这会导致 buffer MyList 会被紧紧包裹

layout(std430) buffer MyList 
{
    PStruct list[];
}

对应C中的如下结构,大小为16字节,P1P2大小为8字节,对齐到4字节:

struct PStruct{
    float P1[2];
    float P2[2];
}

解释参见std140规则2、4、9 std340布局:

OpenGL 4.6 API Core Profile Specification; 7.6.2.2 Standard Uniform Block Layout; page 144:

....

  1. If the member is a two- or four-component vector with components consuming N basic machine units, the base alignment is 2N or 4N, respectively.

...

  1. If the member is an array of scalars or vectors, the base alignment and array stride are set to match the base alignment of a single array element, according to rules (1), (2), and (3), and rounded up to the base alignment of a vec4. The array may have padding at the end; the base offset of the member following the array is rounded up to the next multiple of the base alignment.

...

  1. If the member is a structure, the base alignment of the structure is N, where N is the largest base alignment value of any of its members, and rounded up to the base alignment of a vec4.

...

When using the std430 storage layout, shader storage blocks will be laid out in buffer storage identically to uniform and shader storage blocks using the std140 layout, except that the base alignment and stride of arrays of scalars and vectors in rule 4 and of structures in rule 9 are not rounded up a multiple of the base alignment of a vec4.