TExcelTAD

Render Graphs

A modern frame is not one pass. A typical deferred renderer runs a depth pre-pass, a G-buffer pass, shadow maps, SSAO, lighting, transparent objects, bloom, tone mapping and UI, and many of these feed each other through textures. Hand-ordering such a frame works until someone adds a pass, disables one in the settings menu, or forgets a barrier. Then the bugs are a black screen on one GPU vendor, or a texture read while it is still being written.

A render graph (also called a frame graph, after the 2017 Frostbite talk that popularised it) makes those dependencies explicit. Each pass declares which resources it reads and writes. The graph then works out the rest:

The graph computes From
a valid execution order write → read dependencies (a topological sort)
which passes to skip passes whose outputs nobody reads are culled
when each transient texture is alive its first and last use, so memory can be aliased
where barriers / layout transitions go each resource's previous and next access

The engine builds the graph from scratch every frame (it is cheap: a few dozen passes), compiles it, and executes it.

A pass-ordering model

The program below declares passes with their reads and writes, then does what a render-graph compiler does:

  1. Find the producer of every resource.
  2. Walk backwards from the outputs that must exist (the backbuffer) and mark passes as used. Unmarked passes are culled.
  3. Topologically sort the used passes (Kahn's algorithm, ties broken by declaration order so the result is deterministic).
  4. Record each transient resource's first and last pass, and greedily give non-overlapping lifetimes the same memory slot.
cpp · try it yourself
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>

struct Pass {
    std::string name;
    std::vector<std::string> reads, writes;
};

int main() {
    std::vector<Pass> passes = {
        {"Shadows",   {},                                 {"shadowMap"}},
        {"GBuffer",   {},                                 {"albedo", "normals", "depth"}},
        {"SSAO",      {"normals", "depth"},               {"ao"}},
        {"DebugView", {"normals"},                        {"debugTex"}},     // nobody reads debugTex
        {"Lighting",  {"albedo", "normals", "ao", "shadowMap"}, {"hdr"}},
        {"Bloom",     {"hdr"},                            {"bloom"}},
        {"Tonemap",   {"hdr", "bloom"},                   {"ldr"}},
        {"UI",        {"ldr"},                            {"backbuffer"}},
    };
    const int n = int(passes.size());

    std::map<std::string, int> producer;
    for (int i = 0; i < n; i++)
        for (auto& w : passes[i].writes) producer[w] = i;

    // 1) cull: walk back from the required output
    std::vector<bool> used(n, false);
    std::vector<std::string> stack = {"backbuffer"};
    while (!stack.empty()) {
        std::string r = stack.back(); stack.pop_back();
        int p = producer.at(r);
        if (used[p]) continue;
        used[p] = true;
        for (auto& in : passes[p].reads) stack.push_back(in);
    }
    for (int i = 0; i < n; i++) if (!used[i]) std::cout << "culled: " << passes[i].name << "\n";

    // 2) topological sort (Kahn), lowest declaration index first
    std::vector<std::set<int>> next(n);
    std::vector<int> indeg(n, 0);
    for (int i = 0; i < n; i++) if (used[i])
        for (auto& in : passes[i].reads) {
            int p = producer.at(in);
            if (next[p].insert(i).second) indeg[i]++;
        }
    std::set<int> ready;
    for (int i = 0; i < n; i++) if (used[i] && indeg[i] == 0) ready.insert(i);
    std::vector<int> order;
    while (!ready.empty()) {
        int p = *ready.begin(); ready.erase(ready.begin());
        order.push_back(p);
        for (int q : next[p]) if (--indeg[q] == 0) ready.insert(q);
    }
    std::cout << "order:";
    for (int p : order) std::cout << " " << passes[p].name;
    std::cout << "\n";

    // 3) lifetimes of transient resources (positions in the order)
    std::map<std::string, std::pair<int, int>> life;
    for (int step = 0; step < int(order.size()); step++) {
        const Pass& p = passes[order[step]];
        for (auto* list : {&p.writes, &p.reads})
            for (auto& r : *list) {
                if (r == "backbuffer") continue;
                auto it = life.find(r);
                if (it == life.end()) life[r] = {step, step};
                else it->second.second = step;
            }
    }

    // 4) alias memory: reuse a slot whose last user finished before this resource's first use
    std::vector<int> slotFreeAfter;
    std::vector<std::pair<int, std::string>> byStart;
    for (auto& [r, l] : life) byStart.push_back({l.first, r});
    std::sort(byStart.begin(), byStart.end());
    for (auto& [start, r] : byStart) {
        int slot = -1;
        for (int s = 0; s < int(slotFreeAfter.size()); s++)
            if (slotFreeAfter[s] < start) { slot = s; break; }
        if (slot < 0) { slot = int(slotFreeAfter.size()); slotFreeAfter.push_back(0); }
        slotFreeAfter[slot] = life[r].second;
        std::cout << r << ": passes " << life[r].first << ".." << life[r].second << " -> slot " << slot << "\n";
    }
    std::cout << life.size() << " transient textures in " << slotFreeAfter.size() << " memory slots\n";
}
culled: DebugView
order: Shadows GBuffer SSAO Lighting Bloom Tonemap UI
shadowMap: passes 0..3 -> slot 0
albedo: passes 1..3 -> slot 1
depth: passes 1..2 -> slot 2
normals: passes 1..3 -> slot 3
ao: passes 2..3 -> slot 4
hdr: passes 3..5 -> slot 2
bloom: passes 4..5 -> slot 0
ldr: passes 5..6 -> slot 1
8 transient textures in 5 memory slots

Eight transient textures fit in five slots: depth is dead after SSAO, so hdr reuses its memory, and bloom and ldr reuse the shadow map's and the albedo's. The DebugView pass is declared but its output is never read on the way to the backbuffer, so it costs nothing this frame. A settings toggle that adds debugTex to the UI pass's reads would bring it back without anyone touching the ordering code.

Note: Real graphs alias only resources whose size and format are compatible (or allocate from one large heap with placement), and they must insert a barrier when a slot changes owner. The greedy slot assignment above is the core idea.

What the declarations buy you

  • Barriers for free. Vulkan and Direct3D 12 need explicit image layout transitions and memory barriers. Since the graph knows "Lighting reads ao that SSAO wrote", it can emit exactly the barrier between them. This is the biggest practical reason engines adopt render graphs with explicit APIs.
  • Async compute. A pass marked as compute with no dependency on the graphics passes around it (SSAO often qualifies) can be scheduled on a compute queue to overlap with other work.
  • Debugging. Dumping the graph to Graphviz each frame shows what actually ran. RenderDoc captures then line up with named passes.

What an API looks like

Most implementations use a two-phase lambda: a setup callback declares resources, an execute callback records commands later. Here is a sketch in the style used by several open-source graphs (it is a design pattern, not a specific library's API):

cpp
struct SsaoData { TextureId normals, depth, ao; };

graph.addPass<SsaoData>("SSAO",
    [&](PassBuilder& b, SsaoData& d) {                     // setup: runs while building the graph
        d.normals = b.read(gbuffer.normals);
        d.depth   = b.read(gbuffer.depth);
        d.ao      = b.create("ao", {.width = w / 2, .height = h / 2, .format = Format::R8});
    },
    [=](const SsaoData& d, CommandList& cmd) {             // execute: runs after compile()
        cmd.bindPipeline(ssaoPipeline);
        cmd.bindTexture(0, d.normals);
        cmd.bindTexture(1, d.depth);
        cmd.dispatch((w / 2 + 7) / 8, (h / 2 + 7) / 8, 1);
    });
graph.compile();   // cull, sort, compute lifetimes and barriers
graph.execute();

Unreal Engine's renderer is built on its Render Dependency Graph (RDG) (FRDGBuilder, AddPass, pass parameter structs). In your own engine, start with a fixed list of passes and move to a graph when barrier and resource bookkeeping starts to hurt.

For the shading inside each pass, see Shaders & Graphics Programming. The draw calls inside a pass usually come from a sorted command buffer.

Test yourself

How does a render graph decide that a pass can be culled?

  1. The pass has no reads
  2. None of the pass's outputs are needed, directly or indirectly, to produce the final output
  3. The pass is a compute pass
  4. It took too long last frame

Two transient textures can share the same memory when…

  1. they have the same name
  2. their lifetimes (first use to last use in the pass order) do not overlap
  3. they are both read by the same pass
  4. one of them is the backbuffer

Why are render graphs especially useful with Vulkan or Direct3D 12?

  1. Those APIs have no draw calls
  2. The graph knows every read-after-write dependency, so it can place the explicit barriers and layout transitions those APIs require
  3. They only support one pass per frame
  4. They sort draw calls automatically