Foundations
Frames in flight
The CPU and the GPU are two processors. If each waits for the other, each sits idle half the time. With frames in flight, the CPU prepares the next frame while the GPU still draws the last one. That needs a few copies of the data that changes every frame, and a fence that says when a copy is free again. The last part shows how RASM does it.
In short
- The CPU records a frame, the GPU runs it later. They can work on different frames at the same time.
- Data the CPU writes every frame gets one copy per frame slot. Frame n uses slot n mod N.
- Before the CPU reuses a slot, it waits on a fence until the GPU has finished the last frame that used it.
- A timeline fence is one growing counter. Each submit signals the next value; each slot remembers its value.
- More slots hide more spikes, but add latency. When the GPU is the slow side, a third slot adds latency and no speed.
- Data that never changes, or that only the GPU writes and reads within a frame, needs no copies.
1Two workers, one frame at a time
The CPU builds a frame: it reads input, moves objects, and records commands. Then it submits them, and the GPU runs them. If the CPU then waits for the GPU before it starts the next frame, the two never work at the same time:
With overlap, the slower side alone sets the frame time: max(CPU, GPU) instead of CPU + GPU. The work itself does not change.
2The problem: shared data
Overlap has a price. A frame's commands do not run when they are recorded; they read their data later, while the GPU runs them. Take the camera matrix. The CPU writes it into a buffer, and the GPU reads it during the frame.
One buffer: a race
The CPU writes frame 1's camera while the GPU still draws frame 0 with it.
One buffer per slot
The CPU writes slot 1 while the GPU reads slot 0. F2 writes slot 0 again, after the GPU is done with F0.
The GPU does not notice a CPU write to mapped memory. Nothing in the API stops the race; the program has to avoid it.
There are only two ways out: wait until the GPU is done before writing (the "one slot" picture, slow), or write somewhere else. Frames in flight do the second, and wait only when the other place is still in use.
3Frame slots
Pick a number N, usually 2 or 3. Give every per-frame resource N copies, and call copy i slot i. Frame n uses slot n mod N. So with N = 2, frames 0, 2, 4 use slot 0 and frames 1, 3, 5 use slot 1.
With N slots, the CPU can be at most N − 1 frames ahead of the GPU: frame n must wait for frame n − N, which used the same slot. That wait is the only one the CPU needs.
4Fences: how the CPU knows
A fence is a sync object the GPU signals and the CPU can wait on. The submit names it; when the GPU has finished everything in that submit, it signals the fence. There are two kinds.
Binary: one per slot
Submit with the slot's fence. The GPU finishes and signals it. The CPU waits for it, then resets it before the next submit. Each fence answers one question: "is that one submit done?"
Timeline: one counter
Every submit signals the next value. Values only grow, and nothing is reset. One object answers "how far has the GPU come?" for every submit. Reading the counter never blocks.
A timeline needs one object for all slots. It also serves uploads, readbacks and deferred deletes: each just stores the value it waits for.
| API | Binary fence | Timeline (counter) |
|---|---|---|
| Vulkan | VkFence: wait, then reset | timeline semaphore (core since 1.2): signal a value, wait for a value |
| Direct3D 12 | — | ID3D12Fence is always a counter |
| Metal | a completion handler per command buffer | MTLSharedEvent, a 64-bit value |
| WebGPU | onSubmittedWorkDone, a promise | — |
Do not confuse a fence with a semaphore in the binary sense. A binary semaphore orders work between GPU submissions (for example, "draw only after the swapchain image is free"); the CPU cannot wait on it. See the swapchain and GPU synchronization.
5Worked example: the fence, frame by frame
Two slots and one timeline fence that starts at 0. Each slot starts with the value 0, so the first wait on each slot returns at once. Click through the steps (or use the arrow keys).
1. Frame 0, slot 0
The submit names the value it will signal. The slot stores it, so the next frame that uses slot 0 knows what to wait for.
2. Frame 1, slot 1
The CPU is now one frame ahead. Slot 0 is still in use by the GPU, but the CPU did not touch it.
3. Frame 2, slot 0: the CPU waits
This is the wait that keeps the race away. It sits at the start of the frame, right before the slot is touched, so the CPU did as much work as possible before it.
4. Frame 3, slot 1
With a timeline, the bookkeeping is one number per slot and one counter. Nothing is ever reset.
6What gets a copy per slot, and what does not
The rule is simple: a resource needs one copy per slot when the CPU changes it every frame (or the CPU reads it back), and the GPU may still be using the old contents.
One copy per slot
Command buffers and their memory (pools, allocators)
Re-recording resets their memory, which the GPU reads while it runs them.
Per-frame constants: camera, time, lights
The CPU rewrites them every frame.
Per-object data the CPU updates (transforms)
The same reason. A change must reach every copy, each in its own frame.
Readback buffers, timer queries
The GPU writes them, the CPU reads them after the fence. A second frame must not overwrite them first.
One copy is enough
Meshes, textures, pipelines, samplers
Written once, then only read. If they change, write new data elsewhere, or wait.
GPU-only scratch: a depth buffer, a culling list made and used in one frame
Usually one copy. The queue runs frames in order, and a barrier covers earlier submissions.
Unless frames may overlap on the GPU, or the data must survive to the next frame.
Swapchain images
The swapchain owns them. Their count is not N. See the swapchain.
Changing a resource that has one copy
It is still possible. Either write only to parts no running frame reads (a new row, a new descriptor slot), or defer the change: remember the fence value of the current frame, and apply the change once the counter has passed it. Deleting works the same way: a destroyed object is put in a queue with the current value, and really freed later.
7How many slots: throughput against latency
Latency here means the time from the start of a frame on the CPU (when input is read) to the end of its GPU work. A simple model, with fixed costs per frame, shows the trade-off. The numbers come from stepping the rule "frame n may start when the CPU is free and frame n − N is done on the GPU":
| CPU, GPU per frame | Slots N | Time per frame | Frames per second | Latency |
|---|---|---|---|---|
| 6 ms, 10 ms (GPU-bound) | 1 | 16 ms | 62.5 | 16 ms |
| 2 | 10 ms | 100 | 20 ms | |
| 3 | 10 ms | 100 | 30 ms | |
| 10 ms, 6 ms (CPU-bound) | 1 | 16 ms | 62.5 | 16 ms |
| 2 | 10 ms | 100 | 16 ms | |
| 3 | 10 ms | 100 | 16 ms |
The same rule, stepped live for any costs. The middle row shows the frames that are recorded but not yet on the GPU.
GPU-bound
The CPU runs ahead until it hits the fence. Each extra slot is one more finished frame waiting in the queue, so latency grows by one GPU frame, and speed does not change.
CPU-bound
The GPU waits for the CPU, never the other way. The queue stays empty, so more slots change nothing. They do help when costs vary: a slow CPU frame can then hide behind a fast one.
That is why 2 is the common default, and 3 is used when frame costs jump around. Games that care about input lag go further: they limit how far the CPU may run ahead, or delay the start of the CPU frame so it finishes just in time.
8Where to wait, and other pitfalls
- Waiting right after submit
- Back to "one slot": no overlap. Instead: wait at the start of the frame that reuses the slot.
- Writing the slot before the wait
- The race from section 2 comes back, but only sometimes. Instead: everything that writes a slot's resources runs after its wait.
- Remembering a value nothing signals
- A submit failed, but the slot stored its value anyway. The next wait on that slot never returns. Instead: store the value only after the submit succeeded.
- Mixing up frame number and slot
- Two frames in flight share one slot. Instead: keep both, and index per-frame resources by the slot.
- Readback "now"
- The CPU reads a result the GPU has not written yet. Instead: read a slot's results after its wait: they are N frames old, and that is fine for statistics.
- Waiting forever
- A GPU hang (device lost) freezes the program. Instead: a timeout, or at least an error on a failed wait.
- Resize or shutdown with frames in flight
- Resources are freed while the GPU still uses them. Instead: wait for the device to go idle first; it is rare, so the cost does not matter.
9In RASM
RASM uses two slots (MAX_FRAMES_IN_FLIGHT = 2) and one timeline fence per queue: Renderer::frameFence for the graphics queue, and Renderer::computeFence for the compute queue when async compute is on. A slot remembers the last value of each (FrameResources::fenceValue, FrameResources::computeFenceValue), and beginFrame waits for both. frameCount is the slot, 0 or 1, not a frame counter. Everything that writes a slot's resources runs right after the wait in beginFrame.
beginFrame still waits for both.What has one copy per slot
| Per slot | Where | Written by |
|---|---|---|
| Fence values | FrameResources in Renderer::frameResources | submitBatches; beginFrame waits for them |
| Command buffers, one per batch and queue | Renderer::batchCommandBuffers | the passes; FrameResources::commandBuffer names the one being recorded |
| GPU tables: instances, materials, lights, animated entities, morph weight overrides | GpuTable::buffers | syncGpuScene, through GpuTable::upload |
| Draw lists, one per scene | SceneDrawList::buffers | syncGpuScene, through uploadDrawList |
| Scene data, one per scene view | GpuScene::sceneData (host-visible) | prepareSceneView, at the start of the view's Cull pass |
| Culling: visible lists with their counts, Hi-Z, cull stats | cullStats in GpuScene; visibleDraws, hiz in each SceneView | the culling and Hi-Z passes; the CPU reads cullStats back |
| Light clusters of a shaded view | ViewClusters::buffers | the Light Clusters pass (clustered lighting) |
| Posed transforms, joint matrices, morph weights, skinned vertices | transforms, joints, weights, skinnedVertices in GpuAnimation | the Animate and Skin passes; motion vectors read the other slot's skinned vertices, the frame before's (skinning) |
Attachments of a render target with history | RenderTarget::attachments | passes that draw into the target; the next frame reads the copy |
| Timestamp queries | FrameStatsSlot::timestamps | the GPU timers; read in updateFrameStats |
| Stats overlay text | StatsOverlaySlot::text | updateStatsOverlay, with the UI off |
| Dear ImGui's vertices and indices | UiSlot in Ui::slots | buildUi, with EngineConfig::ui (immediate-mode UI) |
| The Inspect pass's parameters | Inspector::params | recordInspect (inspecting GPU resources) |
A changed table row is marked dirty in every slot (GpuTable::setRow). Each slot then uploads it once, in its own frame, after its own wait. That is why EngineConfig::maxInstances costs its memory twice.
What has one copy
The visibility buffer
One GPU-only buffer per scene view is shared on purpose: SceneView::visibility, what the last frame's occlusion culling saw. The next frame reads it, so it must survive the frame.
Only compute passes use it, and they run on one queue in frame order, and the Cull 1 pass declares it with readPrevious, so the graph puts a compute-to-compute barrier before it: one copy is safe (see occlusion culling).
A render target without history
It has one copy that both slots share. Each frame draws it before it reads it, and the queue runs the frames in order, so the next frame's draw waits behind the barriers of this one (see temporal history).
A use on the other queue waits for it instead (render graphs).
Geometry, textures, pipelines, the bindless set
The geometry pool, textures, pipelines and the one bindless descriptor set have a single copy. They are only added to: new ranges, new textures, new bindless slots, never a change to something a running frame reads.
The bindless set's layout uses update-after-bind, which allows writing new slots while earlier frames still run.
The visible-draw lists and the Hi-Z have one copy per slot for a second reason: with async compute, Cull 1 of the next frame then does not wait for this frame's draws, and can run next to them.
A destroyed object is freed once the frames in flight that may use it are done, through a release queue tied to these fences (deferred destruction). Resize waits for the device to go idle instead, then rebuilds the render targets sized from the window (RenderContext::resizeRenderTargets).
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Slots | N = 2 or 3 | 2, fixed at compile time (MAX_FRAMES_IN_FLIGHT in include/rasm/types.h). |
| Slot index | frame number mod N | frameCount holds only the slot; there is no frame number. It flips in endFrame. |
| Fence | binary per slot, or one timeline | One timeline per queue: frameFence, a Vulkan timeline semaphore. frameFenceValue is the last value signaled; FrameResources::fenceValue is the slot's. With async compute, computeFence, computeFenceValue and FrameResources::computeFenceValue do the same for the compute queue. A frame may signal several values of each, one per batch. |
| Where to wait | start of the frame | In beginFrame, after input, finished loads and swapchain recreation, before anything writes the slot. |
| Value only on success | store it after the submit | The same: a failed submit leaves both values, and calls discardRecording. |
| Wait timeout | a timeout | None: waitForFence waits with UINT64_MAX. A failed wait skips the frame. |
| Readback | N frames late | The cull stats and GPU timers of a slot are read after its wait, so the overlay and the RASM window show the frame from two frames ago. FrameStatsSlot::readFenceValue skips a slot whose frame was never submitted. An image copy (Renderer::readFrame, Renderer::readTexture) rides in a frame's last graphics batch and keeps that frame's fence value, so isReadbackReady turns true about two frames later, and nothing waits (readback). |
| Other users of the timeline idea | uploads, deletes | UploadManager has its own timeline, "Upload Fence" (and the loads' "Load Upload Fence" on the transfer queue), to free staging space. The release queue waits for the frame, compute and both upload fences before it frees a destroyed object (deferred destruction). |
| Swapchain images | separate from slots | Separate. The swapchain also keeps its own acquire semaphores and its own release timeline, so it does not depend on the frame fence. See the swapchain. |
Where it lives in code
| What | Where |
|---|---|
| The slot count | MAX_FRAMES_IN_FLIGHT in include/rasm/types.h |
| Slot state | FrameResources in include/rasm/types.h; frameResources, frameFence, frameFenceValue, computeFence, computeFenceValue, batchCommandBuffers in include/rasm/renderer.h |
| The wait, the submits, the flip | Renderer::beginFrame, Renderer::endFrame and Renderer::submitBatches in src/renderer/renderer.cpp |
| Per-slot tables | GpuTable in src/renderer/gpuTable.cpp |
| Timeline fence | VulkanDevice::createFence, waitForFence, getFenceValue in src/rhi/vulkan/vulkanDevice.cpp; signaled in VulkanQueue::submit |
- Per-frame mutable buffers are indexed by
frameCount, and written only afterbeginFrame's wait for that slot. - GPU scene tables are written only in
syncGpuScene. Change rows throughGpuTable::setRow, never by writing a slot's buffer. - A slot takes a fence value only after a submit that signals it succeeded.
beginFramewaits for both of the slot's fences before anything reuses its command buffers or writes its buffers.- A resource with one copy is freed or reused only through the release queue, after the frames that may use it (deferred destruction).
Further reading
- The Khronos Group, Vulkan Specification: the chapter "Synchronization and Cache Control", on fences and timeline semaphores.
- Alexander Overvoorde, Vulkan Tutorial: the chapter "Frames in flight".
- Microsoft, Direct3D 12 Programming Guide: "Multi-engine synchronization", on ID3D12Fence.
- Tomas Akenine-Möller and others, Real-Time Rendering, 4th edition: the chapter on the graphics pipeline and parallel CPU–GPU work.