API reference
Render graph and custom passes
A render graph is a list of passes. Each pass says what it reads and writes, and records its commands in a callback. The graph puts the passes in an order that respects those reads and writes, then runs them every frame between beginFrame and endFrame. Use it when one render call is not enough: offscreen targets, post effects, compute work. The scene itself is drawn by graph passes too, which addScenePasses adds.
addPass. The execute callback runs every frame, inside execute. Both are yours.In short
- Create targets and buffers in the setup callback, and declare them with
read/write. Only these declarations order the passes. - Passes that write the same resource run in the order you added them. A pass that reads it runs after the writer added before it, and before the next writer, so a resource can be written twice in a frame.
- To draw a scene, call
engine.addScenePasses(graph, scene, camera, rt). It adds the culling and draw passes, and they sort with yours. - A graphics pass draws into exactly one target: the render target it writes, or the swapchain with
writeSwapchain(). The first pass that draws a target clears it; later passes on the same target draw on top. - For last frame's image (accumulation, trails, temporal effects), create the target with
history = trueand declarereadPrevious(rt). - Any other target from
createRenderTargeton the graph or the builder is transient: targets that are never used at the same time share memory. SetswapchainScale = 1.0fto make a target follow the window size. - The graph records the barriers and layout changes from what the passes declare. Declare every buffer and texture a pass uses: an undeclared one gets no barrier.
- A compute pass runs outside any render pass, so it can
dispatch. One added withaddAsyncComputePassruns on the compute queue whenEngineConfig::asyncComputeis on; the graph adds the waits between the queues. - Inside a callback, record with the RenderContext and the command buffer being recorded:
engine.getCurrentFrameResources().commandBuffer. Fetch it inside the callback, since it changes when the pass runs on the other queue. - Pipelines for your own shaders come from
createPipelineandcreateComputePipeline, compiled from Slang source at run time.
1The graph
RenderGraph createRenderGraph();
Returns an empty graph tied to this engine. Keep it alive for as long as you call execute, and keep everything its callbacks capture by reference alive too.
class RenderGraph
{
public:
RenderGraph(Engine* owner);
void addPass(std::string name,
const std::function<void(PassBuilder&)>& setup,
std::function<void(RenderContext&)> execute);
void addComputePass(std::string name,
const std::function<void(PassBuilder&)>& setup,
std::function<void(RenderContext&)> execute);
void addAsyncComputePass(std::string name,
const std::function<void(PassBuilder&)>& setup,
std::function<void(RenderContext&)> execute);
RenderTargetHandle createRenderTarget(const RenderTargetDesc& desc);
void compile();
void execute(CameraHandle camera);
std::string dump() const;
};
The pass list and its order. Make one with createRenderGraph rather than with the constructor. Passes cannot be removed; build a new graph to change the frame.
void addPass(std::string name,
const std::function<void(PassBuilder&)>& setup,
std::function<void(RenderContext&)> execute);
Adds a graphics pass. setup is called right away, before addPass returns, so handles it creates are ready on the next line. The graph must be compiled again (execute does it if you don't).
- name
- A label. It names the pass's GPU timer in the frame stats.
- setup
- Gets a PassBuilder. Create resources and declare reads and writes here.
- execute
- Called every frame between
beginPassandendPass, so draws are allowed and dispatches and barriers are not. The viewport and scissor cover the whole target, and the cull mode isNONE.
target The target is the render target the pass writes, or the swapchain image after writeSwapchain(). A graphics pass must declare exactly one of them, or compile fails. The first pass in the frame that draws a target clears it: color to the target's clearColor (the swapchain uses a dark gray), depth to 0. A later pass on the same target keeps color and depth and draws on top (see Load and store).
void addComputePass(std::string name,
const std::function<void(PassBuilder&)>& setup,
std::function<void(RenderContext&)> execute);
Adds a compute pass. It is sorted like any other pass. execute runs outside any render pass, so dispatch and memoryBarrier are allowed and draws are not. There are no attachments and no clear. A compute pass writes buffers, storage render targets and storage textures: the graph moves each target or texture it writes to STORAGE before it, and each one a later pass reads back to SAMPLED (see Barriers).
errors A write of a target that is not storage logs Compute pass '…' can write only a storage render target (RenderTargetDesc::storage); the write is ignored. and is dropped; a swapchain write logs Compute pass '…' cannot write the swapchain; the write is ignored. A compute pass must write at least one buffer, storage target or texture: without one, compile fails with Compute pass '…' declares no write; declare every buffer, storage target and texture it uses.
The graph adds a barrier before the pass only for a buffer it declares that another pass (or the previous frame) wrote or read; see Barriers. A pass with several dependent dispatches records ctx.memoryBarrier(commandBuffer, PipelineStage::COMPUTE, PipelineStage::COMPUTE) between them itself.
void addAsyncComputePass(std::string name,
const std::function<void(PassBuilder&)>& setup,
std::function<void(RenderContext&)> execute);
Adds a compute pass that may run on the compute queue, next to the graphics work. With EngineConfig::asyncCompute and a compute queue (hasAsyncCompute), it records into the compute queue's command buffer. Without one, it is the same as addComputePass. The pass sorts the same way either way, and the rules of addComputePass apply.
- Fetch
engine.getCurrentFrameResources().commandBufferinsideexecute: during this pass it is the compute queue's command buffer. - When this pass and a pass on the graphics queue use the same declared resource, the graph makes one queue wait for the other instead of recording a barrier (see Across queues).
- The compute queue has no graphics stages: a
memoryBarrierwithGRAPHICSis fitted to it (see memoryBarrier).
An async pass writes no render target: a first write of a transient target must be on the graphics queue, where the graph orders it after the memory's other users. A target write logs Async compute pass '…' cannot write a render target; use addComputePass. The write is ignored.
The scene's culling passes and Hi-Z are added this way (addScenePasses). A pass gains from the compute queue only when graphics work that does not need it can run at the same time; each change of queue costs a little (P11). See the guide Async compute and multiple queues.
RenderTargetHandle createRenderTarget(const RenderTargetDesc& desc);
Makes a render target outside any pass, so you can have the handle before you add passes, for example to give it to addScenePasses. It works like PassBuilder::createRenderTarget: without history the target is transient and the graph owns it; with history it is made like Renderer::createRenderTarget, in memory of its own, but the graph owns it too: destroying the graph destroys it (destroyRenderTargets), so a graph built again does not keep the old one. It declares no read or write. Returns an invalid handle on failure, with an error logged.
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
});
2Declaring reads and writes
class PassBuilder
{
public:
PassBuilder(RenderGraph& g, uint32_t passIdx);
TextureHandle createTexture(const TextureDesc& desc);
BufferHandle createBuffer(const BufferDesc& desc);
RenderTargetHandle createRenderTarget(const RenderTargetDesc& desc);
void read(TextureHandle handle);
void read(BufferHandle handle);
void read(RenderTargetHandle handle);
void read(const BufferHandle (&perFrame)[MAX_FRAMES_IN_FLIGHT]);
void readPrevious(RenderTargetHandle handle);
void readPrevious(BufferHandle handle);
void readPrevious(const BufferHandle (&perFrame)[MAX_FRAMES_IN_FLIGHT]);
void readDepth(RenderTargetHandle handle);
void write(TextureHandle handle);
void write(BufferHandle handle);
void write(RenderTargetHandle rt, uint32_t face = 0);
void write(const BufferHandle (&perFrame)[MAX_FRAMES_IN_FLIGHT]);
void writeSwapchain(WindowHandle window = {});
};
Given to your setup callback. It records what one pass uses. The graph makes it; you do not construct one.
TextureHandle createTexture(const TextureDesc& desc); BufferHandle createBuffer(const BufferDesc& desc); RenderTargetHandle createRenderTarget(const RenderTargetDesc& desc);
The same as Renderer::createTexture, Renderer::createBuffer and Renderer::createRenderTarget. They do not declare a read or write: call read or write too. RenderGraph::createRenderTarget does the same outside a pass. A render target without history is transient: the graph owns its memory and shares it with other transient targets. Textures, buffers and history targets live until the engine shuts down (D4); transient targets are freed with the graph.
void read(TextureHandle handle); void read(BufferHandle handle); void read(RenderTargetHandle handle);
This pass reads the resource. It runs after the last pass added before it that writes the resource, and before the next pass added that writes it. A read added before every writer reads the last writer of the frame, unless this pass writes the resource too: then it reads what the resource held before this frame's writes. A read of something no pass writes adds no order. Declaring a read does not bind anything: the pass still finds the data itself (a bindless index, a device address). It does decide the barriers: a texture or render target read is moved to SAMPLED before the pass, and a buffer read waits for the last write (see Barriers, and Across queues for a write on the other queue).
void readPrevious(RenderTargetHandle handle);
This pass reads the color the previous frame drew into handle. Fetch it with getPreviousRenderTargetTexture. The target must be created with history = true (see History). The read adds no edge, because nothing this frame writes that copy, so a pass may read the previous copy of the target it draws to: that is how accumulation works. The copy is always ready to sample: the frame before drew it, or it is new and was cleared to clearColor at the start of the frame. A storage target's new copy is the exception: it is not cleared, so its writer starts over without it.
errors A target without history logs Pass '…' reads the previous frame of a render target created without history; the read is ignored. during addPass.
void readPrevious(BufferHandle handle);
This pass reads what the previous frame wrote into the buffer. A buffer has one copy, so the pass runs before this frame's first pass that writes it, and no edge comes from this frame's writers. The barrier still waits for the last write, which is the previous frame's. The scene passes use it for the occlusion flags: Cull 1 reads what the last frame's Cull 2 wrote.
void readPrevious(const BufferHandle (&perFrame)[MAX_FRAMES_IN_FLIGHT]);
This pass reads the copy of a per-slot buffer pair that the previous frame wrote: slot (frameCount + MAX_FRAMES_IN_FLIGHT - 1) % MAX_FRAMES_IN_FLIGHT. This frame writes only its own slot, so the read adds no edge; its barrier waits for the previous frame's write, and the next frame's write of that copy waits for this read. The Animate pass uses it for last frame's matrices (keyframe animation).
void readDepth(RenderTargetHandle handle);
This pass samples the depth of handle. The swapchain has no depth to read. Fetch the texture with getRenderTargetDepthTexture and its index with getBindlessTextureIndex. It orders like read(handle): after the last pass added before it that draws the target.
- The last pass before it that drew the target stores its depth.
- The graph moves the depth to
SAMPLEDbefore this pass. - The next pass that draws the target moves the depth back to an attachment and loads it.
The scene's Hi-Z pass uses it to build its depth pyramid between Scene 1 and Scene 2, and a shadowed scene view reads its shadow map with it (addScenePasses).
errors Only a D32_SFLOAT depth can be sampled. That of a depth-only target (no color formats), or of a target with a MOTION_FORMAT second color (TAA), can always be read. The depth of any other target needs EngineConfig::occlusionCulling: only then are those depth textures sampleable and in the bindless set. Otherwise it logs Pass '…' reads a depth texture that can't be sampled: it needs D32_SFLOAT depth, and EngineConfig::occlusionCulling unless its target is depth-only; the read is ignored. A pass that reads the depth of the target it draws to makes compile fail with Pass '…' reads the render target it draws to.
void write(TextureHandle handle); void write(BufferHandle handle);
This pass writes the resource, so passes added after it that read it run after this one. Passes that write the same resource run in the order they were added, and each reader waits for the last writer added before it. Writing a buffer makes the pass wait for every earlier use of it. A compute pass that writes a texture moves it to STORAGE first, so its shader writes it through a storage slot (updateBindlessStorageImage): the texture must be SAMPLED_STORAGE. A graphics pass's texture write only orders passes; only a render target is drawn into.
void read(const BufferHandle (&perFrame)[MAX_FRAMES_IN_FLIGHT]); void write(const BufferHandle (&perFrame)[MAX_FRAMES_IN_FLIGHT]);
This pass reads or writes a buffer that has one copy per frame slot: perFrame[i] is the copy that frames in slot i use. You create and fill the copies yourself.
- Order: every copy counts, so the pass sorts as if it read or wrote each of them.
- Barriers and waits: only the copy of the frame being recorded counts. The frame before uses the other copy, so this frame does not wait for it.
The scene passes declare their visible draws and their Hi-Z this way. So Cull 1 on the compute queue does not wait for the last frame's draws on the graphics queue, and can run next to them.
void write(RenderTargetHandle rt, uint32_t face = 0);
This graphics pass draws into rt, or this compute pass writes the colors of a storage rt. A pass has one output target: a second call replaces the first. Passes that write the same rt run in the order they were added, and a pass that reads rt runs after the last of them added before it.
face is the face of a cube target (RenderTargetDesc::cube), 0 to CUBE_FACES − 1, in Vulkan's order +X, −X, +Y, −Y, +Z, −Z. Each face's first pass clears it, and a later pass on that face loads it. Any other target has only face 0: a higher one makes compile fail. A point light's shadow draws its cube this way (Spot and point light shadows).
void writeSwapchain(WindowHandle window = {});
This graphics pass draws into this frame's swapchain image of window: the main window for an invalid handle, or one from Renderer::addWindow. Each window's swapchain is a resource of its own: passes that draw into one window run in the order they were added, the first clears it and each later one loads it. A pass whose window has no image this frame (minimized, out of date, removed) is skipped, with its barriers. A pass that declares neither write(rt) nor writeSwapchain(), or both, makes compile fail with Pass '…' must write either one render target or the swapchain.
struct Pass
{
std::string name;
std::vector<TextureHandle> inputTextures;
std::vector<BufferHandle> inputBuffers;
std::vector<BufferHandle> previousBuffers;
std::vector<RenderTargetHandle> inputRenderTargets;
std::vector<RenderTargetHandle> previousRenderTargets;
std::vector<RenderTargetHandle> depthRenderTargets;
std::vector<TextureHandle> outputTextures;
std::vector<BufferHandle> outputBuffers;
std::vector<FrameBuffers> frameInputBuffers;
std::vector<FrameBuffers> frameOutputBuffers;
RenderTargetHandle outputRenderTarget;
uint32_t outputFace = 0;
std::function<void(RenderContext&)> execute;
std::string timerName;
AttachmentOps attachmentOps;
bool compute = false;
bool async = false;
bool writesSwapchain = false;
bool encodedSwapchain = false;
uint32_t inDegree = 0;
std::vector<uint32_t> successors;
};
What the graph stores per pass. read and write fill the input and output lists (the per-frame ones fill frameInputBuffers and frameOutputBuffers), addComputePass sets compute, addAsyncComputePass sets compute and async, readPrevious fills previousRenderTargets or previousBuffers, readDepth fills depthRenderTargets, and writeSwapchain sets writesSwapchain. encodedSwapchain, set by addUiPass, draws the swapchain through its UNORM view (AttachmentOps::encodedColor). compile fills attachmentOps (see Load and store). timerName, empty for your passes, lets compute passes next to each other in the order, on one queue, share one GPU timer of that name; the bloom passes share Bloom. inDegree and successors are filled by compile: the number of passes that must run first, and the passes that wait for this one. You never build a Pass yourself.
struct ResourceMetadata
{
uint32_t producerIdx = static_cast<uint32_t>(-1);
};
Declared in rasm/render/renderGraph.h, but nothing uses it: compile keeps its producer maps locally.
struct FrameBuffers
{
BufferHandle slots[MAX_FRAMES_IN_FLIGHT];
};
One per-frame buffer declaration (read(perFrame), write(perFrame)): the copy of each frame slot. Stored in Pass::frameInputBuffers and Pass::frameOutputBuffers. You never build one yourself.
struct QueueUse
{
PipelineStage writeStages = {};
PipelineStage readStages = {};
uint64_t value = 0;
};
struct Access
{
QueueUse queues[QUEUE_COUNT];
};
Protected types inside RenderGraph: what the graph remembers about each buffer a pass declares (bufferAccess) and, with async compute, each texture (textureAccess). queues has one entry per QueueType:
- writeStages
- The stage of the last write on that queue (none before the first).
- readStages
- The stages that have read it on that queue since, behind a barrier.
- value
- The fence value of the batch that used it last on that queue. A pass on the other queue waits for it.
A write empties the other queue's entry. Textures count every use as a write. The state is kept across frames, and only execute changes it. You never build one yourself.
3Compile and execute
compile adds.void compile();
Builds the edges, then sorts the passes (Kahn's algorithm). Passes that write one resource (texture, buffer, render target or the swapchain) get an edge from each to the next one added. A pass that reads the resource gets an edge from the last writer added before it, and one to the next writer. A reader added before every writer gets an edge from the last writer, unless it writes the resource too. readPrevious(buffer) adds an edge to the buffer's first writer instead, and a depth read orders like a read of the target. Does nothing if the graph is already compiled. execute calls it when a pass was added since the last compile, so calling it yourself only moves the work (and its log line) to start-up.
errors A cycle (A reads what B writes and B reads what A writes) logs Frame Graph contains a cycle! and leaves no pass to run. The graph stays uncompiled, so each execute tries again and logs again. Frames still run and present a cleared image, so the window keeps responding.
void execute(CameraHandle camera);
Runs one whole frame: beginFrame(camera), every pass in order, endFrame. Call it once per loop instead of render. The results show on screen when the frame is presented. With async compute, each pass records into the open batch of its queue (Across queues).
- camera
- Gets this frame's mouse and keyboard input (through pollEvents), unless its controller is
NONE; an invalid handle moves no camera. It is not given to the passes:addScenePassestakes its own camera.
When beginFrame returns false (window minimized, swapchain being re-created, failed wait), no pass runs that frame. If no pass draws into the swapchain, endFrame clears it so it can be presented. If the transient targets cannot be placed (out of memory), no pass runs either, and the graph tries again the next frame.
std::string dump() const;
Returns the graph as text, for debugging. F3 (or the Dump button of the RASM window) logs the dump of the next graph that runs, Renderer::render's or one you run with execute, with spdlog::info after its frame, and the RASM window shows it. It has two parts:
- The passes, in the order they run. Each shows its queue (
async computeonly when the engine runs async compute; otherwise an async pass showscompute, as it runs on the graphics queue), what it reads and writes, its load and store ops, and the passes that wait for it (before). - The lifetimes: one row per resource, one column per pass.
Wwrite,Rread,Pread of what the frame before left,-alive between its first and last use,.not used.
The scene passes of 05_city, cut short:
Render graph: 6 passes, in the order they run, async compute off
[0] Cull 1 (compute)
reads: buffer 'Visibility Buffer' (frame before)
writes: buffer 'Visible Draw Buffer' (per frame)
before: [1] Scene 1, [3] Cull 2
[1] Scene 1 (graphics)
reads: buffer 'Visible Draw Buffer' (per frame)
writes: target 'scene_hdr'
attachments: clear color, clear depth, store depth
before: [2] Hi-Z, [3] Cull 2, [4] Scene 2
...
[5] Tone Map (graphics)
reads: target 'scene_hdr'
writes: swapchain
attachments: clear color, no depth
Lifetimes (W write, R read, P read of the frame before, - alive between uses, . not used):
012345
P--W.. buffer 'Visibility Buffer'
WR-WR. buffer 'Visible Draw Buffer'
.WR-WR target 'scene_hdr' (transient)
..WR.. buffer 'Hi-Z Buffer'
.....W swapchain
Names come from the descs (BufferDesc::name, TextureDesc::name, RenderTargetDesc::name); an unnamed resource shows its handle as #index:generation. A per-frame buffer is one row, named after its first slot. The swapchain has a row and no depth: its passes show no depth. A transient target is marked (transient); targets in columns that do not overlap can share memory. A graph that did not compile lists its passes in the order they were added, with no before lines. To see each pass's GPU time, use the frame stats.
Barriers
Before each pass begins, execute records what its reads and writes need. A pass is COMPUTE or GRAPHICS as a whole. These barriers cover uses on the same queue; a use on the other queue gets a wait instead (Across queues).
| The pass declares | Recorded before it | When |
|---|---|---|
read(texture) | transitionImageLayout(texture, SAMPLED) | unless it is SAMPLED already |
read(renderTarget) | transitionImageLayout(color, SAMPLED) for each color of this slot | after a compute write; after a draw endPass left it sampled, and it records nothing |
readPrevious(renderTarget) | transitionImageLayout(previous copy, SAMPLED) for each color, after a clear if no frame drew it yet | the clear only once per copy, and never for a storage target (its writer starts over, as TAA does) |
readDepth(renderTarget) | transitionImageLayout(depth, SAMPLED) | the pass before that drew the target stores its depth |
write(renderTarget) or writeSwapchain() | beginPass moves color and depth (the swapchain has only color) to attachments, dropping their contents | the first pass on the target, which clears it |
| the same, after an earlier pass on the target | beginPass moves them to attachments and keeps the contents | later passes, which load, also after a depth read |
read(buffer) | memoryBarrier: last write's stage → this pass's stage | once per stage after each write |
readPrevious(buffer) | memoryBarrier: last write's stage → this pass's stage | the last write is the previous frame's |
write(buffer) | memoryBarrier: last write and the reads since → this pass's stage | if any pass used the buffer before, also in the previous frame |
write(storage target), compute | transitionImageLayout(color, STORAGE) for each color of this slot | every frame, keeping the contents (from STORAGE it is a write-after-write barrier), except in a transient target's first pass, which drops them |
write(texture), compute | transitionImageLayout(texture, STORAGE) | the texture is SAMPLED_STORAGE |
write(texture), graphics | nothing | it only orders passes |
All of a pass's buffers share one global barrier. A buffer or texture the pass uses without declaring it gets nothing, so declare everything it touches. The graph knows only its own passes: a buffer shared with another graph, or with work outside the graph, is not ordered.
errors compile fails, like on a cycle, for declarations that cannot be right: a pass that reads the render target it draws to, its color or its depth (Pass '…' reads the render target it draws to.), a compute pass with no write, a graphics pass that does not write exactly one render target or the swapchain, a graphics pass that draws into a storage target (Pass '…' draws into a storage render target; only compute passes write one.), and a read of a transient target that no earlier pass draws. The frames then draw no passes until the graph changes.
Across queues
With EngineConfig::asyncCompute, a pass from addAsyncComputePass records into the compute queue, every other pass into the graphics queue. The graph keeps, per resource and per queue, which stages used it and the value of the batch that used it last (Access). A batch is one command buffer and one submit on one queue.
| Before a pass, for each declared resource | The graph |
|---|---|
| A buffer it reads, which the other queue wrote | waits for the other queue's batch that wrote it |
| A buffer it writes, which the other queue wrote or read | waits for the other queue's batch that used it last |
| A texture, render target or swapchain image the other queue used | waits as for a buffer write: every texture use counts as a write, since the first use on a queue is often a layout transition. On the same queue, the layout transitions order textures. |
| The first pass of a transient target | waits for the other queue's last pass this frame that used a transient target, which may have used the memory |
| A resource it does not declare | no wait, like no barrier |
A wait closes the other queue's open batch when it needs that batch's work. The waiting queue's open batch then starts only once the other queue's fence reaches the value. endFrame submits all batches, in the order they were closed. Without a compute queue every pass records into the graphics batch and the graph adds no wait. The scene passes and their four batches: addScenePasses.
Load and store
compile: the first pass on a target clears it, each later one loads color and depth (only color on the swapchain, which has no depth), and the pass before a loading one, or before a depth read, stores its depth. Color is always stored. Read the result in Pass::attachmentOps.What one frame records: examples/04_compute
Access). The first: the previous frame's Animate wrote the buffer and its Draw read it (both frame slots share it), so this write waits for both. The second makes the new positions visible to this frame's draw. The example records no barrier itself.4Render targets
What createRenderTarget makes | How many | Notes |
|---|---|---|
| Color textures | 1 per color format, or that many per frame slot (2) with history; usage SAMPLED_COLOR_ATTACHMENT | Added to the bindless set with LINEAR_CLAMP. endPass leaves it in the sampled layout, so later passes can read it. |
| Depth texture | One per color set; usage SAMPLED_DEPTH_ATTACHMENT for D32_SFLOAT with EngineConfig::occlusionCulling, on a depth-only target or a target with a MOTION_FORMAT color, else DEPTH_STENCIL_ATTACHMENT | Cleared to 0 by the first pass that draws the target, and stored only when a later pass loads it or reads it. A sampleable one is added to the bindless set (NEAREST_CLAMP) when it is created; a pass reads it with readDepth, as the scene's Hi-Z pass and a shadowed scene view do. |
| Bindless slots used | 1 per color texture of MAX_BINDLESS_TEXTURES (1024), and 1 per sampleable depth texture. A resize keeps the slots and the texture handles (resizeRenderTarget, a window resize), not the contents. | |
| First contents | A target that is not transient starts with its colors cleared to clearColor and SAMPLED (except a storage target), so a pass may sample it before any pass draws it: a view texture, a history copy. | |
| Memory | Its own allocation, or, for a transient target, a place in a heap that other transient targets share | |
RenderTargetHandle createRenderTarget(const RenderTargetDesc& desc);
Creates an offscreen color + depth target, a color target without depth (a view texture for ViewOutput), a depth-only target, or a storage target of colors only, and makes its color bindless: one pair that every frame draws, or one pair per frame slot when desc.history is set. A storage target's colors also get a storage slot each. Ready at once. With swapchainScale it is rebuilt at the new size when the window resizes; without it resizeRenderTarget gives it a new size. The handle and its texture handles stay the same. A pass draws into it after builder.write(rt), or after setRenderTarget(rt) in a hand-written frame. For a target that only one graph uses, prefer RenderGraph::createRenderTarget, which can share memory.
errors If a texture cannot be created, the bindless set is full, or a storage target finds no free storage slot (MAX_BINDLESS_STORAGE_IMAGES, which the error names), it logs an error, destroys what it created, and returns an invalid handle.
struct RenderTargetDesc
{
std::string name;
uint32_t width = 0;
uint32_t height = 0;
float swapchainScale = 0.0f;
Format colorFormats[MAX_COLOR_ATTACHMENTS] = {};
Format depthFormat = Format::UNKNOWN;
glm::vec4 clearColor = glm::vec4(0.0f);
bool history = false;
bool cube = false;
bool storage = false;
uint32_t samples = 1;
bool readable = false;
bool operator==(const RenderTargetDesc&) const = default;
};
- name
- A label. The textures are named
"<name> Color Texture"(then"<name> Color Texture 1", …) and"<name> Depth Texture"in debug tools. - width, height
- Pixels. Used when
swapchainScaleis 0. - swapchainScale
- Above 0: the size is the window's (the swapchain's, in pixels) times this, at least 1 × 1, and follows each resize.
1.0ffor full size,0.5ffor half. A rebuilt history target loses last frame's image, and its first read after the resize seesclearColor. - colorFormats
- One format per color attachment, up to MAX_COLOR_ATTACHMENTS (4); the list ends at the first
UNKNOWN, so.colorFormats = {format}makes one. A scene target for TAA has two:{SCENE_COLOR_FORMAT, MOTION_FORMAT}. None makes a depth-only target, such as a shadow map: its passes draw only depth. ForaddScenePasses, use one attachment inSCENE_COLOR_FORMAT. A pipeline that draws into a target comes from createPipeline(name, source, renderTarget), which takes its formats. - depthFormat
- Needed for a target without colors, and for the scene passes.
UNKNOWNwith colors makes a color-only target: its passes draw with no depth attachment, as the tone map into a view texture does. UseFormat::D32_SFLOATwhere there is a depth. Only aD32_SFLOATdepth can be sampled (readDepth, withEngineConfig::occlusionCulling, on a depth-only target or a target with aMOTION_FORMATcolor), and occlusion culling and TAA need that. - clearColor
- Linear color, the same for every color attachment. The first pass that writes the target clears to it, and a new target that is not transient (each history copy too) is cleared to it before the next frame's passes.
- history
truekeeps one copy per frame slot, so a pass can read last frame's color withreadPrevious. It costs twice the memory. Leave itfalsefor a target that is drawn and read in the same frame. A depth-only target can't have it: history keeps only colors.- cube
true: the depth is a cube texture ofCUBE_FACES(6) square faces, sampled in a shader as a SamplerCube. Only for a depth-only target with a fixed square size (no colors,swapchainScale0,width=height); anything else is rejected. Each pass draws one face, named withwrite(rt, face). A point light's shadow is one (Spot and point light shadows).- storage
true: a target that compute passes write instead of drawing. Its colors areSAMPLED_STORAGEtextures, each in a storage slot (getRenderTargetStorageIndex) and in the bindless set, so a later pass samples it like any target. It needs at least one color, every colorR16G16B16A16_SFLOAT(SCENE_COLOR_FORMAT, the format shaders declare binding 1 with), and no depth, and can't be a cube; anything else is rejected. Withhistoryeach copy has its own slots, and a new copy is not cleared: it holds nothing defined until its writer writes it, so the writer must not read the history in its first frame or after the target is rebuilt (a resize, a new swapchain: its textures change), asTAAdoes. Only a compute pass writes it (write(rt)inaddComputePass), each frame fromSTORAGE. The bloom passes use 11 of them. A shader writes it through binding 1, declared with its format:[format("rgba16f")] RWTexture2DArray<float4>forSCENE_COLOR_FORMAT(layer 0).- samples
- Samples per pixel of its color and depth: 1, or 2, 4 or 8 when the device has them (
RenderContext::supportsSampleCount), for MSAA. A multisampled target needs a color, and can't have history, be storage or be a cube; anything else is rejected. Pipelines that draw into it need the same count, whichcreatePipeline(name, source, renderTarget)takes from it. A shader reads its color and depth sample by sample (Sampler2DMS); the bloom and tone-map passes read the single-sample target thatRenderer::addMsaaResolvePassmakes from it. Memory grows with the count: at 1920 × 1080, RGBA16F color and D32 depth take 94.9 MiB at 4 and 189.8 MiB at 8. See MSAA and alpha-to-coverage. - readable
true: its colors and depth can be copied to the CPU withRenderer::readTexture(their textures getTextureDesc::readable). A graph makes a readable target in memory of its own, as it does a history target, because the copy runs at the end of the frame, after later passes could have reused shared memory;RenderContext::createTransientRenderTargetrefuses one. Off by default: the copy usage can cost some GPUs their compression of the image. See Headless rendering and readback.
The full target, with its per-slot textures, is the RenderTarget that RenderContext::getRenderTarget returns.
TextureHandle getRenderTargetTexture(const RenderTargetHandle& renderTarget, uint32_t attachment = 0);
The color texture this frame draws, of color attachment attachment (invalid past the target's last one). For a history target it changes every frame, so fetch it every frame, inside the pass that reads it. Pass it to getBindlessTextureIndex to get the index a shader samples with. endPass leaves it in the sampled layout. In a graph, declare read(rt) so the pass sorts after the one that draws it. An unknown handle logs Render target handle not found. and returns an invalid handle.
TextureHandle getPreviousRenderTargetTexture(const RenderTargetHandle& renderTarget, uint32_t attachment = 0);
The color texture of attachment attachment that the previous frame drew, for a pass that declared readPrevious(renderTarget). Fetch it every frame and pass it to getBindlessTextureIndex. Returns an invalid handle for a target created without history. A copy that no frame drew yet holds clearColor, also outside a graph.
TextureHandle getRenderTargetDepthTexture(const RenderTargetHandle& renderTarget);
The depth texture this frame draws. For a history target it changes every frame, so fetch it every frame, inside the pass that reads it. Sample it only in a pass that declared readDepth(renderTarget), which moves it to the sampled layout; pass it to getBindlessTextureIndex for its index. It is in the bindless set only with D32_SFLOAT depth and EngineConfig::occlusionCulling, a depth-only target or a MOTION_FORMAT color. An unknown handle logs Render target handle not found. and returns an invalid handle.
uint32_t getRenderTargetStorageIndex(const RenderTargetHandle& renderTarget, uint32_t attachment = 0);
The storage slot (binding 1 of the bindless set) of a storage target's color attachment: the index a compute shader writes it with. The slot stays the same for the target's life, across resizes and new placements, and serves both frame slots, since a storage target has one copy. Returns UINT32_MAX for a target that is not storage or an attachment past its last color.
// From src/renderer/bloom.cpp: a compute pass writes one storage target and reads another
const gfx::BloomPushConstants pushConstants{.source = getBindlessTextureIndex(getRenderTargetTexture(input)),
.target = getRenderTargetStorageIndex(output),
.base = INVALID_TEXTURE_INDEX};
History
getRenderTargetTexture gives the copy this frame draws, getPreviousRenderTargetTexture the copy the frame before drew. A new copy is cleared to clearColor at the start of the next frame, so the first read sees no garbage.Transient render targets
A render target made with createRenderTarget on the graph or the builder, with no history, is transient. It belongs to the graph and lives only from the first pass that uses it to the last. After each compile, the graph places all transient targets in shared heaps: two targets whose lifetimes do not overlap get the same memory.
- The handle is ready at once, but the textures exist only from the first
executeafter a compile. Fetch them inside a pass that declares the target. - A transient target's contents are gone after its last pass. Read it in a later frame, or before a pass draws it, and you read another target's data.
compilefails when the first pass that uses one reads it:Pass '…' reads a transient render target that no pass before it draws. - For a target that must keep its contents between frames, use
history = true, orRenderer::createRenderTarget. - Before the first pass of each transient target, the graph records an aliasingBarrier, so its writes wait for the target that used the memory before, last frame's included.
- A compile that changes when the targets are used lays the memory out again: it waits for the GPU to be idle first, so add passes before the loop.
- The transient targets and their memory are freed when the graph is destroyed, after the GPU is idle. A
RenderGraphcan be moved, not copied.
void setRenderTarget(const RenderTargetHandle& renderTarget, uint32_t face = 0);
The next beginPass draws into this target instead of the swapchain; into face face of a cube target. For frames you write by hand with beginFrame / beginPass; RenderGraph::execute calls it for each pass from the pass's write.
void resetRenderTarget();
The next beginPass draws into the swapchain again.
A hand-written frame records its own draws only. The scene is drawn by graph passes (addScenePasses).
// A hand-written frame with an offscreen pass (what the graph does for you)
if (engine.beginFrame(camera))
{
engine.setRenderTarget(rt);
engine.beginPass("Offscreen");
// ... bind a pipeline and draw
engine.endPass();
engine.resetRenderTarget(); // endPass left rt's color ready to sample
engine.beginPass("Present"); // swapchain; sample rt here
// ... bind a pipeline and draw
engine.endPass();
engine.endFrame();
}
5Pipelines for your own shaders
createPipeline | createComputePipeline | |
|---|---|---|
| Entry points in the source | vertMain and fragMain | compMain, or the name you pass |
| Inputs | No vertex buffers: use SV_VertexID and read data through pointers | SV_DispatchThreadID; data through pointers |
| Push constants | PUSH_CONSTANTS_SIZE = 16 bytes, [[vk::push_constant]], e.g. one 8-byte buffer address + two 4-byte values | |
| Textures | Bindless array at [[vk::binding(0, 0)]] | The same bindless array: bind it with bindDescriptorSet. Storage images are binding 1: a storage target's slot from getRenderTargetStorageIndex, or your own texture's from updateBindlessStorageImage. |
| Fixed state | Triangle list, no blending, depth test and write on (GREATER_OR_EQUAL) when the pipeline has a depth, front face counter-clockwise, cull mode from the pass | – |
| Attachments | Swapchain color format with no depth, or the formats of a render target you pass | – |
| Imports | The search path is <shaderDir>/lib, so import core; works. Scalar layout, column-major matrices. | |
PipelineHandle createPipeline(const std::string& name,
const std::string& shaderSource);
Compiles shaderSource (Slang) twice, for vertMain and fragMain, and makes a graphics pipeline from them, for passes that draw into the swapchain: its color format and no depth. It compiles at once, on the calling thread, which can take a moment: create pipelines before the loop, not every frame.
- name
- A label for logs and debug tools. Two pipelines may share one name.
- shaderSource
- The full Slang source, as a string (a raw string literal works well, see below). The same name and source give back the same pipeline.
errors A compile error is logged with Slang's message and the call returns an invalid handle. Binding the pipeline in a pass whose attachments have other formats logs an error and skips the pass's draws.
PipelineHandle createPipeline(const std::string& name,
const std::string& shaderSource,
const RenderTargetHandle& renderTarget);
The same, but the pipeline draws into targets with renderTarget's formats and sample count: its color formats, in order, its depth format and its samples. Use it for every pass that draws into a render target: a target always has a depth, and the two-argument overload has none. The target's textures need not exist yet: a transient target's handle is enough. In the shader, fragMain returns a struct with one output per attachment, in the target's order:
struct Targets
{
float4 color : SV_TARGET0;
float4 mask : SV_TARGET1;
};
A depth-only target (no color formats) gives a pipeline without colors: its fragment shader writes no color.
errors An invalid or destroyed renderTarget logs Pipeline '…' needs a valid render target. and returns an invalid handle.
PipelineHandle createComputePipeline(
const std::string& name,
const std::string& shaderSource,
const std::string& entryPoint = "compMain");
Compiles one compute entry point of shaderSource and makes a compute pipeline. Bind it in a compute pass, push its constants, then dispatch.
- entryPoint
- The
[shader("compute")]function to use. One source can hold several, asshaders/passes/cull.slangdoes.
errors A compile error, or a missing entry point, logs an error and returns an invalid handle.
ShaderHandle createShader(
const std::string& name,
const std::string& shaderSource,
ShaderType type,
const std::string& entryPoint);
Compiles one entry point of Slang shaderSource into a shader of one stage (VERTEX, FRAGMENT, COMPUTE, TASK or MESH), for a PipelineDesc of your own: give its descriptorSetLayout getRenderContext().getBindlessDescriptorSetLayout() and make it with RenderContext::createPipeline. Unlike createPipeline, the pipeline then sets its own blend mode, depth test and write, and topology. The C API's rasm_create_pipeline works this way.
auto &ctx = engine.getRenderContext();
rasm::PipelineDesc desc = {.name = "overlay",
.vertexShader = engine.createShader("overlay", source, rasm::ShaderType::VERTEX, "vertMain"),
.fragmentShader = engine.createShader("overlay", source, rasm::ShaderType::FRAGMENT, "fragMain"),
.descriptorSetLayout = ctx.getBindlessDescriptorSetLayout(),
.colorAttachmentFormats = {ctx.getSwapchainImageFormat()},
.blendMode = rasm::BlendMode::PREMULTIPLIED_ALPHA,
.depthTest = false};
rasm::PipelineHandle overlay = ctx.createPipeline(desc);
errors A compile error, a missing entry point or a type of more than one stage logs an error and returns an invalid handle.
6Timing your own GPU work
uint32_t beginGpuTimer(const CommandBufferHandle& commandBuffer,
const std::string& name);
Writes a start timestamp into the frame's command buffer and returns a timer id. Call it between beginFrame and endFrame, with getCurrentFrameResources().commandBuffer. The graph already times every pass by its name, so use this for a part of a pass.
Returns UINT32_MAX (which endGpuTimer ignores) when nothing is measured: the stats overlay is off and getFrameStats was never called, the GPU has no timestamps, or the frame already used all timers. A frame has MAX_GPU_TIMERS (256) timers: one for the whole frame, and 255 for the passes and your timers together. The first time they run out, a warning is logged.
void endGpuTimer(const CommandBufferHandle& commandBuffer, uint32_t timer);
Writes the end timestamp of timer. The time appears in FrameStats::gpuTimers under the timer's name MAX_FRAMES_IN_FLIGHT frames later, when that frame slot is reused. See getFrameStats.
7Complete examples
Offscreen scene, trail and full-screen passes (examples/01_render_graph)
// Shortened from examples/01_render_graph/main.cpp
rasm::RenderGraph graph = engine.createRenderGraph();
const rasm::Format colorFormat = engine.getRenderContext().getSwapchainImageFormat();
// No history: transient. It lives from "Scene 1" to "Trail".
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;
}
// fullScreenTriangle is Slang source: a vertMain that covers the screen, the bindless
// array, and push constants with two texture indices. Each pipeline adds its fragMain.
auto presentPipeline = engine.createPipeline("present", fullScreenTriangle + presentFragment);
auto drawFullScreen = [&engine](rasm::RenderContext &ctx, rasm::PipelineHandle pipeline, uint32_t first, uint32_t second)
{
auto commandBuffer = engine.getCurrentFrameResources().commandBuffer;
const uint32_t indices[2] = {first, second};
ctx.bindPipeline(commandBuffer, pipeline);
ctx.bindDescriptorSet(commandBuffer, pipeline, engine.getBindlessDescriptorSet(), 0);
ctx.pushConstants(commandBuffer, pipeline, indices, sizeof(indices), 0);
ctx.draw(commandBuffer, 3);
};
// History: one copy per frame slot, so the pass reads last frame's trail.
rasm::RenderTargetHandle trailHandle{};
rasm::PipelineHandle trailPipeline{};
graph.addPass(
"Trail",
[&](rasm::PassBuilder &builder)
{
trailHandle = builder.createRenderTarget({
.name = "trail_rt",
.swapchainScale = 1.0f,
.colorFormats = {colorFormat},
.depthFormat = rasm::Format::D32_SFLOAT,
.clearColor = glm::vec4(0.0f),
.history = true,
});
builder.read(rtHandle); // runs after "Scene 2"
builder.readPrevious(trailHandle); // last frame's trail
builder.write(trailHandle); // this frame's trail
},
[&](rasm::RenderContext &ctx)
{
drawFullScreen(ctx, trailPipeline, engine.getBindlessTextureIndex(engine.getRenderTargetTexture(rtHandle)),
engine.getBindlessTextureIndex(engine.getPreviousRenderTargetTexture(trailHandle)));
});
// The pipeline takes its formats, depth included, from the target it draws into.
trailPipeline = engine.createPipeline("trail", fullScreenTriangle + trailFragment, trailHandle);
// Transient. It starts after offscreen_rt's last pass, so the two share memory.
// Two color attachments: the trail's color, and a mask of where the bunny is.
rasm::RenderTargetHandle compositeHandle{};
rasm::PipelineHandle backgroundPipeline{};
graph.addPass(
"Background",
[&](rasm::PassBuilder &builder)
{
compositeHandle = builder.createRenderTarget({
.name = "composite_rt",
.swapchainScale = 1.0f,
.colorFormats = {colorFormat, rasm::Format::R8G8B8A8_UNORM},
.depthFormat = rasm::Format::D32_SFLOAT,
});
builder.read(trailHandle);
builder.write(compositeHandle);
},
[&](rasm::RenderContext &ctx)
{
drawFullScreen(ctx, backgroundPipeline, engine.getBindlessTextureIndex(engine.getRenderTargetTexture(trailHandle)), 0);
});
// The pipeline takes both formats from the target. Its fragMain writes SV_TARGET0 and SV_TARGET1.
backgroundPipeline = engine.createPipeline("background", fullScreenTriangle + backgroundFragment, compositeHandle);
graph.addPass(
"Present",
[&](rasm::PassBuilder &builder)
{
builder.read(compositeHandle);
builder.writeSwapchain();
},
[&](rasm::RenderContext &ctx)
{
// Green where the mask is 0
drawFullScreen(ctx, presentPipeline, engine.getBindlessTextureIndex(engine.getRenderTargetTexture(compositeHandle, 0)),
engine.getBindlessTextureIndex(engine.getRenderTargetTexture(compositeHandle, 1)));
});
graph.compile();
while (engine.running())
graph.execute(camera);
Compute then draw (examples/04_compute)
// Shortened from examples/04_compute/main.cpp
rasm::BufferHandle particles = engine.createBuffer({.name = "Particle Positions",
.usage = rasm::BufferUsage::STORAGE,
.size = PARTICLE_COUNT * 2 * sizeof(float)});
const uint64_t particlesAddress = engine.getRenderContext().getBufferDeviceAddress(particles);
graph.addComputePass(
"Animate",
[&](rasm::PassBuilder &builder)
{
builder.write(particles);
},
[&](rasm::RenderContext &ctx)
{
auto commandBuffer = engine.getCurrentFrameResources().commandBuffer;
const AnimatePushConstants pushConstants = {
.positions = particlesAddress, // 8 bytes
.count = PARTICLE_COUNT, // 4 bytes
.time = frame * FRAME_TIME}; // 4 bytes: 16 in all
ctx.bindPipeline(commandBuffer, animatePipeline);
ctx.pushConstants(commandBuffer, animatePipeline, &pushConstants, sizeof(pushConstants));
const uint32_t groups = (PARTICLE_COUNT + GROUP_SIZE - 1) / GROUP_SIZE;
ctx.dispatch(commandBuffer, groups);
});
graph.addPass(
"Draw",
[&](rasm::PassBuilder &builder)
{
builder.read(particles); // this pass runs after "Animate"
builder.writeSwapchain();
},
[&](rasm::RenderContext &ctx)
{
auto commandBuffer = engine.getCurrentFrameResources().commandBuffer;
// ... push the address, then three vertices per particle
ctx.bindPipeline(commandBuffer, drawPipeline);
ctx.pushConstants(commandBuffer, drawPipeline, &pushConstants, sizeof(pushConstants));
ctx.draw(commandBuffer, PARTICLE_COUNT * 3);
});
In the shader the address arrives as a pointer: float2* positions; in the push constant struct. See getBufferDeviceAddress.
8What the graph does not do
- Only render targets are transient. Textures and buffers from the builder, and history targets, live until you destroy them; a graph destroys the targets it made.
- The graph orders only its own passes. A buffer that two graphs share is not ordered between them, and two graphs that draw the same scene view (scene, camera, target) share its buffers. A graph holds the scene views it added until it is destroyed or replaced.
- Pipelines live until shutdown: they are shared through the dedup cache. Render targets, buffers and textures can be destroyed.
- Async compute passes overlap little with the scene passes today: each change of queue costs a little, and a frame with uploads overlaps less (
P11).
How the graph works inside, with the barriers and layouts step by step: the guide Render graphs. How the two queues share a frame: Async compute and multiple queues. To add a pass to the engine itself, see the new-pass skill in .claude/skills/.