Engine tour

The GPU scene tables

The scene lives on the GPU as a few tables of fixed-size rows. A draw names an instance row, and the instance row names a geometry row and a material row. The CPU changes a row only when something changed, and syncGpuScene uploads the changed rows once per frame.

This is stop 3 of the engine tour, after the big picture and one frame. It shows RASM's tables and how the objects you create get into them. Why a renderer keeps its scene on the GPU like this is in GPU-driven rendering and indirect draws.

CPU work GPU work / drawn GPU buffer

In short

  • Engine-wide tables: geometry (one row per sub-mesh), material (one row per material), instance (one row per entity × sub-mesh). Per scene: a draw list of DrawInfo.
  • An entity gets its instance rows once its mesh is loaded. It joins the draw lists once every texture it uses is loaded. Nothing is drawn half-loaded.
  • syncGpuScene runs once per frame, after the fence wait. It gives rows to new entities, rebuilds the draw lists that changed, and uploads this frame slot's dirty rows.
  • A draw list is sorted into up to 7 runs by alpha mode and cull mode, because the pipeline and the cull mode are set per indirect draw.
  • A row's cull mode comes from its material (doubleSided) and the sign of its matrix's determinant.

1The tables and their row pointers

Rows point to other rows by index. Follow one draw, d1, through the tables:

Draw list per scene and frame slot d0 d1 indexCount = 36 firstIndex = 120 vertexOffset = 48 firstInstance = 3 d2 DrawInfo, 20 B · the range of LOD 0 Instance table GpuTable, one copy per frame slot row 0 row 1 row 2 row 3 worldMatrix normalMatrix geometryIndex = 7 materialIndex = 2 previousWorld, animationRow row 4 InstanceData, 160 B Geometry table one copy, in the geometry pool rows 0 … 6 row 7 vertexOffset boundsCenter boundsRadius lodCount lods[8]: index ranges rows 8 … Material table GpuTable, row = material index rows 0 … 1 row 2 material factors + bindless texture slots materialId Geometry Index Pool fetched by the draw Geometry Vertex Pool pulled by vertMain
The draw itself carries the index range and the vertex offset, so drawing does not read the geometry table. Only cull.slang reads it, for the bounding sphere and the LOD ranges: culling swaps the draw's firstIndex and indexCount for the chosen LOD's (LOD selection). vertMain pulls its vertices from the pool by index (vertex pulling). A material row holds bindless slot numbers, not textures.

The picture shows how many buffers each table has, and who writes it. The table under it has the details.

a buffer written by the CPU written by the GPU
frame slot 0 frame slot 1 written by Geometry table one buffer, in the geometry pool CPU, once per sub-mesh Material table CPU: writeMaterialRow Instance table CPU: writeInstanceRows Draw list · one per scene CPU: uploadDrawList Scene data · a row per scene view CPU: prepareSceneView Visible draws · one per scene view GPU: writeMain Hi-Z · one per scene view GPU: hizMain Visibility · one per scene view one buffer, shared by both slots GPU: late countMain
A table the CPU rewrites has one buffer per frame slot, so the CPU never writes a buffer the GPU still reads. The geometry table needs one copy: no frame has read a new row yet.
TableBuffersRowsWritten by
Geometry
GeometryData, 200 B
one, in the geometry pool (tableBuffer)geometryPoolSubMeshes (214)upload of the geometry pool, once per sub-mesh, with one GeometryLod per LOD. No frame has read a new row yet, so one copy is enough.
Material
MaterialData, 304 B
GpuTable, one per frame slotEngineConfig::maxMaterials + 1 rows; row = material handle index, reused at once by the next materialwriteMaterialRow
Instance
InstanceData, 160 B
GpuTable, one per frame slotmaxInstances (216), bump-allocatedwriteInstanceRows. animationRow names the row's InstanceTransform while a clip moves its sub-mesh, −1 otherwise.
Animated entities
AnimatedEntity, 120 B
GpuTable, one per frame slotmaxAnimatedEntities (214), a row from an entity's first play, or from its instance rows for a skinned or morphed meshwriteAnimationRow, on play, stop or move (keyframe animation)
Morph weight overrides
float, 4 B
GpuTable, one per frame slotmaxMorphWeights (216), a range per posed entity of a morphed meshwriteMorphWeightRows, on setMorphWeights and clearMorphWeights; a quiet NaN where the clip's weight counts (morph targets)
Morph weights
float, 4 B
one per frame slotmaxMorphWeights (216), the same rangesthe GPU: the Animate pass writes each weight, which the Skin pass reads
Animated transforms
InstanceTransform, 172 B
one per frame slota range per playing entity; grows ×2the GPU: the Animate pass, before any view; a skinned or morphed sub-mesh's row also has its posed bounds and its first skinned vertex
Skinned vertices
VertexFull, 64 B
one per frame slota range per posed skinned or morphed entity, each sub-mesh from a multiple of 64; grows ×2the GPU: the Skin pass, once per frame before any view (skinning)
Draw list
DrawInfo, 20 B
buffers in SceneDrawList, one per frame slot and scenegrows ×2 when too smallrebuildDrawList, then uploadDrawList
Visible drawsvisibleDraws in SceneView, per frame slot and scene viewgrows ×2 in place (resizeBuffer, same handle) when too small; culling's scratch and the draw counts (MAX_DRAW_RUNS uint32_ts, written by writeMain) follow the drawsthe GPU: writeMain packs the kept draws (stream compaction)
Visibilityvisibility in SceneView, one per scene view, shared by both frame slotsmaxInstances uint32_ts, one per instance row, 0 at startthe GPU (late countMain, occlusion culling)
Hi-Zhiz in SceneView, per frame slot and scene viewfloats, all levels of the target's size; grows in place when the target is biggerthe GPU (hizMain)
Label alphas
float, 4 B
labelBuffers in SceneView, per frame slot and shaded scene viewone per label slot up to the highest in use, grows ×2 (at most MAX_LABELS)placeViewLabels, every frame (Text and labels)
Scene datasceneData, one per frame slot, hostVisibleMAX_SCENE_VIEWS = 32 SceneData, one per scene viewprepareSceneView, every frame, at the start of the view's Cull pass

All of these are created once, in createGpuScene and GeometryPool::create, except the draw-list buffers, which grow on demand, and the buffers of a scene view. A scene view is one (scene, camera, target) that addScenePasses draws; it is made the first time a graph adds its passes (createSceneView), and its visible-draw and Hi-Z buffers start small and grow in place, so the handles the passes declared stay valid. How a GpuTable uploads only its dirty rows, per frame slot, is in GPU memory and uploads.

See the tables while it runs

With EngineConfig::ui, the RASM window's GPU tables section lists each GpuTable above (rows used, capacity, bytes per slot, and GpuTable::uploadedRows: rows sent this frame) and shows one entity's instance, material and animated entity rows field by field. The field names, types and offsets come from the shader compiler's reflection (ShaderCompiler::findStructLayout), and the values from GpuTable::row, the CPU copy every slot receives: what was uploaded, not a readback. See Inspecting GPU resources.

How a shader finds the tables

No table is bound. The push constant points to this scene view's SceneData, and SceneData points to every table of this frame slot. So a shader follows two pointers to reach any row (Buffer device addresses).

PushConstants scene + firstDraw, argument SceneData one per scene view vertsPtr geometryPtr instancesPtr materialsPtr allDrawsPtr drawInfoPtr drawCountsPtr visibilityPtr hizPtr Geometry Vertex Pool Geometry table Instance table, this slot Material table, this slot the scene's draw list, this slot visible draws, this view draw counts, this view's part visibility flags, this view Hi-Z, this view The index pool is bound as the index buffer, not reached by pointer.
Culling also gets cullSlotsPtr and groupCountsPtr (its scratch, after the visible draws in the same buffer) and cullStatsPtr. Without culling, drawInfoPtr points to the draw list itself. Every row struct has a twin in core.slang with the same bytes: see Struct layout rules.

2The life of an entity

createEntity with a valid mesh queued waiting for mesh entitiesWaitingForMesh mesh still LOADING: check next frame mesh state? FAILED never drawn mesh FAILED: warning no room in table: error READY gets its rows one per sub-mesh, written table full waiting for textures entitiesWaitingForTextures a texture still loads in the draw lists of every scene that holds it all loaded all loaded a new texture loads updateTransform: rows rewritten, same state
The states are lists and flags in GpuScene. A destroyed entity, or one whose mesh is destroyed, gives its rows back (releaseEntityRows). An entity with an invalid mesh handle is never queued and never gets rows.
StateWhere it is storedLeaves it when
Waiting for meshentitiesWaitingForMesh (from queueInstanceRows)its mesh is no longer MeshState::LOADING
Has rowsEntityDrawState: firstInstance, instanceCountnever (rows stay for the engine's life)
Waiting for textureswaitingForTextures = true, and entitiesWaitingForTexturesa texture load finished (texturesFinished) and all of its textures are loaded
In the draw liststhe entity's scenes bits (one per scene that holds it)updateMaterial gives it a texture that still loads

"Its textures" means every texture of every sub-mesh's material: the primitive's material, or else the entity's. An invalid material handle resolves to the default material (getSubMeshMaterial, getMaterial). An entity that is in no scene still gets rows, but no draw list holds it.

3syncGpuScene, step by step

It runs in beginFrame, after finishLoads, the fence wait, updateFrameStats, and updateStatsOverlay or, with EngineConfig::ui, buildUi:

  1. loadsfinishLoads
  2. fence waitfor this slot
  3. stats, UIupdateFrameStats; updateStatsOverlay or buildUi
  4. scene syncsyncGpuScene: this section

Here is one call, in a scene with four entities. Click through (or use the arrow keys).

1. Before: what is waiting

entitiesWaitingForMesh entitiesWaitingForTextures scene 1 draw list e1ready e2ready e3loading e4loaded rebuild = false staleSlots = 00 texturesFinished = true instance table rows (instanceCount = 2) e4 e4 012345

Scene 1 holds e1, e2, e3, e4 (in that order). e1's mesh has 2 sub-meshes, e2's has 1. e4 got rows 0 and 1 in an earlier frame, but one of its textures was still loading. That texture finished in this frame's finishLoads.

finishLoads made the meshes of e1 and e2 READY and set texturesFinished, at the start of beginFrame.

2. Entities whose mesh is ready get rows

entitiesWaitingForMesh entitiesWaitingForTextures scene 1 draw list e3loading e4loaded e2loading rebuild = true staleSlots = 00 texturesFinished = true instance table rows (instanceCount = 5) e4 e4 e1 e1 e2 012345

e1: rows 2–3, written with setRow (both slots dirty). All its textures are loaded, so markDrawListsDirty sets scene 1's rebuild.
e2: row 4, written too, but a texture still loads: it moves to the textures list.
e3: its mesh still loads, so it stays.

Rows are a bump allocation: firstInstance = instanceCount, then instanceCount grows by the sub-mesh count. If the table has no room, the entity logs an error and leaves the list without rows.

3. A texture finished: check the waiting entities

entitiesWaitingForMesh entitiesWaitingForTextures scene 1 draw list e3loading e2loading e4drawable rebuild = true staleSlots = 00 texturesFinished = false instance table rows (instanceCount = 5) e4 e4 e1 e1 e2 012345

The list is checked only when texturesFinished is set, and the flag is cleared first. A frame with no finished texture skips this step.
e4: all loaded → waitingForTextures = false, markDrawListsDirty.
e2: its texture still loads, so it stays.

The rows of e4 do not change here. Only its draw-list membership does.

4. Rebuild the dirty draw lists

entitiesWaitingForMesh entitiesWaitingForTextures scene 1 draw list e3loading e2loading rebuild = false staleSlots = 11 scene 1 draw list (CPU), in scene order, then sorted into runs row 2 row 3 row 0 row 1 e1e4 e2 waits for textures, e3 has no rows: no draws

rebuildDrawList walks the scene's entities in order and adds one DrawInfo per drawable sub-mesh (firstInstance = its row). Then it stable-sorts by alpha mode and cull mode into runs, and marks the list stale in both frame slots.

The whole list is rebuilt, not patched. Its cost grows with the number of entities in the scene (P7). Only scenes with the rebuild flag do it.

5. Upload this frame slot

frame slot 0 (frameCount = 0) instances.upload rows 2, 3, 4 → one range materials.upload dirty rows, if any uploadDrawList every list stale in this slot Instance Table 0 Material Table 0 Draw Info Buffer, slot 0

Each goes through fillBuffer. After the upload, scene 1's staleSlots = 10: slot 1 still has the old list. The next frame runs in slot 1, and the same three calls bring slot 1 up to date.

The upload runs after the fence wait for this slot, so no GPU work still reads these buffers. A change made after beginFrame (for example updateTransform while recording) reaches the GPU in the next frame.

The last step uploads one frame slot only. Try it on a small instance table of 8 rows (RASM's has maxInstances rows). The meshes here are already loaded, so a new entity gets its rows in the next frame.

the CPU copy (shadow) buffer row, up to date dirty: the buffer holds old data uploaded by the last frame
Click a row of the CPU copy to move its entity (updateTransform): its rows become dirty in both buffers. Press "Next frame" and count the frames until both buffers are clean again. Then add entities with createEntity until the table is full.

4Draw lists and runs

draw list, scene order e1 · 0NONE · BACK e1 · 1NONE · NONE e2 · 0MASK · BACK e3 · 0NONE · FRONT e3 · 1NONE · BACK e4 · 0BLEND stable sort by alpha mode (NONE, MASK, BLEND), then cull mode (NONE, FRONT, BACK) after the sort e1 · 1NONE · NONE e3 · 0NONE · FRONT e1 · 0NONE · BACK e3 · 1NONE · BACK e2 · 0MASK · BACK e4 · 0BLEND run 0first 0, count 1 run 1first 1, count 1 run 2first 2, count 2 run 3first 4, count 1 run 4 · blendfirst 5, count 1 The blend run always has cull mode NONE, so it is one run that can be drawn in one sorted order.
The sort order is the order of the AlphaMode values, then of the CullMode values. Within a run, draws keep their scene order. drawSceneView sets each run's pipeline and cull mode and issues one indirect draw per run; a shaded view leaves the blend run to its Transparent pass, which draws it sorted back to front (transparency).

A run is a DrawRun {alphaMode, cullMode, first, count}. There are at most MAX_DRAW_RUNS = 8 runs: three cull modes for each of NONE and MASK, the point run (point cloud chunks, and the glyph chunks the glyph cull draws: point clouds, instanced glyphs) and one BLEND run (a static_assert ties the numbers together). A draw is skipped, with a warning when the entity gets its rows, if its sub-mesh has no vertices or no indices.

When a draw list is rebuilt

SceneDrawList::rebuild is set in two places:

How a draw list reaches the GPU

the CPU list a slot's buffer, up to date a slot's buffer, still the old list
after the rebuild draws: new buffers[0]old buffers[1]old staleSlots = 11 after slot 0's frame draws: new uploadDrawList buffers[0]new buffers[1]old staleSlots = 10 after slot 1's frame draws: new uploadDrawList buffers[0]new buffers[1]new staleSlots = 00 Each slot uploads in its own frame, after its fence wait.
One bit of staleSlots per frame slot. A set bit means that slot's buffer is older than the CPU list.
  1. Rebuild sets staleSlots to both bits. The CPU list in draws is now newer than both slot buffers.
  2. Each slot uploads in its own frame. uploadDrawList writes draws into buffers[frame] and clears that slot's bit. If the buffer is too small, it destroys it and creates one with max(drawCount, capacity × 2) rows. Only this slot's last frame used the old buffer, and the fence wait covered it.
  3. prepareSceneView skips a list that is not ready. If the list is empty, or this slot's bit is still set (the upload failed), the scene passes record nothing this frame and the target keeps its clear color.

5The cull mode of a row

Each instance row gets one of the three cull modes. Why a mirrored object must cull its front faces is in Face culling and winding order. Here is how RASM picks the mode:

getCullMode per sub-mesh row material doubleSidedor BLEND? yes NONE no det < 0? mirrors yes FRONT no BACK
Front faces are counter-clockwise. A mirroring transform (negative determinant) turns them clockwise, as glTF specifies, so the row culls FRONT instead.
both sides are drawn

NONE

The material is doubleSided, or see-through (BLEND), whose single-sided back faces the shader drops. Nothing is culled.

mirrored: front is clockwise

FRONT

Not double-sided, and the determinant is negative: the transform mirrors.

front is counter-clockwise

BACK

Every other row: the usual case.

det = scale.x · scale.y · scale.z · det(mat3(sub-mesh transform))

scale
the scale of the entity's Transform
det(mat3(…))
the determinant of the sub-mesh's own transform

The determinant needs no matrix multiply: the entity's Transform is translate × rotate × scale (Transform::toMatrix), and a rotation has determinant 1. The cull mode and the material's alpha mode are kept per row on the CPU in instanceCullModes and instanceAlphaModes; the GPU never sees them. updateDrawModes recomputes them when the transform or the material changes, and marks the draw lists dirty only if some row's mode changed.

6You call X → this gets uploaded

You callCPU sideReaches the GPU
createEntity with a meshqueueInstanceRows: onto the mesh listIts instance rows, once the mesh is READY. Its scenes' draw lists, once its textures are loaded.
addEntityToScenesets the scene's bit in scenesThat scene's draw list, if the entity is already drawable.
updateTransformwriteInstanceRows: setRow for each sub-mesh, then updateDrawModesOnly that entity's rows, in each slot's next frame. Draw lists only if a cull mode changed.
createMaterial, glTF loadMaterialwriteMaterialRowOne material row.
updateMaterialwriteMaterialRow; refreshEntitiesAfterMaterialChange if doubleSided changed or a texture still loadsThe material row (same row index, so no instance row changes). Draw lists of entities that change cull mode or start waiting.
a texture load finishesfinishLoads sets texturesFinishedDraw lists of entities that become drawable.
a mesh load finishes, or createMeshfinishMeshLoad or createMesh: GeometryPool::upload. The LODs were built before, by buildMeshLods.The vertices, the indices of every LOD, and one geometry row per sub-mesh, once.
createLight, updateLightwriteLightRow: setRow on the light table; markLightListsDirty when a light gains or loses its rangeOne light row. The scene light lists only when a light moved between global and local (clustered lighting).
setMorphWeights, clearMorphWeightswriteMorphWeightRows: setRow on the morph weight override table, one per weight; writeAnimationRow when the motion resetsThe entity's weight rows, uploaded by syncGpuAnimation from syncGpuScene.
addLightToScenesets the scene's bit in lightScenes, marks its light listThat scene's light list: global rows, then local ones.
addScenePassesfinds or makes the scene view (createSceneView); its Cull pass calls prepareSceneView, which fills the view's SceneData every frameAt once (the scene data buffer is hostVisible).

A row is uploaded twice, once per frame slot, and only its newest value is sent. Moving one entity in a scene of ten thousand uploads that entity's rows, not the table. Material changes are rare, so refreshEntitiesAfterMaterialChange checks every entity instead of tracking who uses the material.

7Where it lives in code

WhatWhere
State: tables, lists, draw lists, scene viewsGpuScene, EntityDrawState, SceneDrawList, DrawRun, SceneView in src/renderer/gpuScene.h
Creating the tablesRenderer::createGpuScene in src/renderer/gpuScene.cpp; GeometryPool::create in src/renderer/geometryPool.cpp
The per-frame syncRenderer::syncGpuScene, called from Renderer::beginFrame in src/renderer/renderer.cpp
RowsqueueInstanceRows, writeInstanceRows, updateDrawModes, writeMaterialRow, getCullMode in src/renderer/gpuScene.cpp
Draw listsaddEntityToDrawList, markDrawListsDirty, rebuildDrawList, uploadDrawList in src/renderer/gpuScene.cpp
Callerssrc/scene/entity.cpp, src/scene/scene.cpp, src/assets/material.cpp
Row structssrc/renderer/uberMaterialTypes.h and shaders/lib/core.slang
Table pointersRenderer::prepareSceneView fills SceneData in src/renderer/gpuScene.cpp; read by shaders/passes/rasm.slang and shaders/passes/cull.slang
The light table and the scene light listsGpuLights in src/renderer/lightClusters.h; Renderer::syncGpuLights, called at the end of syncGpuScene
LODs of a meshbuildMeshLods in src/assets/meshLod.cpp; the rows in GeometryPool::upload

8Rules when you change it

Keep these true
  • Change table rows only through GpuTable::setRow (or set a draw list's rebuild). Slot buffers are written only in syncGpuScene, after that slot's fence wait.
  • Only gpuScene.cpp touches GpuScene. Other files call the Engine methods (queueInstanceRows, writeInstanceRows, writeMaterialRow, addEntityToDrawList, refreshEntitiesAfterMaterialChange).
  • An entity joins a draw list only with rows and all textures loaded. Keep that check in both addEntityToDrawList and rebuildDrawList.
  • EntityDrawState::scenes has one bit per scene, so MAX_SCENES must stay at most 16 (a static_assert checks it).
  • The run order is the order of AlphaMode, then of CullMode, and MAX_DRAW_RUNS must equal 2 × the cull modes + 2 (the point run and the blend run). The blend run is last and has cull mode NONE.
  • Changing InstanceData, MaterialData, GeometryData or DrawInfo is a CPU↔GPU struct change: follow the struct contract.
Known limits

A scene with a changed entity rebuilds its whole draw list (P7), and so does a scene an entity leaves. Scene handles start at 1, so 15 of the MAX_SCENES scenes are alive at most. Pools fragment and are not defragmented.