GPU data

Struct layout rules

The CPU writes a struct into a buffer, and a shader reads it. Two different compilers decide where each field goes, and they must agree on every byte. This page explains the rules each side uses, where they differ, and how to check that they match. The last part shows how RASM does it.

In short

  • Every type has a size and an alignment. A field goes at the next offset that is a multiple of its alignment; the gap before it is padding.
  • C++ aligns each type to its own size (a float to 4, a double to 8). A vec3 of floats is 12 bytes, aligned to 4.
  • GPU languages have several rule sets. std140 aligns a vec3 to 16 and pads arrays to 16. std430 drops the array padding. scalar aligns everything to its scalar, like C++.
  • The same struct can be 112, 96 or 72 bytes depending on the rules. A mismatch does not crash; the shader just reads the wrong bytes.
  • Check it: static_assert the C++ offsets, and compare them with the shader compiler's reflection at startup.

1The problem: two compilers, one buffer

A C++ compiler lays out the CPU struct. A shader compiler lays out the GPU struct. Nothing connects the two. The bytes in the buffer are whatever the CPU wrote; the shader reads each field at the offset its compiler chose.

CPU writes (C++) a b = (1, 2, 3) c next fields … 041620 shader reads (std430) a padding b ? 01628 b is read from bytes 16–28: c and the next field
Scale: 10 px per byte. The most common layout bug: a three-component vector after a scalar. C++ puts it at 4, std140 and std430 put it at 16.
No error, no crash

The shader's b is (c, next, next). The values are real floats from the wrong place, so there is no error and no crash. The picture is simply wrong, or, if a pointer field moves, the GPU follows a garbage address and the device is lost.

2Size, alignment and offset

Every layout rule set, CPU or GPU, uses the same algorithm. Only the numbers in it differ. Here are its five words, on an array of a struct with a float a and a double b:

stride = 16: from one element to the next the next element a padding b a b 04816 202432 offset of b = 8 size of b = 8 alignment of b = 8: its offset must be a multiple of 8, so 4 bytes of padding come before it
Scale: 20 px per byte. Dashed boxes are padding.
WordMeaning
sizehow many bytes the value takes
alignmentits offset must be a multiple of this number
offsetwhere the field starts, from the start of the struct
paddingunused bytes added so the next field is aligned, or so the struct size is
stridethe distance from one array element to the next
offset = 0
maxAlign = 1
for each field:
    offset = roundUp(offset, align(field))      // padding goes here
    field.offset = offset
    offset = offset + size(field)
    maxAlign = max(maxAlign, align(field))
structSize  = roundUp(offset, maxAlign)          // padding at the end
structAlign = maxAlign

roundUp(x, a) is the smallest multiple of a that is ≥ x. The padding at the end makes the size a multiple of the alignment, so that in an array every element is aligned too: the array stride is the struct size.

3C++ layout

On every desktop platform, C++ aligns each scalar to its size: int32_t and float to 4, double, int64_t and pointers to 8. A struct aligns to its largest member. Order matters: the same fields can need more or less padding.

float, double, int 24 bytes float pad double int pad 048162024 double, float, int 16 bytes double float int 081216
Scale: 16 px per byte. The end padding of the first struct is there so that a second element of an array starts at 24, a multiple of 8. Sorting fields from the biggest alignment to the smallest removes most padding. It does not change what the fields mean, only where they are.

Math libraries follow the same rules. In glm (by default):

12 bytesa vec3: three floats, aligned to 4
36 bytesa mat3: three vec3 columns
16 bytesa vec4: also aligned to only 4

Some libraries (and glm with special options) align vec4, or even vec3, to 16 for SIMD; that changes every offset after them.

The C++ side can be pinned with checks the compiler runs:

struct Light
{
    glm::vec3 position;
    float intensity;
};

static_assert(sizeof(Light) == 16);
static_assert(offsetof(Light, intensity) == 12);

4GPU layouts: std140, std430, scalar

Vulkan GLSL and SPIR-V know three rule sets for buffer memory. They differ in two places: how a three-component vector aligns, and whether arrays and structs are rounded up to 16 bytes.

Typestd140std430scalar
float, int, uintsize 4, align 4size 4, align 4size 4, align 4
vec2size 8, align 8size 8, align 8size 8, align 4
vec3size 12, align 16size 12, align 16size 12, align 4
vec4size 16, align 16size 16, align 16size 16, align 4
array of Tstride and align rounded up to 16stride = size of T (rounded to its align)stride = size of T
structalign = largest member, rounded up to 16align = largest memberalign = largest member
matrix (column-major)an array of column vectors: mat3 = 3 × 16 = 48 bytesthe same: mat3 = 48 bytes3 × 12 = 36 bytes
64-bit (uint64_t, double, a pointer)size 8, align 8size 8, align 8size 8, align 8
Rule setWhere it is used
std140The oldest. The default for uniform buffers in GLSL. Wastes the most space.
std430The default for storage buffers and push constants in Vulkan GLSL.
scalarNeeds the Vulkan feature scalarBlockLayout (core in 1.2 as an optional feature, required since 1.4). Can be turned on per block, or for a whole shader by a compiler option. Closest to C++.

5One struct, three layouts

Here is one struct, laid out under all three rule sets. d is an array of two vec2; m is a 3 × 3 matrix stored as three columns (c0, c1, c2).

struct Example
{
    float a;
    float3 b;
    float c;
    float2 d[2];
    float3x3 m;
};
std140 · 112 bytes a pad b c d0 d1 m c0 m c1 m c2 0 16 32 48 64 80 96 112 std430 · 96 bytes a pad b c d0 d1 m c0 m c1 m c2 0 16 32 48 64 80 96 scalar · 72 bytes a b c d0 d1 m c0 m c1 m c2 0 4 16 20 36 72
Scale: 6 px per byte. Dashed boxes are padding. The same five fields: 112, 96 or 72 bytes. Only the scalar layout matches what a C++ compiler makes from the same struct: the C++ struct with glm's default vec3 and mat3 is exactly the scalar row.

Click through the std430 row, field by field, with the algorithm of section 2.

1. a: float

a 0 next free byte = 4 a is a float: size 4, align 4. offset = roundUp(0, 4) = 0. Next free byte: 4. maxAlign = 4.

The first field always starts at 0.

2. b: float3

a pad b 0 4 16 next free byte = 28 b is a float3: size 12, but align 16 in std430. offset = roundUp(4, 16) = 16. Bytes 4 to 16 become padding. Next free byte: 28. maxAlign = 16.

The only padding between fields in this struct: 12 bytes before b.

3. c: float

a pad b c 0 16 28 next free byte = 32 c is a float: align 4. offset = roundUp(28, 4) = 28. It fills the last 4 bytes of the 16-byte slot that b started.

No padding: a scalar fits right after a float3.

4. d: float2[2]

a pad b c d0 d1 0 16 32 48 next free byte = 48 d is an array of float2: align 8, stride 8 (std140 would make both 16). offset = roundUp(32, 8) = 32. Two elements: 32 to 48.

In std140, each float2 would take 16 bytes, and d would end at 64.

5. m: float3x3

a pad b c d0 d1 m c0 m c1 m c2 0 16 32 48 64 80 96 next free byte = 96 m is 3 columns, each a float3: align 16, so the column stride is 16, not 12. offset = roundUp(48, 16) = 48. 3 × 16 bytes: 48 to 96.

Each column of a float3x3 wastes 4 bytes in std430 and std140, but not in scalar layout.

6. The end: size and alignment

a pad b c d0 d1 m c0 m c1 m c2 0 16 32 48 64 80 96 next free byte = 96 maxAlign is 16 (from b and m). structSize = roundUp(96, 16) = 96. No padding at the end. In an array, element 1 starts at 96.

The size is 96. The C++ struct is 72, so the two sides disagree from b on.

Now try it yourself. The picture below runs the same algorithm twice on these five fields: with the C++ rules, and with the shader rules you pick.

where C++ writes a field the shader reads the same bytes the shader reads other bytes dashed: padding
In std430, move the fields until only m is wrong (hint: put a float right after the float3). Then pick scalar: every order matches C++, with no padding.

6The usual traps

Four traps you can see in the bytes. Blue is the C++ struct, purple is what the shader expects.

C++ v1 v2 12 std430 v1 v2 16

Two vec3 in a row

std430: the second starts at 16, not 12. A vec3 after a scalar moves in the same way (section 1).

Fix: use scalar layout, or put a float after each vec3 (a vec3 + float pair fills 16 bytes in every rule set), or use vec4.

C++: 16 bytes std140: 64 bytes 163248

Arrays of scalars in std140

float x[4] has a stride of 16: 64 bytes, not 16.

Fix: use vec4 x[1], or std430/scalar.

C++: 36 bytes c0c1c2 std140, std430: 48 bytes c0c1c2

mat3

48 bytes in std140/std430, 36 in C++.

Fix: scalar layout, or store a mat3x4 / three vec4.

C++: 1 byte next GLSL, HLSL, Slang: 4 bytes bool next

bool

1 byte in C++, 4 bytes in GLSL, HLSL and Slang.

Fix: use uint32_t on the CPU side.

And six more, without a picture:

Row-major vs column-major
The matrix arrives transposed. Pick one majorness for the shader compiler and match the math library (glm is column-major).
size_t, long, int
Their size depends on the platform. Use fixed-size types: uint32_t, int32_t, uint64_t.
A 64-bit field after an odd number of 4-byte fields
Both sides insert 4 hidden padding bytes. Fine if both do it, but a hand-written offset table forgets them. Keep 64-bit fields at offsets that are multiples of 8, with explicit padding fields.
The struct's end
A struct with a 64-bit field rounds its size up to 8 in C++. A GPU rule may round differently. Add an explicit padding field so the size is a multiple of 8 (or 16) on both sides.
Enums
The size of a plain C++ enum is up to the compiler. Use enum class E : uint32_t on both sides.
vec3 after a scalar
std140/std430 move it to the next 16; C++ does not (section 1). The fix is the same as for two vec3 in a row.

7Other APIs

API, memory kindRuleOur Example: where is b?
Vulkan GLSL, uniform bufferstd14016
Vulkan GLSL, storage bufferstd43016
Vulkan with scalar layoutscalar4
HLSL constant buffer16-byte "registers": a vector may not cross a 16-byte boundary; arrays and structs start a new register4 (4 + 12 = 16 does not cross)
HLSL structured bufferpacked, like scalar4
Metalfloat3 is 16 bytes, aligned to 16; packed_float3 is 12, aligned to 416 (or 4 with packed_float3)
WGSL (WebGPU)vec3 aligned to 16; uniform buffers add std140-like array rules16

8Push constants

Push constants are a few bytes written straight into the command buffer, the fastest way to give a draw small per-draw values. Their layout follows the same rules (std430 by default in Vulkan GLSL). Extra limits apply:

128 bytestotal size, at least, in Vulkan 1.0 to 1.3maxPushConstantsSize
256 bytesat least, in Vulkan 1.4. Many desktop GPUs allow 256.maxPushConstantsSize
× 4offsets and sizes are multiples of 4

The Direct3D 12 equivalent is root constants: the whole root signature is 64 DWORDs (256 bytes), shared with root descriptors and tables.

vertex stage: 0 to 32 fragment stage: 32 to 80 not declared 03280128 a push inside a range: fine a push past the range: refused
Ranges. The pipeline layout declares which byte ranges each shader stage sees. A push must stay inside a declared range. The numbers here are an example.

Because the space is small, a common design puts just one pointer (8 bytes) and a couple of indices there, and everything else in buffers. See Buffer device addresses.

9Making sure both sides agree

A layout mismatch gives no error by itself. So each project picks one or more ways to catch it:

C++ struct sizeof, offsetof static_assert: fails the build if a number changes shader struct the compiler's reflection API reports each field's offset and the struct's size compare at startup after each shader compile: size and every offset equal? if not: log and refuse
Offsets and sizes catch a moved field. They do not catch a uint on one side and a float on the other, or two swapped fields of the same size. For that, also compare each field's type.
Other ways

Generate one side from the other: a tool writes the C++ header from the shader's reflection, or the shader from a shared description. Or write the struct once in a header that both compilers read (HLSL and C++ can share simple structs).

10In RASM

RASM uses scalar layout for everything, so its C++ structs (with glm's default packing) and its Slang structs follow the same rules. The structs live twice: in src/renderer/uberMaterialTypes.h (namespace rasm::gfx) and in shaders/lib/core.slang. Two checks hold them together.

uberMaterialTypes.h C++, glm default packing struct SceneData { … } static_assert(sizeof(SceneData) == 2224) static_assert(offsetof(…) == …) compile time: pins the C++ side core.slang Slang, compiled at startup struct SceneData { … } session options: GLSLForceScalarLayout MatrixLayoutColumn validateRasmStructs after each link: reflection size + offsets vs C++ sizeof / offsetof every build: fails the shader How it finds the Slang layout pc scene lights, vertsPtr, drawInfoPtr, instancesPtr, geometryPtr → lods, materialsPtr → material → 4 parts
The two checks together catch a wrong size or a moved field, in every build. Field types are not compared. Slang reports scalar offsets only along this path. Asked directly, a type behind a pointer gets std140/std430 padding, so the check starts at the push constant and follows the fields (fieldStruct). A shader whose pc.scene is not SceneData is skipped.

The shared structs

StructBytesRead through
PushConstants16the push constant pc
SceneData2224pc.scene
Light68lightsPtr, the light table
ShadowMap72SceneData::shadowMaps, 16 of them
VertexFull64vertsPtr; also tied to rasm::Vertex
DrawInfo20drawInfoPtr, allDrawsPtr; also the indirect draw command
InstanceData160instancesPtr
GeometryData, GeometryLod, MorphDelta200, 20, 24geometryPtr; MorphDelta through AnimationFrame::morphs
MaterialData, Material, TextureTransform312, 84, 24materialsPtr
MetallicRoughnessMaterial, NormalMaterial, OcclusionMaterial, EmissiveMaterial40, 12, 12, 20the four parts of Material

What scalar layout buys: two real structs

StructScalar (used)std430 would giveWhere the difference comes from
GeometryData200 bytes224 bytesboundsCenter (a float3 at offset 4) would move to 16, and the size would round up to 16
InstanceData156 bytes176 bytesnormalMatrix (a float3x3) would be 48 bytes, not 36, and previousWorld (three float4s) would move from 108 to 128

SceneData, byte by byte

shadowMaps[16] · 16 × 72 grid 0 144 288 452 1824 2224 matrices, origin pointers planes, counts, runs, sizes, LOD → meshlet culling, grid ↓ 1604 to 2224: LOD camera, environment, lights, last frame, meshlets, origin, labels, grid
Scale: 700 px for 2224 bytes. The pointers (outlined) start at 144, a multiple of 8, so no hidden padding is needed before them; the last three are the light table, the scene's light list and the view's light clusters. The frustum planes fill 288 to 384; the 4-byte values from 384 (the seven run starts and the blend run among them) end with forcedLod at 448. shadowMaps (sixteen ShadowMaps of 72 bytes: a float4x4, a texture index and a split) fills 452 to 1604. The four ShadowedLights (12 bytes each), the two light counts, nearZ and depthSamples end at 1720. TAA's fields follow: previousViewProjection (a float4x4), jitter, textureLodBias and the 4-byte debugView end at 1800, so the last three pointers, animatedTransformsPtr (the Animate pass's matrices), skinnedVertsPtr and previousSkinnedVertsPtr (the Skin pass's vertices of this frame and the frame before), sit 8-aligned from 1800 and end at 1824. The nine pointers of meshlet culling follow, 1824 to 1896, then cullViewPoint, the three per-run arrays, meshletRuns, coneRuns and a padding word to 2008, and meshletDataPtr to 2016. The render space's originLow and the 4-byte zero (large worlds) end at 2032, and environmentOrientation, a float4, at 2048. labelsPtr, the view's label alphas (labels), ends at 2056. The camera's GridData (reference grid, 168 bytes of 4-byte values, its own zero last) ends at 2224, a multiple of 8: the next view's SceneData keeps its pointers aligned too (a static_assert checks it).

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Rule setstd140, std430 or scalarScalar for every buffer and the push constant: the Slang session option GLSLForceScalarLayout, and the device feature scalarBlockLayout.
Matricespick one majornessColumn-major on both sides: MatrixLayoutColumn in the session, glm on the CPU.
C++ sidea math library's default packingglm with no alignment options: vec3 is 12 bytes, mat3 36.
One definition or twogenerate, or share, or checkTwo hand-written copies, checked. Field names may differ: C++ Material::pbr is Slang metallicRoughness.
Compile-time checkstatic_assertThe static_asserts at the end of uberMaterialTypes.h, more in geometryPool.cpp (tying rasm::Vertex to VertexFull), and one per push-constant struct.
Reflection checkat startup, refuse on mismatchvalidateRasmStructs, in ShaderCompiler::compileFromString, on the layouts Slang reported after the link, or on the ones a shader cache entry stored with them, so a cached shader is checked like a compiled one. It checks a program whose push constants hold the scene (SceneData and every struct behind its pointers), and the engine passes' own push constants, found by name: ToneMapPushConstants, ResolvePushConstants, TaaPushConstants, BloomPushConstants, UiPushConstants, InspectPushConstants (with the InspectParams behind it), EnvironmentPushConstants and AnimatePushConstants. An application's own pipelines are not checked. It logs each mismatch, and the shader is not compiled, so its pipeline is not created and nothing reads the wrong layout. It runs in every build.
Layouts for toolsread the layout from the compilerEach compile keeps the fields of every struct its push constants reach, with the same walk (collectStructLayouts), and the shader cache stores them. The RASM window's GPU tables section prints rows with them, so no field list is written by hand (Inspecting GPU resources).
Type checkalso compare typesNot done (C11): a uint32_t against a float passes.
Explicit paddingkeep the end a multiple of 8Smaller structs have padding fields. In SceneData, the 4-byte debugView after textureLodBias also keeps animatedTransformsPtr 8-aligned: the size is 1824, a multiple of 8, which a static_assert checks. A new 4-byte field there needs a padding word with it.
Push constants≤ 128 or 256 bytes16 bytes, PUSH_CONSTANTS_SIZE: one range that the vertex, fragment and compute stages all see (and the task and mesh stages where the GPU has them), in the one pipeline layout every pipeline shares. RenderContext::pushConstants refuses a push past it. The stats overlay's OverlayPushConstants is 16 bytes too.
Shared constants—MAX_VIEW_SHADOWS, MAX_CLUSTER_LIGHTS, MAX_VERTEX_UV_SETS, MAX_MESH_LODS, MAX_DRAW_RUNS, MaterialId, LightType are written on both sides with the same values. Nothing checks them.

A mismatch shows up at startup, in any build, with messages in this form (from validateStruct), and the shader is not compiled:

Size mismatch for <struct>: C++ <bytes>, shader <bytes>
Offset mismatch for <struct>.<field>: C++ <offset>, shader <offset>

Shaders are compiled at startup

RASM compiles its Slang shaders when the engine starts, from EngineConfig::shaderDir, or reads them from its shader cache, whose key holds every shader file. So the check runs on every start, and a shader edit needs no build step. tools/compile-shaders.bat compiles every pass offline with the same flags (-force-glsl-scalar-layout, -matrix-layout-column-major), only as a syntax check; the engine does not use its output.

Where it lives in code

WhatWhere
C++ structs and static_assertssrc/renderer/uberMaterialTypes.h
Slang structsshaders/lib/core.slang
Session optionsShaderCompiler::initialize in src/renderer/shaderCompiler.cpp
The reflection checkvalidateRasmStructs, validateStruct, fieldStruct in src/renderer/shaderCompiler.cpp
Vertex tiessrc/renderer/geometryPool.cpp
Push-constant sizePUSH_CONSTANTS_SIZE in include/rasm/types.h; createPipelineLayout in src/rhi/vulkan/vulkanDevice.cpp; RenderContext::pushConstants in src/rhi/renderContext.cpp
Offline compile checktools/compile-shaders.bat
Keep these true
  • Change a shared struct on both sides in the same change: the C++ struct, the Slang struct, the static_asserts, and the table in validateRasmStructs. The gpu-struct-sync skill lists every place.
  • Run an example after the change: the reflection check runs at startup and logs any mismatch.
  • Never use bool, size_t, int or glm's aligned types in a shared struct.
  • Keep 64-bit fields at offsets that are multiples of 8, and the struct size a multiple of 8.
  • Compare the two definitions field by field by eye: types are not checked.
Not done yet

C11: the reflection check compares sizes and offsets, not types. The shared constants and enums are not checked at all.

Further reading