GLSL Struct Alignment

I’m struggling to figure out how this struct in glsl is aligned so that my struct in C++ will match. Can anyone see the issue? Thanks.

//GLSL

struct MyStruct {
	mat4 matrix;
	vec4 color;
	dvec3 data;
};

//C++

struct MyStruct {
	float matrix[16];
	float color[4];
	double data[3]
};

First, the GLSL structure needs to be declared with layout(std140) or layout(std430); SSBOs can use either, UBOs can only use std140. If you don’t use one of those layout qualifiers, the implementation is free to choose the layout and you have to query the offsets (and array strides) with glGetProgramResource.

Second, you need 16 bytes of padding between color and data, as data needs to be 32-byte aligned (§7.6.2.2 Standard Uniform Block Layout):

Note that if you’re creating an array of these structures, you’ll need an extra 8 bytes of padding, as the structure’s alignment will be 32 bytes.

Essentially, mat4 and vec4 both need to be 16-byte aligned while dvec3 needs to be 32-byte aligned; the required alignment for structures is the largest alignment of any member (so 32 bytes in this case).

Thankyou. Solved it. I was unaware that a GLSL struct could be declared with layout, everything I’ve tried won’t compile.

Like this here won’t compile:

layout(std140) struct MyStruct {
	mat4 matrix;
	vec4 color;
	dvec3 data;
};

You can’t use it on a “bare” struct declaration. You can use it on a variable declaration (for a uniform or buffer variable) or on an interface block declaration. This includes declarations whose type is or contains a struct.

Ah okay. That makes sense, thankyou. :slight_smile: