PDA

View Full Version : std140 layout for uniform blocks clarification



ajith.mk
12-10-2015, 02:42 AM
I just couldn't get it. The only thing I could figure out is base alignment. Its either N,2N or 4N. In a structure how do I calculate offset and aligned offset of its members? I have read some articles by googling but I guess something's wrong with me. I cannot make head or tails of the whole issue.

Alfonse Reinheart
12-10-2015, 10:38 AM
Can't get what? You haven't explained what it is that you don't understand about the rules. It's hard to help someone when they don't actually say what it is they don't understand.

Give us an example of a struct, and then explain where you're stuck.

GClements
12-10-2015, 02:04 PM
The offset of the first field is the offset of the structure itself. The offset of any subsequent field is the offset of the previous field plus the size of the previous field, rounded up to the next multiple of the alignment of the current field.

The size of an array or structure is always a multiple of its alignment; it may have padding at the end to satisfy this requirement.

In other words, the base offset for each field is the offset immediately after the end of the previous field (including any padding in the case of a structure or array). The aligned offset of each field is its base offset rounded up to the next multiple of its alignment. Each field is stored at its aligned offset.

E.g. given the structure


struct example {
float a;
vec4 b;
float c;
float d;
};

Assuming N=4, its alignment is 16 bytes (4N) and its size is 48 bytes (12N). The offsets of a, b, c and d are 0, 16 (4N), 32 (8N) and 36 (9N) bytes respectively. So there are 12 bytes (4N) of padding between x and y and 8 bytes (2N) at the end of the structure.

The memory layout looks like


| a |...|...|...|b.x|b.y|b.z|b.w| c | d |...|...|


Note that the size of a vec3 isn't a multiple of its alignment. It must be aligned to a multiple of 4N, but its size is only 3N. A scalar value (with an alignment of N) may occupy the "spare" field, but any type with greater alignment can't as it would be misaligned.

ajith.mk
12-10-2015, 07:14 PM
That memory layout cleared a lot of things. Thank you.