Foundations
Deferred destruction
A program that streams content (map tiles, game levels) destroys textures and buffers all the time. But when the CPU destroys an object, the GPU may still be running a frame that reads it. Deferred destruction splits destroy in two: the name of the object dies at once, and its memory dies later, when the GPU has finished every frame that may use it. This page explains how to know when that is. The last part shows how RASM does it.
In short
- The CPU is one or two frames ahead of the GPU. An object destroyed in frame n may still be read by frames n − 1 and n.
- Destroy has two parts. The handle dies now, so no new work can use the object. The memory dies later.
- "Later" is a fence value: the value the queues signal when the frame that was recorded at the destroy is done. Every queue counts, and so do uploads.
- A release queue holds what waits. Each frame end gives the new entries their values; each frame start frees the entries whose values the fences reached. Nothing waits on the CPU.
- What the GPU finds by a number (a bindless slot, a pool range, a table row with one copy) waits too. Data with one copy per frame slot can be reused at once.
- Freed ranges of a pool go on a free list that joins neighbours. Reuse brings fragmentation: free space split into holes.
- Users of a destroyed object fall back to a default, objects made for one owner die with it, and what a renderer still draws is refused.
- When nothing was destroyed, the queue is empty and costs nothing.
1The problem: the GPU is behind
With frames in flight, the CPU records frame 12 while the GPU still runs frame 11. Look at texture T: frame 11 samples it, and frame 12 has already recorded draws that sample it. Now the program destroys T in frame 12.
Waiting until the GPU is idle at every destroy would work, but it stops the CPU for a whole frame. A program that destroys ten tiles a frame would never overlap the CPU and the GPU again.
2The idea: two deaths
Destroy frees at once
Simple, and wrong whenever a frame in flight uses the object.
The handle dies now, the memory later
New code can't use T: its generational handle is stale. Old frames still can.
An object may be freed only when every piece of GPU work that was submitted, or recorded, before the destroy has finished.
3When is "later"? Fence values
A timeline fence is a counter on the GPU. Each submit signals the next value when its work is done, and the CPU can read the counter without waiting (frames in flight). So "later" is a list of values, one per counter that work on the object may be behind:
The graphics queue
The frame's last graphics submit. It covers everything the frame drew.
Every other queue
Work on a second queue can run after the graphics work. Its own counter says when it is done.
Uploads
A copy into the object may have been sent after the frame. It must finish before the memory goes.
The values to wait for are the ones the counters signal after the destroy: the end of the frame being recorded. They are not known at the destroy call, only once that frame is submitted. So the frame end hands them out:
- destroyThe handle dies. The free waits, with no values yet.
- end of the frameAfter the submits: each waiting free gets the values the counters signal last.
- the GPU runsThe counters reach those values, one by one.
- start of a frameRead the counters; free every entry whose values they all reached.
A frame whose submit failed, or that was never submitted, runs nothing. Its frees take the values the counters signaled last, from the frames before. They cover all work that was ever sent, so the frees are still safe.
4The release queue, step by step
The release queue is a list of frees in order. New ones wait at the back with no values. Since the values only grow, the queue is sorted by them, and the frame start stops at the first entry that is not done.
Frame 12: destroy T
The handle of T is stale from now on. The image and its slot stay as they are.
End of frame 12: tag
The entry gets the values of frame 12's submits, and the uploads' last ones.
Start of frame 13: not yet
Reading a counter does not wait. The frame goes on.
Start of frame 14: free
With two frames in flight, an object is freed about two frame starts after its destroy.
Try it. Destroy a texture, then make a new one, and press "Next frame" until the GPU is done. Then turn the queue off and do the same.
5What waits, and what can be reused at once
Memory is not the only thing the GPU finds again later. Anything the GPU looks up by a number must not change its meaning while a frame in flight may look it up.
Memory: waits
Buffers, images, the heaps they are placed in.
Numbers with one copy: wait
A bindless slot, a range of a shared pool, a row of a table with one copy.
One copy per frame slot: at once
A row may take a new object now. The frame in flight reads its own copy, which is written only after its fence.
Shared immutable objects: kept
A deduplicated pipeline or shader may have other holders. They are few, so they live as long as the device.
6Reusing ranges of a pool
A GPU-driven engine keeps all meshes in a few big buffers: one for vertices, one for indices, a table with a row per sub-mesh. A mesh takes a range of each. When meshes only come, a counter at the end is enough. When they also go, the freed ranges must come back, or a streaming program fills the pool in minutes.
First fit
Walk the free list from the start; take the first range that is large enough. Simple, and keeps the end free.
Best fit
Take the smallest range that fits. Leaves big ranges whole, but needs the free ranges sorted by size too.
A second index to keep.
Size classes
Round each request up to a power of two, one free list per size. Fast, never searches, but wastes up to half of a range.
Fragmentation is the cost of reuse: the free space is split into holes. A request can fail although the holes add up to more than it needs. Try it: free every other range, then ask for a large one.
Size the pool with room to spare, so a hole is usually found. Keep ranges of one object together, so they go together. Report the largest free range when a request fails, not only the total, or the error looks impossible. Moving live ranges to close the holes (defragmenting) needs every user of an offset to be updated, and is a step most engines take only when a pool is close to full.
7What uses a destroyed object
An object can be destroyed while other objects still name it: a material that entities use, a mesh with entities on it, a texture in a material. There are three answers, and an engine usually mixes them:
Leave it
The user keeps a stale number. If the slot is reused, it uses the new object: the ABA bug, on the GPU.
Fall back
Users let go and take a default: no material, no texture, nothing to draw. The engine must find them, so it counts them.
Own it
What an import made belongs to what was imported, and is destroyed with it. Nobody else is expected to keep it.
Refusing is a fourth answer, for objects whose users are few and important: a camera or a scene that a render graph still draws. A clear error that says what holds it is better than a frame that silently draws nothing.
8Pitfalls
- Garbage or a lost device a frame after a destroy
- The memory was freed while a frame in flight read it. Free through the queue, never at the call.
- The wrong texture flickers on old objects for one or two frames
- A slot or a range was reused before the frames that knew the old meaning were done. Its release must wait too, not only the memory.
- A free that never happens
- It waits for a value nothing will signal: taken before the submit, or for a submit that failed. Tag at the end of the frame with the values the counters really signaled last.
- Memory grows while the window is minimized
- No frame runs, so a queue that is tagged and collected only inside a frame never moves. Between frames nothing is being recorded, so a free may take the values signaled last at once: tag and collect also where a skipped frame still passes.
- A copy writes into freed memory
- An upload sent after the frame still writes the object. Its counter is one of the values to wait for.
- A full pool, although half of it is free
- Fragmentation: no single hole is large enough. Join neighbours when freeing, size the pool with room to spare, and report the largest free range.
- The frame stalls at a destroy
- A wait for the device to be idle at each destroy. Read counters, never wait on them, to decide what to free.
9In RASM
Every object can be destroyed. RenderContext::destroyTexture, destroyBuffer and destroyRenderTargets (and Renderer::destroyTexture, Renderer::destroyBuffer, Renderer::destroyRenderTarget for applications) release the handle at once and give the free to a rhi::ReleaseQueue; the other destroy* calls give it what the GPU reads by number through RenderContext::releaseAfterGpu. Renderer::endFrame tags the queue after submitBatches, and Renderer::beginFrame collects it after the fence wait of the frame slot. Nothing waits on the CPU.
Each destroy call
| Call | Waits for the GPU (release queue) | Reused at once | Users fall back |
|---|---|---|---|
destroyEntity | nothing | its instance rows; its animated row and its ranges of the animation buffers (written as stopped, clip −1, which the passes skip) | its scenes rebuild their draw lists without it |
destroyMesh | its ranges of the five geometry streams, its geometry table rows, its animation pool range | its index | entities on it draw nothing (searched only while Mesh::users is not 0); its import's materials and textures are destroyed with it |
destroyMaterial | nothing | its row of the material table | entities made with it, and its mesh's sub-meshes, take the entity's or the default material; their rows are rewritten (searched only when something uses it) |
destroyTexture | the image and its bindless slot | its index | materials that use it lose it |
destroyLight | nothing | its row of the light table | its scenes rebuild their light lists; a shadow made for it casts nothing |
destroyEnvironment | its image, cubes and four slots | its index | scenes that use it have none |
destroyCamera, destroyScene | a scene's draw list and light list buffers | the index (the scene's bit in every entity and light is cleared first) | refused while a render graph draws a view of them; Renderer::render's graph lets go first |
The pools are RangeAllocators (src/core/rangeAllocator.cpp): a std::map of free ranges by offset, first fit, joining neighbours on free. The geometry pool has one per stream and one for its table rows; a mesh takes every range of every sub-mesh before it writes anything, and gives all back if one does not fit. The instance table, the animated entity table's ranges and the animation pool have one each. examples/17_streaming pushes thousands of tiles through pools sized for about two windows of them, and Renderer::getPoolStats stays flat.
Where RASM follows this page, and where it differs
| Part | This page | RASM |
|---|---|---|
| Handle | dies at the call | The same: the HandlePool of the object's table bumps the generation, so a lookup with the old handle logs an error and fails (generational handles). |
| Counters | one per queue, and the uploads' | RELEASE_TIMELINES = 4: frameFence, computeFence (only with async compute), the frames' upload fence and the loads' upload fence (on the transfer queue, transfer queues). |
| Tag | at the end of the frame | tagReleases in endFrame, right after submitBatches, also when the frame was dropped. |
| Collect | at the start of a frame, by reading the counters | beginFrame tags and collects first thing, before it may skip the frame (a minimized window), and collects again after the slot's fence wait. With nothing tagged it returns at once. |
| Free | a free function per entry | A std::function per entry, in order. RenderContext::cleanup waits for the device and runs them all (releaseAll). |
| Bindless slots | wait like memory | The same. A texture holds one slot; its destroy gives it back through the queue, and updateBindlessDescriptorSet takes freed slots first. Bindless resources has the details. |
| Materials that use a destroyed texture | must stop using its slot | Renderer::destroyTexture removes the texture from every material that has it and rewrites their rows, so the slot samples nothing before it is reused. |
| Per-slot table rows | reusable at once | The rows of a GpuTable (instances, materials, lights, animated entities) have one copy per frame slot, written only in syncGpuScene after the slot's fence. |
| Range allocator | first fit, best fit or size classes | First fit over a std::map, neighbours joined. No defragmenting: a refused mesh logs every stream's use and the largest free ranges. |
| Users | leave, fall back, own or refuse | Fall back for entities, materials and textures; own for a glTF import's materials and textures; refuse for cameras and scenes a graph draws. Counted: Mesh::users and Registry::materialUsers, so the usual order (entities first) searches nothing. |
Code map
| What | Where |
|---|---|
The queue: release, tag, collect, releaseAll | src/rhi/releaseQueue.h, src/rhi/releaseQueue.cpp |
Deferred frees of textures, buffers (also the old buffer of resizeBuffer), heaps and storage slots; tagReleases, collectReleases | src/rhi/renderContext.cpp |
| Tag and collect in the frame | Renderer::endFrame, Renderer::beginFrame in src/renderer/renderer.cpp |
| Destroy calls | destroyTexture in src/assets/texture.cpp, destroyMesh in src/assets/mesh.cpp, destroyMaterial in src/assets/material.cpp, destroyEnvironment in src/assets/environment.cpp, destroyEntity in src/scene/entity.cpp, destroyLight in src/scene/light.cpp, destroyCamera in src/scene/camera.cpp, destroyScene and the remove*FromScene calls in src/scene/scene.cpp |
| Ranges | RangeAllocator in src/core/rangeAllocator.cpp; GeometryPool::allocate, write, free; releaseEntityRows in src/renderer/gpuScene.cpp; releaseEntityAnimation, releaseMeshAnimation in src/renderer/animation.cpp |
| A user: Dear ImGui's textures | releaseUiTexture in src/renderer/ui.cpp |
| Unit tests | tests/releaseQueueTests.cpp, tests/rangeAllocatorTests.cpp |
| Example: tiles streamed in and out around a moving camera | examples/17_streaming |
Never free a GPU object, a bindless slot or a shared range at the call that destroys it: give the free to the release queue. Never wait on a fence to decide what to free. A table with one copy per frame slot is written only in its slot's frame, so its rows need no queue.
Still open: graph teardown (releaseSceneView), re-placing transient render targets and growing the animation buffers still wait for the GPU (D35). No pool is defragmented.
Further reading
- Frames in flight: slots and timeline fences.
- Generational handles: why the stale handle fails safely.
- Bindless resources: slot lifetime.