Culling and the frame

Render graphs

A frame is many passes: shadows, a G-buffer, lighting, post effects, UI. Each one reads what earlier ones wrote. A render graph (or frame graph) lets every pass declare what it reads and writes, and works out the rest: the order of the passes, which passes are not needed, the barriers between them and, in bigger engines, where in memory each texture lives. This page explains how. The last part shows what RASM's graph does.

In short

  • Each pass declares the resources it reads and writes. Passes never name each other.
  • "B reads what A writes" becomes an edge A → B. The passes and edges form a directed acyclic graph (DAG).
  • A topological sort (for example Kahn's algorithm) gives an order where every writer runs before its readers. A cycle means the frame cannot be ordered.
  • Passes whose results nobody reads can be culled.
  • Knowing every use of every resource, the graph emits the barriers and layout transitions itself.
  • Knowing every resource's lifetime, it can place short-lived (transient) textures in the same memory, one after another: aliasing.

1The problem

Without a graph, a frame is a hand-written list of passes. Each pass also carries the synchronization it needs, written by hand: "wait for the shadow map to be written, then move it to a layout for sampling". This works for three passes. With twenty, it breaks in quiet ways.

A frame written by hand Shadow GBuffer Lighting Post barrier barrier barrier SSAO? A new pass: where does it go? Which barriers does it need, and which old ones are now wrong?
Every orange line is code someone wrote and must keep right. A missing one is a race the validation layers may not catch. The order, the barriers, and the memory of every texture are all global knowledge, spread over many places.

By hand, you must do four jobs, and each one fails in its own way:

1. Lighting 2. Shadow shadow map reads writes later

Order the passes

Goes wrong: a pass reads a texture before it is written: last frame's data, or garbage.

race idle

Place every barrier and layout transition

Goes wrong: too few: races and flicker; too many: the GPU sits idle.

Debug debug view: off

Decide which passes run

Goes wrong: a debug pass keeps running after its view is turned off.

the frame, left to right

Give every texture its own memory

Goes wrong: memory for textures that are only alive for part of the frame.

2The idea: declare, compile, execute

The frame graph was presented by Yuriy O'Donnell for Frostbite at GDC 2017, and most engines now have one. It splits the frame into three phases.

1. Setup Shadow shadow map Lighting shadow map Post backbuffer each pass declares: create, read, write no GPU work yet 2. Compile Shadow GBuffer Lighting Debug Post 1 2 3 4 culled edges, sort, cull, lifetimes, barriers, memory placement 3. Execute 1 2 3 4 barriers each pass in order: its barriers, then its callback records commands
A pass is two pieces of code: a setup function that declares, and an execute function (often a lambda) that records commands later.

Frostbite runs all three every frame. That is cheap: a frame has tens to hundreds of passes, not millions. Other engines compile once and only redo it when the passes change.

During setup, resources are only virtual: a handle and a description (size, format), no memory yet. There are two kinds:

this frame created by a pass beforeafter

Transient

A pass creates it. It lives only inside this frame.

this frame comes from outside the graph

Imported

A pass imports it from outside: the swapchain image, or last frame's color for temporal effects.

Only compile decides where each transient resource really lives.

3Passes and resources

Here is a small frame used in the rest of the page. An arrow into a resource is a write, an arrow out of it a read.

a pass a resource an imported resource
Shadow GBuffer Lighting Debug Post shadow map G-buffer HDR debug view backbuffer(imported) no reader
The backbuffer is imported: it comes from outside the graph and must be written, so the pass that writes it is the graph's goal.
Passes only meet through resources

Adding SSAO means one new pass that reads the G-buffer and writes an AO texture, plus one read in Lighting.

Versions: writing the same resource twice

Sometimes two passes write the same texture: transparent objects are drawn on top of the lit image. If both writes go to "HDR", the graph cannot tell whether Post wants the image before or after the transparent pass. So each write makes a new version of the resource, and a read names the version it wants.

Lighting HDR v1 Transparent HDR v2 Post
Same memory, two versions. Each version has exactly one writer, so "who wrote what I read" always has one answer. Versions turn every hazard into a plain read-after-write edge. They are only names: both versions live in the same texture.

4From declarations to edges

Two passes must be ordered when they touch the same resource and at least one of them writes it. These are the classic hazards. The orange arrow is the edge the graph adds:

shadow map Shadow Lighting writes reads edge: Shadow → Lighting

Read after write (RAW)

Lighting reads the shadow map that Shadow wrote.

HDR Post UI reads writes edge: reader → next writer

Write after read (WAR)

Post reads HDR, then a UI pass draws into HDR. If UI ran first, Post would read the image with the UI in it.

texture first second writes writes edge: first → second writer

Write after write (WAW)

Two passes write the same texture.

G-buffer Lighting Debug reads reads no edge: any order

Read after read

Lighting and Debug both read the G-buffer. They can run in any order.

With versions, all three hazards become read-after-write edges between versions. The algorithm is then short: map each resource version to the pass that writes it, and for every read, add an edge from that writer to the reader. For the frame above:

ResourceWriterReadersEdges
shadow mapShadowLightingShadow → Lighting
G-bufferGBufferLighting, DebugGBuffer → Lighting, GBuffer → Debug
HDRLightingPostLighting → Post
debug viewDebug––

5Sorting: Kahn's algorithm

A topological sort lists the nodes of a DAG so that every edge points forward. Kahn's algorithm (1962) does it by counting. A pass's in-degree is the number of edges into it: how many writers it still waits for. A pass with in-degree 0 can run now.

for each pass p:  inDegree[p] = number of edges into p
queue = every pass with inDegree 0, in the order they were added
while queue is not empty:
    p = queue.popFront()
    order.append(p)
    for each edge p → s:
        inDegree[s] -= 1
        if inDegree[s] == 0: queue.pushBack(s)
if order has fewer passes than the graph: there is a cycle

The five passes were added in the order Post, Lighting, Shadow, GBuffer, Debug (#0 to #4), on purpose: the order of adding does not matter, only the edges. Click through the sort.

waits for a writer ready: in the queue sorted

1. Count the incoming edges

Shadow added #2 in 0 GBuffer added #3 in 0 Lighting added #1 in 2 Debug added #4 in 1 Post added #0 in 1 queue Shadow GBuffer order empty

Shadow and GBuffer wait for nobody. They enter the queue in the order they were added: Shadow (#2) before GBuffer (#3).

2. Take Shadow

Shadow added #2 done GBuffer added #3 in 0 Lighting added #1 2 → 1 Debug added #4 in 1 Post added #0 in 1 queue GBuffer order 1. Shadow

Each successor of the taken pass loses one incoming edge. Lighting still waits for GBuffer.

3. Take GBuffer

Shadow added #2 done GBuffer added #3 done Lighting added #1 1 → 0 Debug added #4 1 → 0 Post added #0 in 1 queue Lighting Debug order 1. Shadow 2. GBuffer

Two passes become ready at once. Either order is correct; this one keeps the order of the edges.

4. Take Lighting

Shadow added #2 done GBuffer added #3 done Lighting added #1 done Debug added #4 in 0 Post added #0 1 → 0 queue Debug Post order 1. Shadow 2. GBuffer 3. Lighting

Post becomes ready, behind Debug in the queue.

5. Take Debug, then Post

Shadow added #2 done GBuffer added #3 done Lighting added #1 done Debug added #4 done Post added #0 done queue empty order 1. Shadow 2. GBuffer 3. Lighting 4. Debug 5. Post 5 of 5: no cycle

All 5 passes are in the order, so the graph has no cycle. The work is one visit per pass and one per edge: O(passes + edges).

6. When there is a cycle

A B B reads A's output A reads B's output in 1 in 1 queue: [] order: [] 0 of 2 sorted Each waits for the other: no valid order exists.

No pass can start. A graph should report this as an error with the pass names, because it is always a mistake in the declarations.

Which order, among the valid ones

A DAG usually has many valid orders. Here, Debug could also run right after GBuffer. Kahn's algorithm with a FIFO queue in "order added" gives a stable, predictable answer. Engines that care pick on purpose:

writer reader texture alive memory free again time →

Short lifetimes

Run a reader soon after its writer. The texture between them dies sooner, and its memory can be reused sooner (section 8).

writer other work reader barrier: the writer is done long ago time →

Fewer stalls

Put independent work between a writer and its reader, so the barrier between them waits for work that is already done.

6Culling unused passes

A pass whose outputs nobody reads does not change the image. The graph can skip it. Start from the passes that write something that leaves the graph (an imported resource such as the backbuffer), and walk the edges backwards. Every pass that is never reached is culled.

Shadow added #2 GBuffer added #3 Lighting added #1 Debug added #4 culled: nobody reads Post added #0 sink Start at Post: it writes the backbuffer, which leaves the graph. Walk the edges backwards: Lighting, then Shadow and GBuffer. Debug is never reached.
Frostbite does the same with reference counts: a resource with no readers drops its writer's count, and a pass with count 0 is culled, which may free more resources in turn.

This is what makes debug views free when they are off: the pass is still declared, but nothing reads its output. A pass with effects the graph cannot see, such as a readback to the CPU, must be marked so that it is never culled.

Try it on the frame of this page. Every read is a dot: cut one, or connect the debug view to Post, and the graph is compiled again.

a pass that runs a resource a read that a running pass needs; its dot cuts it dashed: a culled pass, a cut read
Cut the read between the shadow map and Lighting: Shadow is culled. Then connect the debug view to Post: Debug runs, and Post needs one more layout transition. The order always comes from the sort of section 5.

7Barriers and layout transitions

The GPU runs commands in parallel and keeps data in caches. A barrier makes later work wait for earlier work and makes its writes visible (see GPU synchronization). An image also has a layout: how its memory is arranged for one kind of use. The graph knows, for each pass in order, how it uses each resource, so it can work out both:

the G-buffer's state, pass by pass Shadow not used GBuffer writes: attachment Lighting reads: sampled Debug reads: sampled Post not used UNDEFINED → COLOR_ATTACHMENT old contents dropped COLOR_ATTACHMENT → SHADER_READ_ONLY waits for the color writes no barrier read after read The first use of a transient texture starts from UNDEFINED: nothing in it is worth keeping, so the GPU may skip loading it. All barriers a pass needs go into one call before the pass, so the GPU drains its work once, not once per resource.
The graph keeps one state per resource (layout, and the stages and accesses of its last use), and compares it with what the next pass needs.
Declared useVulkan layoutStage and access to wait for or block
render into (color)COLOR_ATTACHMENT_OPTIMALcolor attachment output · color attachment write
render into (depth)DEPTH_ATTACHMENT_OPTIMALearly and late fragment tests · depth write
sample in a shaderSHADER_READ_ONLY_OPTIMALthe shader stages that read · shader read
write in a compute shaderGENERAL (images) · buffers have no layoutcompute shader · shader write
presentPRESENT_SRC_KHRnothing after it: the present engine waits on a semaphore

Two refinements are common. Split barriers signal at the end of the writer and wait just before the reader, so the GPU can work in between. And a pass is either all graphics or all compute, so the graph only needs to know the stage of the pass, not of every draw inside it.

The same knowledge picks each pass's load and store ops: whether an attachment's old contents are loaded or cleared at the start, and whether its new contents are kept at the end. The graph knows who drew the target before and who reads it after. See Load and store ops.

8Transient resources and memory aliasing

After sorting, the graph knows each transient resource's lifetime: from the first pass that uses it to the last. Two resources whose lifetimes do not overlap can share the same memory. This is aliasing. Here is another small frame, a post-processing chain, with made-up but typical sizes:

Pass (sorted)0 GBuffer1 Lighting2 DoF3 MotionBlur4 Tonemap
G-buffer, 32 MiBwritereadread (depth)
HDR, 16 MiBwriteread
DoF, 16 MiBwriteread
MB, 16 MiBwriteread
No aliasing: 80 MiB 0 1 2 3 4 G-buffer 32 HDR 16 DoF 16 MB 16 0 80 Aliasing: 64 MiB 0 1 2 3 4 G-buffer 32 HDR 16 DoF 16 MB 16 0 64 x: pass index in the sorted order · y: offset in one memory heap, in MiB MB lives in passes 3 and 4. The G-buffer is dead after pass 2, so MB reuses its memory.
The heap only needs to hold the largest set of textures alive at the same time: here pass 2, with the G-buffer, HDR and DoF, 64 MiB. Real frames with many post effects save much more.

Placing the resources is an interval packing problem. A simple greedy method works well: sort the resources by size, largest first, and put each one at the lowest offset where it overlaps no already-placed resource that is alive at the same time.

What aliasing needs

The resources come from one memory heap, with compatible memory types and alignment. Each one is created on that memory, not with its own allocation.

The catch

When a resource takes over memory, its old contents are garbage. Its first use must fully overwrite it (a clear, or a discard and a full write), and a barrier must separate the last use of the old resource from the first use of the new one. A barrier on one image covers only that image, so this one is a global memory barrier.

How the offsets are chosen, why the barrier must be global, and the variants on other APIs are in Transient memory and aliasing.

9Async compute

Many GPUs can run a compute queue next to the graphics queue. Compute work that does not depend on the graphics work in flight can fill the gaps in it. The graph knows the dependencies, so it can move a compute pass to the other queue and put a semaphore on each edge that crosses between queues.

graphics Shadow GBuffer Lighting Post compute particle simulation semaphore: Lighting waits Time goes right. The simulation is hidden behind Shadow and GBuffer instead of adding to the frame.
It only pays when the two kinds of work use different parts of the GPU. Shadow maps (raster heavy) next to a compute pass (math heavy) is the classic pair.

Queues, semaphores between them and resource sharing have their own page: Async compute and multiple queues.

10Variants and pitfalls

Undeclared use is invisible

A pass that reads a texture without declaring it gets no edge and no barrier. Most graph bugs are missing declarations.

frame Nframe N+1frame N+2 copy A: write copy B: write copy A: write

Persistent resources

Textures that live across frames (last frame's color for TAA, an exposure value) are imported, not transient. With frames in flight, they often need one copy per frame; see History buffers.

rebuild retain declare + compile · run a frame

Rebuild or retain

Rebuilding the graph every frame makes dynamic frames easy (a pass is declared or not). Compiling once is cheaper, but every change needs a recompile.

pass 1 pass 2 memory subpass subpass the data stays on chip

Render pass merging

On tile-based mobile GPUs, passes that read the previous pass's output at the same pixel can be merged into one render pass with subpasses, keeping the data on chip.

graphics compute semaphore

One queue or many

Async compute adds cross-queue semaphores and makes resource ownership harder: a resource used on two queues needs a queue ownership transfer or concurrent sharing.

11In RASM

RASM's render graph is a small one. It sorts passes with Kahn's algorithm, records the texture transitions and buffer barriers that their declarations need, picks each pass's load ops, and places transient render targets in shared memory. It does not cull passes. A pass added with RenderGraph::addAsyncComputePass runs on a compute queue when the engine has one (across queues, below). The graph is retained: you add the passes once, and RenderGraph::execute runs them every frame. The scene is graph passes too: Renderer::addScenePasses adds them to any graph, and Renderer::render runs a graph that holds only them (ViewGraph::render).

examples/01_render_graph scene 5 passes offscreen_rt Trail trail_rt ×2 readPrevious Background composite_rt Present → swapchain same memory offscreen_rt and composite_rt are transient and never live together, so they share one heap. trail_rt has history: its own memory. examples/04_compute Animate compute pass writes Particle Positions reads Draw 3 vertices per particle swapchain COMPUTE | GRAPHICS → COMPUTE before Animate (the previous frame's passes) · COMPUTE → GRAPHICS before Draw
The two examples that build their own graph. In 01, addScenePasses adds the scene's five passes (next diagrams) into offscreen_rt. Every graphics pass declares its one target: write(rt) or writeSwapchain().
rasm::RenderGraph graph = engine.createRenderGraph();
const rasm::Format colorFormat = engine.getRenderContext().getSwapchainImageFormat();

const rasm::RenderTargetHandle rtHandle = graph.createRenderTarget({
    .name = "offscreen_rt",
    .swapchainScale = 1.0f,
    .colorFormats = {colorFormat},
    .depthFormat = rasm::Format::D32_SFLOAT,
    .clearColor = glm::vec4(0.0f), // alpha 0 marks the background
});

// The scene's culling and draw passes, into offscreen_rt. The passes below read what they drew.
if (!engine.addScenePasses(graph, scene, camera, rtHandle))
{
    return 1;
}

One frame

compile() only if not compiled beginFrame(camera) false → return, no passes for each pass in executionOrder its queue's batch, then waits and barriers graphics pass compute pass setRenderTarget(pass.outputRenderTarget) beginPass(pass.name, ops) timer, attachments, clear or load pass.execute(ctx) your draws endPass() timer, RT color → SAMPLED resetRenderTarget() beginGpuTimer(cmd, pass.name) pass.execute(ctx) your dispatches endGpuTimer(cmd, timer) No render target, no rendering scope, no clear. after the last pass no barrier: the next frame's passes wait for this one endFrame() overlay, → PRESENT_SRC, submit batches
Each pass records into the open batch of its queue (Renderer::useQueue): an async compute pass into the compute batch when there is a compute queue, every other pass into the graphics batch. Without a compute queue the frame is one command buffer (see the frame loop). Each pass gets a GPU timer named after it; compute passes in a row with one Pass::timerName share one, as the 11 passes of bloom share Bloom.

Barriers in RASM

The pass declaresRecorded before itWhen
read(texture)transitionImageLayout(texture, SAMPLED)unless it is SAMPLED already (read after read)
read(renderTarget)transitionImageLayout(color, SAMPLED) for each color: nothing after a draw, whose endPass left it SAMPLEDa barrier after a compute pass wrote a storage target
readDepth(renderTarget)transitionImageLayout(depth, SAMPLED); the last earlier pass on the target stores its depth, and the next one moves it back and loads itneeds occlusionCulling unless the target is depth-only or has a MOTION_FORMAT color; not the target the pass draws to
readPrevious(renderTarget)nothing: the frame before left that copy SAMPLED, or clearNewHistory cleared a new copy at the start of the frame–
the first pass of a transient targetaliasingBarrier: a global memory barrier, since the target's memory held another target beforeevery frame
write(renderTarget) or writeSwapchain()beginPass moves color and depth (the swapchain has only color) to attachments with discard: from UNKNOWN, contents droppedthe first pass on the target (it clears)
the same, on a target an earlier pass drewbeginPass moves them to attachments without discard, keeping the contentslater passes (they load)
write(renderTarget) of a storage target, in a compute passtransitionImageLayout(color, STORAGE) for each color: the GENERAL layout, with compute shader reads and writesevery frame; the first use of a transient one also gets the aliasingBarrier and starts from UNKNOWN, dropping the old bytes
read(buffer)one memoryBarrier: the last write's stage → this pass's stageonce per stage after each write
readPrevious(buffer)like read(buffer); the last write is the previous frame'sonce per stage after each write
write(buffer)one memoryBarrier: the last write and the reads since → this pass's stageif any pass used it before
write(texture)transitionImageLayout(texture, STORAGE) in a compute passa graphics pass's texture write only orders passes
read or write of a per-frame buffer arraylike read(buffer) or write(buffer), for the buffer of this frame's slot onlyevery slot's buffer still orders the passes
a resource the other queue usedno barrier: a semaphore wait at the start of this queue's batch (Renderer::waitForQueue)with async compute only (below)

Texture state lives in RenderContext: rhi::TextureStates remembers each texture's last usage, so transitionImageLayout takes only the new one. If recorded commands are never submitted, RenderContext::discardRecording puts the old states back; the command buffers that did go out keep theirs. Buffers are reached through device addresses, so the graph cannot see them; it trusts the declarations. For each declared buffer it keeps an Access (bufferAccess): per queue, the stage of the last write, the stages that read since, and the batch that used it last. All of a pass's buffers fold into one global memoryBarrier. This is examples/04_compute over two frames:

frame N frame N+1 Animate COMPUTE · write Draw GRAPHICS · read Animate COMPUTE · write Draw GRAPHICS · read C | G → C C → G C | G → C C → G Access after the pass (graphics queue): write C · reads none write C · reads G write C · reads none write C · reads G
C = COMPUTE, G = GRAPHICS. The state carries over to the next frame, so Animate waits for the previous frame's draw, which read the same buffer. A barrier's first scope includes earlier submissions on the same queue, so no fence is needed for that. The example has no async pass, so the compute queue's half of the state stays empty.

The scene passes: one resource, written twice

addScenePasses adds five passes that share resources: the visible-draw list is written by both culling passes, and the target's depth is drawn by both scene passes. The graph orders them by these rules, in the order the passes were added:

The passes declareOrder
two writes of one resourcein the order they were added
a read added between two writesafter the write before it, before the write after it
a read added before every writeafter the last write, unless the pass writes the resource too: then it reads what the resource held before this frame
readPrevious(buffer)no edge from this frame's writers; it runs before the first one, and its barrier still waits for last frame's write
readDepth(renderTarget)like a read of the target
Cull 1compute Scene 1graphics · clears Hi-Zcompute Cull 2compute Scene 2graphics · loads G|C → C C → G C → C, depth → SAMPLED G|C → C C → G visible draws, draw counts write read write read the target's depth draw · store readDepth load · draw Hi-Z buffer write read visibility flags readPrevious write read by the next frame's Cull 1
Each arrow is an edge of the sort. A read between two writes runs after the first and before the second, so Scene 1 draws before Cull 2 rewrites the list. Hi-Z samples the target's depth (readDepth), so the graph makes Scene 1 store it, moves it to SAMPLED, and Scene 2 loads it. C = COMPUTE, G = GRAPHICS. Without occlusion culling there are only Cull and Scene.

A scene view's buffers grow while the application runs. They grow in place (RenderContext::resizeBuffer keeps the handle), so what the passes declared stays valid. The visible draws and the Hi-Z have one buffer per frame slot, and the passes declare them with the array forms of PassBuilder::read and PassBuilder::write (FrameBuffers). A graph's declarations are fixed when the passes are added, so every slot's buffer orders the passes. But barriers and waits cover only the buffer of the slot being recorded: Cull 1 does not wait for the previous frame's draws, which use the other slot. How the passes cull is in occlusion culling.

Across queues

With EngineConfig::asyncCompute, on a GPU that has a compute queue (RenderContext::hasAsyncCompute), a pass from addAsyncComputePass records on the compute queue. Without one it is a plain compute pass. The order of the passes is the same either way; only the queue changes. The graph keeps the state of each resource per queue, and before a pass it looks at the other queue's half:

This passThe other queueThe graph
reads a bufferwrote itRenderer::waitForQueue with the value of that queue's batch
writes a bufferwrote it or read itthe same
uses a texture or a render targetused itthe same: every texture use counts as a write, since the first use on a queue is often a layout transition
is a transient target's first passused a transient target this frameRenderer::waitForQueue with the value of its last such pass (transientUses): the memory may have held what it used
uses an undeclared resource–nothing, like no barrier

A wait is a semaphore wait at the start of the waiting queue's batch, not a barrier. It blocks all commands and makes the other queue's writes visible. If the value belongs to the other queue's open batch, that batch is closed first. Every buffer and image is shared by both queues (concurrent sharing), so nothing moves ownership. Textures are tracked across queues only: on one queue, their layout transitions order them.

compute graphics Cull 1 Scene 1 Hi-Z Cull 2 Scene 2 … Tone MapTransparent, overlay present Cull 1, next frame draws depth draws Time goes right. A box is a batch: one command buffer, one submit. Hot arrows are the waits the graph adds; inside a batch, Hi-Z and Cull 2 get a plain barrier. The next frame's Cull 1 needs nothing Scene 2 uses.
The scene passes with async compute: four batches, submitted in this order at the end of the frame (the frame loop). Cull 1 of the next frame can run next to Scene 2, except where the GPU has mesh shaders: then Scene 2 writes the meshlet bits that Cull 1 reads. That is the only overlap today, so async compute costs a little more than it saves on the scene passes (P11) and is off by default. The idea in general: Async compute and multiple queues.

Render targets: transient, history, and the rest

one frame, passes in order → offscreen_rt composite_rt one heap: the same memory, one after the other

Transient: no history

Textures are created after the compile, in memory shared with the graph's other transient targets. The graph owns them.

frame Nframe N+1 copy 0: drawn copy 1: drawn read as previous

History: one set per frame slot

A pass draws this frame's copy and reads the copy the previous frame drew. Its memory is its own. So is a readable target's, which a readback copies after the frame's last pass.

A render target from PassBuilder::createRenderTarget without history and not readable is transient. Its handle exists at once; its textures are created after the compile, when the graph knows the order. RenderGraph::transientLifetimes finds the first and last position in the order of a pass that uses each one, and RenderContext::placeTransientRenderTargets asks the device for each texture's size and alignment and packs them with rhi::packAliased: biggest first, each at the lowest offset that no texture with an overlapping lifetime uses. Then it creates one heap per set of memory types and the textures inside it. In examples/01_render_graph that saves 40%: 25.3 MiB instead of 42.2 MiB at 1920 × 1080. The algorithm step by step: Transient memory and aliasing.

A transient's first use each frame is beginPass, which moves its attachments from UNKNOWN. That image barrier only orders writes to the same image, not the writes of the target that used the memory before. So RenderGraph::execute records RenderContext::aliasingBarrier, a global memory barrier, before the first pass of each transient target: the new writes wait for every attachment write and shader read before, last frame's included. And the first use must be a draw: compile fails when it is a read.

When the layout changes, fails, and ends

The layout is made again only when a compile changes the lifetimes. If a heap cannot be made, the frames draw no passes and the graph tries again each frame. The graph owns its transient targets and the history and readable targets it made: its destructor waits for the GPU and frees them with RenderContext::destroyRenderTargets.

A render target has up to MAX_COLOR_ATTACHMENTS color textures, which one pass draws together (Multiple render targets), and one depth texture. It has one set of attachments that every frame draws. That is safe with frames in flight: on one queue, frame N+1's passes run after frame N's, and the first use in frame N+1 is a barrier that waits for frame N's reads. A use on the other queue waits for frame N's use instead, since the state carries over between frames.

A target created with history = true is RASM's imported history resource: it holds one set per frame slot. A pass draws this frame's copy and reads the copy the previous frame drew with PassBuilder::readPrevious. That read adds no edge, so a pass may read the old copy of the target it draws to. RenderContext::createRenderTarget marks each new copy, and Renderer::beginFrame clears it to clearColor before any pass, so the first frame does not read garbage, in a graph or not (more in History buffers). Look the textures up in execute, every frame:

auto commandBuffer = engine.getCurrentFrameResources().commandBuffer;
auto current = engine.getBindlessTextureIndex(engine.getRenderTargetTexture(trailHandle));
auto previous = engine.getBindlessTextureIndex(engine.getPreviousRenderTargetTexture(trailHandle));

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Phasessetup, compile, execute; often every frameRetained. setup runs at once inside RenderGraph::addPass; RenderGraph::compile runs once when it succeeds (again only after a new pass), but a failed compile is tried again every frame (B28); RenderGraph::execute runs every frame.
Resourcesvirtual handles; transient or importedRender targets without history and not readable are transient, with textures created after the compile and freed with the graph. History and readable targets made by the graph are real resources, created at once in memory of their own and freed with the graph (RenderGraph::historyTargets). Textures and buffers are real resources, created at once and kept forever. Imported ones: the swapchain, color only (PassBuilder::writeSwapchain), and what the previous frame wrote (PassBuilder::readPrevious, for a history render target or a buffer).
Edgesevery hazard, with versionsNo versions; the add order stands in for them. The writers of each resource run in the order they were added, and a reader runs after the last writer added before it and before the next one. So a resource can be written twice in a frame, as the scene passes do. A reader added before every writer reads the last one.
SortKahn's algorithmKahn's algorithm with a FIFO queue that starts in the order passes were added, so independent passes keep that order. A cycle logs Frame Graph contains a cycle! and the frames draw no passes.
Inspect pass–The RASM window's Buffers section adds one compute pass for the resource it shows (RenderGraph::inspectPass); after the sort, compile moves it right after the last pass it depends on, so it copies the resource before a later pass writes it again. It is taken out again (RenderGraph::removePass) when nothing is picked. See Inspecting GPU resources.
Checks–compile also fails for a pass that reads the render target it draws to (its color or its depth), for a compute pass that declares no write (of a buffer, a storage target or a texture), for a graphics pass that draws into a storage target, and for a graphics pass that does not write exactly one render target or the swapchain. An async compute pass writes no render target.
Pass cullingwalk back from the outputsNone: every pass runs.
Texture barriersfrom each resource's stateThe same idea, with a remembered state per texture. Only reads are declared; attachments are moved by beginPass and endPass.
Buffer barriersper resourceOne global memoryBarrier per pass, from the declared buffers' last write and reads on the same queue. The state carries across frames.
Transient memory, aliasingone heap, lifetimesThe same, for render targets only, laid out again only when a compile changes the lifetimes, not every frame. A global barrier starts each target's first pass. One heap per set of memory types; greedy first fit, biggest first.
Sizeoften relative to the screenRenderTargetDesc::swapchainScale; a resize rebuilds the target, or places its group again, with the device idle.
Load and storeper passPer pass, but inferred: passes on one target run in add order, the first clears it, later ones load color and depth (unless the pass has Pass::clearsOutput, which RASM's shadow views set: shadows per view), and the one before a load or a depth read stores its depth (RenderGraph::assignAttachmentOps). There is no way to ask for a load on the first pass, or for DONT_CARE.
Async computea second queue, a semaphore on each edge between queuesOpt-in (EngineConfig::asyncCompute), and only for passes added with addAsyncComputePass. An edge between queues is a wait at the start of a batch. Resources are shared by both queues, with no ownership transfers. The loads' copies run on a third queue, outside the graph (transfer queues).
Everything in the graphthe whole frameAlmost: the scene's culling and draws are graph passes (addScenePasses), and Renderer::render runs a graph. Only endFrame records outside it: the empty Clear pass, the stats overlay and the barrier to PRESENT_SRC.

Where it lives in code

WhatWhere
Graph, pass, builder typesRenderGraph, Pass, PassBuilder in include/rasm/render/renderGraph.h
Add, sort, runRenderGraph::addPass, RenderGraph::addComputePass, RenderGraph::addAsyncComputePass, RenderGraph::compile, RenderGraph::execute in src/renderer/renderGraph.cpp
Buffer barriers, waits across queuesRenderGraph::bufferBarrier, RenderGraph::waitForOtherQueue, RenderGraph::textureWaits in src/renderer/renderGraph.cpp; Access, QueueUse in include/rasm/render/renderGraph.h
BatchesRenderer::useQueue, Renderer::waitForQueue, Renderer::closeBatch, Renderer::submitBatches in src/renderer/renderer.cpp
Texture staterhi::TextureStates in src/rhi/textureStates.cpp; RenderContext::transitionImageLayout, RenderContext::discardRecording in src/rhi/renderContext.cpp
The scene passes, and the graph of Renderer::renderRenderer::addScenePasses in src/renderer/gpuScene.cpp; ViewGraph::render in src/renderer/viewGraph.cpp, one graph for a list of views (Many views of one scene)
Pass begin and end, frame endRenderer::beginPass, Renderer::endPass, Renderer::endFrame in src/renderer/renderer.cpp
Transient layoutRenderGraph::transientLifetimes in src/renderer/renderGraph.cpp; RenderContext::placeTransientRenderTargets, RenderContext::destroyRenderTargets, RenderContext::aliasingBarrier in src/rhi/renderContext.cpp; rhi::packAliased in src/rhi/memoryAliasing.cpp; VulkanDevice::createPlacedTexture in src/rhi/vulkan/vulkanDevice.cpp
Render targets and historyRenderContext::createRenderTarget in src/rhi/renderContext.cpp; Renderer::getRenderTargetTexture, Renderer::getPreviousRenderTargetTexture, Renderer::getRenderTargetDepthTexture in src/renderer/renderer.cpp; RenderContext::clearNewHistory in src/rhi/renderContext.cpp
DebuggingRenderGraph::dump in src/renderer/renderGraph.cpp: the passes in run order and a lifetime table. F3 logs it for the graph of Renderer::render (Renderer::pollEvents sets graphDumpRequested, Renderer::render hands it to ViewGraph::render)
Teststests/renderGraphTests.cpp (sort, checks, buffer barriers, per-frame buffers, lifetimes, the dump), tests/memoryAliasingTests.cpp, tests/textureStatesTests.cpp
From Crasm_render_graph_add_pass and the rasm_cmd_ functions in src/c/cGraph.cpp: a pass's resources as a list in place of the setup lambda, and a C callback in place of the execute lambda (C API, callbacks)
Examplesexamples/01_render_graph/main.cpp, examples/04_compute/main.cpp, examples/20_views/main.cpp (the graph of a list of views), examples/33_c_render_graph/main.c (a graph built from C)
Keep these true
  • Declare every resource a pass reads or writes with PassBuilder. An undeclared use is not sorted and gets no barrier, and on the other queue no wait.
  • Get the command buffer from getCurrentFrameResources inside execute. With async compute it changes from pass to pass, as recording moves between the queues' batches.
  • Look up getRenderTargetTexture, getPreviousRenderTargetTexture and their bindless indices inside execute, every frame. For a history target they change every frame.
  • No dispatch or memoryBarrier inside a graphics pass: RenderContext refuses both. Use addComputePass.
  • Add the passes that write one resource in the order they must run: the add order is the write order.
  • A pass that samples a depth declares readDepth, and never for the target it draws to. It needs EngineConfig::occlusionCulling unless the target is depth-only or has a MOTION_FORMAT color (TAA): only then is a D32_SFLOAT depth sampleable. The swapchain has no depth.
  • Change a texture's layout only through transitionImageLayout, which keeps the remembered state right. Recorded commands that are not submitted must be followed by discardRecording, as endFrame does.
  • Sorting, the compile checks and buffer barriers run on the CPU only. Add a test in tests/renderGraphTests.cpp when you change compile or bufferBarrier.
Not done yet

Transient textures and buffers (only render targets are transient), pass culling, and ownership transfers instead of sharing every resource between the queues (P11). For writing your own passes, see the render graph API.

Further reading