Foundations

Generational handles

An engine has many objects: meshes, textures, entities, buffers. Code outside the engine needs a way to name one of them, and to find out when the object it names is gone. A generational handle does both with two small numbers. This page explains how it works. The last part shows how RASM does it.

In short

  • A raw pointer breaks when the object moves or is freed. A plain index breaks when its slot is reused for a new object.
  • A handle is an index into a table of slots plus a generation: a counter that goes up each time the slot is freed.
  • A lookup checks that the handle's generation equals the slot's generation. If not, the handle is stale and the lookup fails safely.
  • Freed slots go on a free list and are reused, so the table does not grow forever.
  • A tag type makes a mesh handle and a texture handle different types, so the compiler stops you from mixing them.
  • A handle does not own its object. The table does. Destroying an object the GPU still uses must wait until the GPU is done.

1The problem: naming an object

An application asks the engine to load a mesh. The engine must give back something the application can keep and pass back later: "draw this mesh". There are three common choices.

p = &B A B C objects somewhere in memory

Pointer

The address of the object. Good: the fastest, no lookup at all.

Breaks when the object moves (an array grows, a level is compacted) or is freed. Using it then is undefined behaviour: a crash, or worse, wrong data.

i = 1 A B C 012

Index

A position in a table. Good: small (4 bytes), survives moves, easy to send to the GPU.

Breaks when the slot is reused. The old index now names a different object, and nothing notices. This is called the ABA problem.

h = {1, 1} A · 1 B · 1 C · 1 012

Generational handle

An index plus a generation. Good: small, survives moves, and detects reuse.

Breaks only when the generation counter wraps around (section 4).

The picture shows how each one fails. Follow B: it is named, then it goes away.

an object a new object in a reused slot wrong, and nobody notices detected
Pointer the address of the object A B p = &B array grows A B C p points to freed memory Index a position in a table A B i = 1 free B, then make D in the same slot A D i = 1 now means D, silently Handle index + generation A · 1 B · 1 h = {1, 1} the same: free B, make D A · 1 D · 2 1 ≠ 2: "B is gone", safely
The number after each object is its slot's generation. Only the handle can tell "the object I meant" from "a new object in the same place".

2The idea: index plus generation

The engine keeps each kind of object in a table of slots. Each slot stores the object and a generation number. A handle stores two numbers: the slot's index, and the generation the slot had when the handle was made.

handle index = 2 gen = 5 old handle index = 2 gen = 4 Table of slots index generation object 01mesh "rock" 13free 25mesh "tree" 31mesh "car" 5 = 5 → "tree" 4 ≠ 5 → stale
The old handle was made for an object that lived in slot 2 before "tree". That object was destroyed, so the slot's generation went from 4 to 5. The lookup is one array access and one compare. It is almost as cheap as a plain index.

The lookup in pseudo-code:

lookup(handle):
    if handle.index >= slots.size:
        return null                  // never made
    slot = slots[handle.index]
    if slot.generation != handle.generation:
        return null                  // stale: freed, maybe reused
    return slot.object

Two more rules make this complete:

slot 2 · destroyed gen 4 → 5 {2, 4} {2, 4} {2, 4} every copy: 4 ≠ 5 stale at once

Destroying adds 1 to the generation

Every handle made before is now stale, at once, without finding them.

default handle {0, 0} slot 0 · gen 1 slot 1 · gen 3 slot 2 · gen 1 0 is never a slot's generation: no match

Generation 0 means "no object"

Slots start at generation 1. So a handle that is all zeros, which is what a default-constructed handle is, never matches a slot. It is the handle version of a null pointer.

3Reusing slots: the free list

Without reuse, the table grows by one slot for every object ever made. A game that spawns and removes bullets would grow it forever. So a destroyed slot goes on a free list, and the next create takes a slot from it. The generation is what makes this reuse safe. Click through an example (or use the arrow keys).

1. Create A, B and C

slots Agen 1 Bgen 1 Cgen 1 012 free list empty handles A = {0, 1}B = {1, 1}C = {2, 1} The free list is empty, so each create adds a new slot at the end.

Each handle copies its slot's current generation.

2. Destroy B

slots Agen 1 freegen 2 Cgen 1 012 free list [1] handles A = {0, 1}B = {1, 1}C = {2, 1} stale: 1 ≠ 2 Nobody had to find the copies of B's handle. The generation alone makes all of them stale.

The object is destroyed, the generation goes up, the index goes on the free list.

3. Create D: it reuses slot 1

slots Agen 1 Dgen 2 Cgen 1 012 free list empty handles A = {0, 1}B = {1, 1}C = {2, 1}D = {1, 2} The table did not grow. B and D share index 1 but not the generation.

Create pops an index from the free list and uses the slot's current generation.

4. Look up B and D

slots Agen 1 Dgen 2 Cgen 1 012 lookup({1, 1}) slot 1 has gen 2, the handle has 1 → null: "B is gone" lookup({1, 2}) slot 1 has gen 2, the handle has 2 → D Without the generation, lookup({1}) would return D to code that still means B. That is the bug handles exist to stop.

The stale lookup fails in a defined way. The caller can log it, skip the work, or treat it as a bug.

Now run the same table by hand. It starts where step 1 ends.

a slot with an object a handle whose lookup works a free slot, or a stale handle that fails safely a lookup that returns the wrong thing
Click B to destroy it, then create an object: it gets slot 1 with generation 2, and the handle of B fails safely. Then turn the compare off and see what the same handle returns.
first free = 1 A → 3 C → 5 E end 012345

Where the free list lives

A free slot holds no object, so its memory can store the index of the next free slot. The free list then needs no extra memory: one "first free" index, and a chain through the free slots. This is an intrusive free list.

freed first → freed last stack 1 3 5 queue 1 3 5 reused next reused next

Which slot to reuse first

A stack (last freed, first reused) is simplest and keeps memory warm in the cache. A queue (first freed, first reused) spreads reuse over all free slots, so each generation grows more slowly. That delays the wrap-around of section 4.

4How many bits

Handles are often packed into one 32-bit or 64-bit integer, so they are cheap to copy, hash and store in GPU buffers. The bits are split between the index and the generation. The index bits limit how many objects can live at once. The generation bits limit how many times one slot can be reused before its generation wraps back to an old value.

32 bits index: 20 bits generation: 12 bits 32 bits index: 24 bits gen: 8 bits 64 bits index: 32 bits generation: 32 bits
The 64-bit row is drawn at half the scale of the others: each of its halves is as big as a whole 32-bit handle.
SplitObjects alive at onceReuses of one slot before a wrapWorst case: one slot reused every frame at 60 fps
20 + 12 bits220 = 1,048,576212 = 4,096wraps after 68 seconds
24 + 8 bits224 = 16,777,21628 = 256wraps after 4.3 seconds
32 + 32 bits232 ≈ 4.3 billion232 ≈ 4.3 billionwraps after 2.3 years

A wrap only causes a bug if old code still holds a handle from exactly one full cycle ago, and uses it. That is rare, but a small generation makes it possible. Two common fixes:

Agen 7 retiredgen = max Cgen 2 not on the free list again: one slot is lost, no handle can alias

Retire the slot

When its generation reaches the maximum, do not put it on the free list again. It is lost, but no handle can ever alias.

stack 7 1 1 queue 3 3 3 generation of 3 slots after 6 reuses

Spread the reuse

A queue-ordered free list (section 3) reuses each slot less often.

5Dense storage for fast loops

A table with holes is slow to loop over: the loop must skip the free slots, and the live objects are spread out in memory. Systems that loop over every object each frame (all entities, all particles) often add one more layer. This is usually called a slot map.

sparse slots what handles index gen 1→ 0 gen 2free gen 1→ 2 gen 3→ 1 slot 0slot 1slot 2slot 3 dense objects what loops read A D C no holes: a loop reads 3 objects in a row back array position → its slot slot 0 slot 3 slot 2 012
Lookup is now two steps (slot, then dense position) instead of one. In exchange, loops are as fast as over a plain array. A third array maps each dense position back to its slot (0 → 0, 1 → 3, 2 → 2).

Removing an object moves the last dense object into the hole ("swap and pop"), and the back array says which slot to repoint. The order of the dense array is not kept.

gen 1→ 0 gen 2free gen 1→ 2 gen 3→ 1 A D C remove D

Before

D sits in the middle of the dense array. Its slot is slot 3.

gen 1→ 0 gen 2free gen 1→ 1 gen 4free A C C moved

After "swap and pop"

C fills the hole, slot 2 is repointed, and slot 3 is free with a new generation. No object is skipped in a loop.

6Type-safe handles

A mesh handle and a texture handle are both "two integers". If they are the same C++ type, nothing stops code from passing a mesh handle to a function that wants a texture. The lookup then reads the wrong table, and may even pass the generation check by luck.

mesh handle {2, 1} bind a texture texture table 0 1 2 it compiles, and reads texture 2

One type for every handle

The compiler sees two integers. The mistake shows up at runtime, as the wrong texture.

MeshHandle {2, 1} wants a TextureHandle texture table 0 1 2 compile error: the types differ

A tag per kind of handle

The mistake never runs. The table is not touched.

The fix is a tag type: an empty type that is never defined and never used at runtime. It is only there to make each kind of handle a different type.

struct MeshTag;
struct TextureTag;

template <typename Tag>
struct Handle
{
    uint32_t index = 0;
    uint32_t generation = 0;
};

using MeshHandle = Handle<MeshTag>;
using TextureHandle = Handle<TextureTag>;

void bindTexture(TextureHandle texture);

Now bindTexture(mesh) is a compile error. The tag costs nothing: both types have the same two fields and the same size. This pattern is also called a phantom type or a strong typedef.

7Who owns the object

A handle is a weak reference. Holding it does not keep the object alive. The object belongs to its table, and it lives until someone calls destroy. This is different from a reference-counted pointer.

Raw pointerReference count (shared_ptr)Generational handle
Who decides when it diesWhoever calls deleteThe last holder to let goThe owner of the table, by an explicit destroy
Using it after the object diedUndefined behaviourCannot happen: it is still aliveDetected: the lookup fails
Cost of a copyFreeAn atomic add and later an atomic subFree
Can go into a GPU buffer or a fileNo, the address means nothing thereNoYes, it is just numbers

The GPU makes "destroy" harder

The CPU is usually one or two frames ahead of the GPU (see Frames in flight). When the CPU destroys a buffer, a frame that the GPU has not finished yet may still read it. Freeing the memory at once would let the GPU read garbage, or crash it. So engines split destroy into two parts:

CPU frame 10: destroy(h) frame 11 frame 12: wait for fence 10 GPU frame 9 frame 10: may read h 1. generation + 1: h is stale memory → delete queue (frame 10) fence 10 signaled 2. the GPU is done with frame 10: free the memory and the slot
Deferred destruction. The handle dies at once, so new code cannot use it. The memory dies only when the last frame that could use it has finished on the GPU.

The same delay matters for the slot. If the slot is reused too early, and the GPU still reads the old object's index from a buffer, the GPU reads the new object. So a slot whose index the GPU knows should also go back on the free list only after that fence.

8Handles for things made from a description

Some objects are fully described by their creation settings, and never change after. A compiled shader, a pipeline, a sampler and a descriptor layout are like this. If two parts of the program ask for the same one, they can share it. The table then keeps a second map: from the description to the handle. This is called interning or a dedup cache.

create(desc) pipeline, shader, ... hash(desc), then compare every field in the cache map equal found return the cached handle nothing is created not found create it, give a new handle store desc → handle in the cache
A hash finds the candidates fast. The full compare decides, because two different descriptions can have the same hash.
user 1: create user 2: create one pipeline read only the same handle twice

Dedup is right for immutable objects

Shaders, pipelines, samplers, layouts. Nobody writes into them after creation, so sharing one is the same as having two. It saves memory and creation time; a pipeline can take milliseconds to compile.

user 1: write user 2: write one buffer both write here they overwrite each other

Dedup is wrong for mutable objects

Buffers and textures. Two users that ask for "a 1 MiB storage buffer" want two buffers, because each will write its own data. Sharing one would make them overwrite each other.

Every field must take part in both the equality and the hash

A field that is left out of the compare makes two different descriptions look equal, and one user silently gets the other's object. A field left out of only the hash is still correct, just slower (more collisions).

Asset loading often uses the same idea one level up: a map from the file path to the handle. Loading the same file twice then gives the same mesh, and the file is read once.

9Pitfalls

Lookup checks only the index
Stale handles find the new object: the ABA bug is back. Fix: always compare the generation.
Slots start at generation 0
A zero-initialized handle matches slot 0. Fix: start at 1; keep 0 for "invalid".
Keeping a reference to the object across a create
The table may grow and move every object; the reference dangles. Fix: look the handle up again after anything that can create.
Freeing memory the GPU still reads
Garbage on screen, or a lost device. Fix: deferred destruction, tied to the frame fence.
Reusing a slot whose index is in a GPU buffer
The GPU reads the new object for one or two frames. Fix: return the slot to the free list after the fence, too.
Using a counter as the index (never reusing)
Simple, and stale handles are found by a hash-map miss. But a table indexed by it grows forever. Fine for objects that are rarely made. Use a free list for objects made every frame.

10In RASM

RASM uses one handle type for every object, Handle in include/rasm/handle.h, with an index and a generation. It has the type-safe tags of section 6. Every table hands out its handles from a HandlePool: the free list and the generation bump of sections 2 and 3.

HandlePool (one per table) allocate(), release(), isAlive() free list (last in, first out), generation + 1 registry.entityHandles buffers.handles Renderer::registry · CPU objects entities[handle.index] [0] unused [1] Entity [2] Entity [3] Entity … Also materials, cameras, meshes, lights, scenes, environments, readbacks. Every public call checks isLive: index and generation. A capped pool keeps MAX_* − 1 alive at most. loadedMeshes, loadedTextures: path → handle RenderContext::Impl · GPU objects objects[handle.index]: rhi::X* buffers rhi::Buffer* textures rhi::Texture* + shaders, pipelines, command buffers, fences, ... Lookup: compare the generation, then one array access. A stale handle logs an error, returns null. Buffers, textures, render targets can be destroyed.
No lookup hashes a handle any more (P4). A destroyed buffer or texture is freed later, when the GPU is done with it: see deferred destruction.

Two kinds of owner

CPU objects: Engine's registry

createEntity: registry.entityHandles.allocate() gives {3, 1}, or index 0 when MAX_ENTITIES − 1 entities are alive: then it warns and returns an invalid handle. registry.entities grows to the pool's size. The handle is the position in a vector, as in section 2, and isLive compares the generation.

GPU objects: RenderContext's tables

createBuffer: rhi::Device::createBuffer makes the object first (null on failure: an invalid handle). Then the table's pool gives a handle, and the object goes at its index. destroyBuffer releases the handle at once and frees the object once the GPU is done with it.

OwnerTypeLimitWhere the limit is
Engine registryEntityMAX_ENTITIES = 262,144 (218) (262,143 alive at once)include/rasm/entity.h
Meshno count limit; its sub-meshes take rows of the geometry table (EngineConfig::geometryPoolSubMeshes = 16384) and ranges of the geometry poolinclude/rasm/types.h
MaterialEngineConfig::maxMaterials = 4096 alive at onceinclude/rasm/types.h
CameraMAX_CAMERAS = 32 (31 alive at once)include/rasm/renderer.h
LightEngineConfig::maxLights = 16384include/rasm/types.h
SceneMAX_SCENES = 16 (15 alive at once)include/rasm/scene.h
Engine readbacksPendingReadbackno count limit; takeReadback releases its handlesrc/renderer/readback.h
RenderContext tablesbuffers, textures, pipelines, ...no count limit; at most RendererConfig::maxBindlessTextures (16384 by default) textures hold a bindless slot at onceinclude/rasm/types.h

Indices start at 1, so slot 0 is never used. That is why a pool with a cap holds one less than its limit: 31 cameras fit in 32. The cap counts live objects, since a released index comes back.

Meshes have no count cap. A mesh is refused only when its sub-meshes do not fit the geometry pool: one row of the geometry table per sub-mesh, and ranges of the vertex and index pools. The whole mesh is checked before anything is created.

the mesh registry: a std::vector, no count limit [0]unused [1]2 subs [2]1 sub [3]3 subs [4] [5] ...more meshes A0 A1 B0 C0 C1 C2 rows in use the geometry table: EngineConfig::geometryPoolSubMeshes rows 2 free new mesh D4 subs needs 4 rows, 2 free the geometry pool is full nothing is created
The same check covers the vertex, index, color, skin and morph pools, whose sizes are the other EngineConfig::geometryPool* fields. A mesh that does not fit logs what it needs and what is in use. createMesh then returns an invalid handle and uses no index; loadMesh has already returned a handle, so its mesh becomes failed.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Handle layoutindex + generation, often packed in 32 or 64 bitsTwo separate uint64_t fields: 16 bytes per handle. The C API packs them into one 64-bit id, generation << 32 | index (A stable C ABI).
Invalid handlegeneration 0The same: isValid is generation != 0, so {} is invalid.
Type safetytag typesThe same: Handle<Tag> with 23 tags, from MeshHandle to TileHandle. It is the only template RASM code may define.
Making a handlepop the free list, or add a slotThe same: HandlePool::allocate pops the free list (last released, first reused), or adds an index. The stack keeps the indices low, so the tables indexed by handle stay short.
Generation bump on destroyyesThe same: HandlePool::release adds 1. A slot whose generation reaches MAX_HANDLE_GENERATION (232 − 1) is retired, never reused, so every generation fits in 32 bits.
Stale handle detectioncompare generationsThe same: isAlive (also false for a free slot). RenderContext lookups log an error and fail; Engine's public calls check isLive.
Storageslot array, or a slot mapA slot array: a std::vector per type, indexed by index, for CPU objects and for the rhi:: pointers. Render targets are in a std::deque, so a reference survives a new target.
Deferred destructiona delete queue tied to the frame fenceThe same: destroyBuffer, destroyTexture and destroyRenderTargets release the handle at once and give the free, and a texture's bindless slot, to a release queue (deferred destruction).
Dedup cacheimmutable objects onlyshaderDescCache, pipelineDescCache, descriptorSetLayoutDescCache. Buffers and textures are always new (B1).
Path cachefile path → handleloadedMeshes (by path) and loadedTextures (by path and format) in the registry.

The dedup caches

Every creation descriptor in include/rasm/render/resource.h (ShaderDesc, PipelineDesc, BindlessDescriptorSetLayoutDesc, ...) has a defaulted operator==, so equality always compares every field. The hashes are written by hand in src/rhi/resource.cpp. ShaderDescHash hashes the name, the type, the entry point and the SPIR-V bytes; PipelineDescHash hashes the name, the four handles (with HandleHash), the topology, the color and depth formats, the blend mode, depth write and depth test, the sample count and alpha-to-coverage.

Because a pipeline's description holds shader handles, and equal shader descriptions give the same shader handle, two equal pipeline descriptions find each other too.

Two more details

Where it lives in code

WhatWhere
The handle, tags, aliases, hashHandle, HandleHash, hashCombine in include/rasm/handle.h
Making handlesHandlePool, HandleSlot in include/rasm/handle.h; src/core/handle.cpp; tests in tests/handleTests.cpp
CPU objectsRenderer::Registry in include/rasm/renderer.h; createEntity in src/scene/entity.cpp, loadMesh in src/assets/mesh.cpp, createMaterial in src/assets/material.cpp
GPU objects and lookupsRenderContext::Impl, lookup in src/rhi/renderContext.cpp
DestroyRenderContext::destroyBuffer, RenderContext::destroyTexture in src/rhi/renderContext.cpp; Renderer::destroyTexture in src/assets/texture.cpp
Dedup cachescreateShader, createPipeline, createBindlessDescriptorSetLayout in src/rhi/renderContext.cpp
Descriptor hashesShaderDescHash, PipelineDescHash, BindlessDescriptorSetLayoutDescHash in src/rhi/resource.cpp
Keep these true
  • A new field in ShaderDesc, PipelineDesc or BindlessDescriptorSetLayoutDesc is compared by the defaulted operator== on its own, but must also be added to its hash in src/rhi/resource.cpp.
  • Never add dedup to createBuffer or createTexture (B1). Cache at the asset level, and destroy what you replace.
  • Free GPU objects and bindless slots through the release queue, never at the destroy call.
  • A default handle ({}) means "none". Check isValid before using a handle that a create may have failed to fill.
Every object can be destroyed

Every table frees and reuses its indices. A generation never passes MAX_HANDLE_GENERATION: a slot that reaches it is retired, which costs one index after four billion reuses of that slot, and never wraps. loadMesh needs its handle before the file is parsed (it returns at once), so a file that does not parse keeps its index until destroyMesh frees it.

Further reading