Culling and the frame

History buffers: last frame's image

Some effects need to know what the screen looked like a moment ago: a fading trail, temporal anti-aliasing, a denoiser, auto exposure. They keep a history buffer, an image that survives from one frame to the next. This page explains why it takes two images, how they swap, how to blend the past with the present, and when the past must be thrown away. The last part shows how RASM does it.

In short

  • A temporal effect reads last frame's result and writes this frame's result.
  • A pass cannot sample an image while it draws into the same image. That is a feedback loop, and the result is undefined.
  • So keep two copies and swap them every frame: draw one, read the other. This is ping-pong.
  • With frames in flight, the slot index already alternates, so it can pick the copy. Barriers on the one queue keep the copies safe; the fence alone does not.
  • Blending is a running average: mix(previous, current, α), or a decaying trail: max(current, previous × k). With k = 0.85, a trail falls to 10% in about 14 frames.
  • History is invalid on the first frame, after a resize and after a camera cut. Clear it, rebuild it, or ignore it for one frame.
  • It costs a second full-screen image and one more full-screen read per frame.

1Effects that need the past

Most passes only need this frame: the scene, the lights, the camera. A temporal effect also needs its own output from the frame before. It takes that output, mixes in what is new, and writes the result. Next frame, the result is the input again. The simplest example is a trail behind a moving object:

A trail: each frame keeps 85% of the old image moves 0.52 0.61 0.72 0.85 1.0 4 frames ago 3 frames ago 2 frames ago 1 frame ago this frame
The trail is free: the pass draws only the ball. No pass draws the old positions. They are still in the image from last frame, which the pass reads and dims.

Many well-known effects work this way. They differ in what they keep and how they mix it:

old, a bit darker · new

Trails, motion trails

Keeps: last frame's trail image.

Keeps the brighter of "new" and "old, a bit darker".

one frame average of all

Accumulation (path tracing, a still camera)

Keeps: the average of all frames so far.

Adds one more noisy sample to the average.

one frame averaged

Temporal anti-aliasing (TAA)

Keeps: last frame's smooth image.

Moves the camera by less than a pixel each frame and averages the results.

time →

Temporal denoising

Keeps: last frame's filtered lighting.

Averages noisy lighting over time instead of over many rays.

moves

Motion blur (simple)

Keeps: last frame's image.

Blends it in where things move.

this frame dark bright

Auto exposure

Keeps: last frame's brightness (one pixel).

Moves slowly towards this frame's brightness, so the eye "adapts".

2One image cannot be read and drawn at once

The obvious idea is one image: read the old value at a pixel, and write the new value back to the same image. In a draw, this does not work:

This is a feedback loop, and graphics APIs call its result undefined. Validation layers report it.

One image: a feedback loop image T pass reads draws old value, new value, or half written? undefined Two images: no loop image A last frame drew it image B this frame draws it pass reads draws reads only A, draws only B next frame: A and B swap roles
The fix is to never touch one image in both ways in the same pass. The old result lives in one image, the new result goes to another.
A compute shader is a special case

If every thread reads and writes only its own pixel of a storage image, one image is enough, since no other thread touches that pixel. But as soon as a thread reads a neighbour (a blur, a reprojection, a filtered sample), it needs two images again.

3Ping-pong: two images that swap

Keep two copies of the image, A and B. Frame 0 draws A. Frame 1 reads A and draws B. Frame 2 reads B and draws A. Each frame, the copy that was "new" becomes "old". The data does not move; only the names swap. This is called ping-pong, or double buffering.

copy A copy B frame 0 frame 1 frame 2 frame 3 draws reads, but nothing drew it: cleared reads draws draws reads reads draws Grey arrow: the pass, inside one frame. Orange arrow: the same image, kept to the next frame. The result zig-zags between the two copies. Each frame reads what the frame before drew.
Frame n draws copy n mod 2 and reads copy (n + 1) mod 2. Frame 0 reads a copy that no frame drew yet; section 7 deals with that.

The code that picks the copies is two lines. The important part: both indices change every frame, so anything that refers to "the current copy" or "the previous copy" must be looked up again every frame.

// frame n draws history[n % 2] and reads history[(n + 1) % 2]
const uint32_t drawIndex = frameIndex % 2;
const uint32_t readIndex = (frameIndex + 1) % 2;

Here are two real copies. A ball moves, and each frame writes the ball over the darkened old image, so the ball leaves a trail.

Pause, then press Next frame a few times and watch which copy gets the new ball. Then turn the swap off: copy B is never drawn, so there is nothing old to read.

4Other ways to keep the past

Ping-pong is the usual choice, but not the only one:

A B the roles swap each frame

Ping-pong

Two copies, swap the roles each frame.

Good for: most temporal effects.

Cost: 2 images, no copy

pass output copy history read next frame

Copy at the end

One "history" image and one output; after the pass, copy the output into history.

Good for: when the output must stay at one fixed image (another system holds it).

Cost: 2 images, plus one full-screen copy per frame

pass output shown later pass history kept, often smaller

Output + history, kept apart

The pass writes a new output image; a later pass writes the history it wants to keep.

Good for: TAA, where the history and the shown image differ (for example, before and after sharpening).

Cost: 2 images, often a smaller history

own pixel only

In place, compute

One storage image; each thread reads and writes only its own pixel.

Good for: per-pixel accumulation with no neighbour reads.

Cost: 1 image

5History and frames in flight

With frames in flight, the CPU records frame n + 1 while the GPU still runs frame n. Each frame has a slot, and with two slots the slot index goes 0, 1, 0, 1. That is exactly the ping-pong pattern, so many engines give each slot its own history copy and let the slot index pick it. With N slots and N copies, slot i draws copy i and reads copy (i − 1) mod N.

Is it safe? The CPU waits on a fence before it reuses a slot, but that fence only says the frame two frames ago is done. The frame in between may still be reading the copy that the new frame will draw. What keeps the copy safe is the queue order and two barriers:

CPU GPU record F0 record F1 waits record F2 waits record F3 F0 · slot 0 draws A F1 · slot 1 reads A · draws B F2 · slot 0 reads B · draws A fence: F0 done 1 2
On one queue the GPU runs F0, F1, F2 in that order, and a barrier also waits for work submitted earlier. So the two barriers are enough, with no extra fence.
  1. After F0 draws A"A was drawn, now it is sampled". F1's read sees all of F0's pixels.
  2. Before F2 draws A"A was sampled, now it is drawn". F2 waits until F1 has read A.
The fence is not enough

The fence only covers F0. When the CPU records F2, F1 may still read A, so barrier 2 is what keeps A safe.

Two consequences follow:

6Mixing the past with the present

The pass has two inputs at every pixel: c, this frame's new value, and h, the history from last frame. It writes the new history h'. Two formulas cover most effects.

Running average

h' = mix(h, c, α)
= (1 − α) · h + α · c

Each frame, the new value gets weight α, and everything older shrinks by (1 − α). The frame i frames ago has weight α·(1 − α)i. This is an exponential moving average. It is used by TAA, denoisers and auto exposure. A small α is smooth but slow; with α = 0.1 the average covers about 1/α = 10 frames.

Decaying trail

h' = max(c, h · k)

The old image gets a bit darker every frame (k < 1), and anything new that is brighter wins at once. A pixel that was lit once and then left alone fades as kn. It is not an average: a bright object stays at full brightness, and only its trail fades.

Both fade the same way once the input goes dark: if c = 0, both give h' = h × (1 − α) or h × k. They differ in how fast they follow a new value. Here is one pixel that an object covers for 10 frames and then leaves, with k = 0.85 and α = 0.15:

1.0 0.5 0 0 10 20 30 40 frame (at 60 fps, 10 frames = 0.17 s) 5 frames later: 0.44 14 later: 0.10 28 later: 0.011 max(c, h × 0.85): trail mix(h, c, 0.15): average input c: object there The object leaves after frame 9. The trail drops from 1.0, the average from 0.80, both by × 0.85 per frame.
The trail jumps to full brightness at once and lags only on the way down. The average lags both ways: after 10 frames it has reached only 1 − 0.8510 = 0.80.

The same two formulas on a whole image. A ball crosses a noisy background and covers each pixel for 10 frames.

Lower α until the noise is gone, and see what happens to the ball in the average. Then raise it. The trail never averages: it keeps the brightest noise it has seen.

How long does a trail last?

After n frames, a pixel keeps kn of its brightness. The half-life, the number of frames to reach 0.5, is ln 0.5 / ln k. For k = 0.85 that is 4.3 frames.

Frames later0.85nTime at 60 fpsTime at 144 fps
10.8517 ms7 ms
4.3 (half-life)0.5071 ms30 ms
50.4483 ms35 ms
140.10233 ms97 ms
280.011467 ms194 ms

The same k gives a trail less than half as long at 144 fps as at 60 fps. The effect depends on the frame rate. To fix that, choose k for a reference rate and raise it to the frame time: with the frame time dt in seconds, use kdt × 60. At 144 fps that gives 0.8560/144 = 0.93 per frame, and the trail lasts the same 0.23 s to reach 10%. For a running average, use 1 − (1 − α)dt × 60 the same way.

60 fps 144 fps 97 ms 233 ms 0 100 ms 200 ms

The same k every frame

The trail reaches 10% after 14 frames: 233 ms at 60 fps, but 97 ms at 144 fps.

60 fps 144 fps 0 100 ms 200 ms

k scaled by the frame time

0.93 per frame at 144 fps: the trail lasts the same 0.23 s at both rates.

float4 trail(float4 current, float4 previous, float dt)
{
    float k = pow(0.85, dt * 60.0);
    return max(current, previous * k);
}

Precision

History is fed back into itself many times, so small errors add up. In an 8-bit image, a value of 3/255 times 0.85 is 2.55/255, which rounds back to 3/255 on hardware that rounds to the nearest step. Dark trails then never quite reach 0. A running average with a small α has the same problem: a change smaller than one step is lost. A 16-bit float format avoids both; it costs twice the memory.

0 1/255 2/255 3/255 4/255 × 0.85 = 2.55 stored: rounds back to 3 an 8-bit image can only hold whole steps
The value goes round in a circle and never gets darker: a dark trail stops at a dark grey.

7When the history is wrong

The formulas trust that h really is "this pixel, last frame". Sometimes it is not:

? ? ? never drawn

First frame

The old copy holds garbage. A new image holds whatever was in that memory. Reading it can show noise or an old frame from another program.

Fix: clear every new copy to a known value before any frame reads it, or pass a flag that says "no history yet" and use c alone on frame 0.

old size new size

Resize

Pixels no longer line up. Images that follow the window size are made again. Keeping the old copy and sampling it with the new size would blend pixels that are no longer at the same place.

Fix: make new copies, clear them, start over. The new copies are new images, so the first-frame rule applies to them too.

a room (last frame) a street (this frame)

Camera cut, teleport, a new level

The old place bleeds in. The image has nothing to do with last frame. Without a reset, the old place fades out over the next frames, like a ghost.

Fix: the CPU knows when this happens, so it tells the shader to ignore h for one frame (a "reset" flag).

ghosts

Something moves

Old pixels stay: ghosting.

Fix: reproject, then clamp or reject (below).

The first three are events the CPU knows about. The last one happens at single pixels, so the shader must detect it. A temporal effect is only as good as its history.

Reprojection: when the camera or objects move

A trail wants the old pixels to stay. TAA and denoisers do not: they want the same surface point, not the same pixel. When the camera moves, that point was at another place on the screen last frame. A motion vector per pixel says how far it moved, and the pass samples the history there:

history (last frame) p' p: wrong place this frame p p' = p − motion(p) Motion comes from the camera (this frame's and last frame's view-projection matrices) and from each object's own movement. The history is read with a filtered sample, since p' is rarely at a pixel center.
Reprojection follows a surface point back in time. Without it, a moving camera smears the image.

Reprojection is not perfect, so the pass also checks the history value:

last frame: hidden this frame: visible

Disocclusion

A point that was hidden last frame (behind an object that moved away) has no history at all. Shading changes too.

3 × 3 min max history

Clamp (TAA)

TAA looks at the 3 × 3 pixels around p in this frame and clamps the history colour into their range (minimum to maximum). A history value far outside that range is surely wrong, and is pulled in.

last frame depth, normal ≠ this frame depth, normal start this pixel over

Reject (denoisers)

Denoisers instead reject the history when depth or normal differ too much, and start that pixel over.

These checks remove most ghosting, at the cost of some flicker.

8Costs

At 1920 × 1080:

7.9 MiBmemory: one 8-bit RGBA copy4 bytes per pixel
15.8 MiBmemory: one 16-bit float RGBA copy; better for averages8 bytes per pixel
2 ×memory with ping-pong, plus a depth image per copy, if the pass draws with depth
0.5 GB/sbandwidth: one more full-screen read per frame; about this much for 8-bit at 60 fps, more with reprojection, which reads several neighbours

Memory sharing: none. History must survive between frames, so it can't share memory with transient images.

A history buffer often does not need the full screen size or format. Auto exposure keeps one pixel. A denoiser may keep half-resolution lighting. Only keep what the next frame really reads.

9Pitfalls

Every second frame the pass samples the image it draws: a feedback loop, validation errors, flicker
"Current" and "previous" image were looked up once, at setup. Look up both every frame. They swap.
Noise or a random old image for one frame, which then fades out
History was read on the first frame. Clear new copies, or use a "no history" flag.
Stretched or shifted ghost image
History was kept after a resize. Make new copies and treat them as new.
The old scene fades through the new one
No reset on a camera cut. Ignore history for one frame.
Smearing and ghosting when the camera moves
The same pixel was used instead of reprojection (TAA, denoise). Use motion vectors, and clamp or reject.
The effect is longer at 30 fps than at 144 fps
A fixed k or α per frame. Scale by the frame time (section 6).
Banding; trails that stop at a dark grey
8-bit history. Use 16-bit float.
Undefined values
The history is sampled while drawing into it. Use two copies, or one copy per pixel in compute.

10In RASM

RASM has history for render targets. A render target created with RenderTargetDesc::history set to true has one set of attachments per frame slot (MAX_FRAMES_IN_FLIGHT = 2). That is ping-pong, picked by the slot index frameCount. New copies are cleared before any frame reads them.

CPU · when the target is created RenderTargetDesc history = true createAttachments 2 copies instead of 1 attachments[0] attachments[1] one per frame slot, own memory, never aliased pendingClears a HistoryClear per copy Every frame, in order beginFrame before any pass clearNewHistory to clearColor → SAMPLED Trail pass reads prev · draws current endPass colors → SAMPLED current = attachments[frameCount], previous = attachments[(frameCount + 1) % 2]. endFrame flips frameCount, so the next frame reads the copy this frame drew.
The clear runs only for new copies: once after creation, and again after each resize that rebuilds the target. After that, every copy is either drawn by a frame or left as it was, and a drawn copy always ends the frame SAMPLED. A storage history target, which a compute pass writes (TAA's), ends it STORAGE.

examples/01_render_graph draws a fading trail of the bunny this way. The Trail pass creates trail_rt with history, declares that it reads the previous copy, and draws the current one:

graph.addPass(
    "Trail",
    [&rtHandle, &trailHandle, colorFormat](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);
        builder.readPrevious(trailHandle);
        builder.write(trailHandle);
    },

    [&engine, &drawFullScreen, &trailPipeline, &rtHandle, &trailHandle](rasm::RenderContext &ctx)
    {
        drawFullScreen(ctx, trailPipeline, engine.getBindlessTextureIndex(engine.getRenderTargetTexture(rtHandle)),
                       engine.getBindlessTextureIndex(engine.getPreviousRenderTargetTexture(trailHandle)));
    });

Its fragment shader is the decaying trail from section 6, with k = 0.85 per frame:

float4 fragMain(VSOutput input) : SV_TARGET
{
    float4 current = gTextures[pc.indices[0]].Sample(input.UV);
    float4 previous = gTextures[pc.indices[1]].Sample(input.UV);
    return max(current, previous * 0.85);
}

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Copiestwo, ping-pongOne per frame slot in RenderTarget::attachments: MAX_FRAMES_IN_FLIGHT = 2. A target without history has one copy that every slot shares (createAttachments).
Picking the copyn mod 2 and (n + 1) mod 2Renderer::getRenderTargetTexture returns copy frameCount; Renderer::getPreviousRenderTargetTexture returns copy (frameCount + MAX_FRAMES_IN_FLIGHT - 1) % MAX_FRAMES_IN_FLIGHT, and an invalid handle for a target without history. Both take a color index for targets with several colors.
Feedback loopnever read and draw one imageRenderGraph::compile fails when a pass reads the target it draws to with read. PassBuilder::readPrevious is the allowed way: the previous copy is never drawn this frame, so it adds no edge. It logs an error and ignores the read for a target without history.
History of a buffertwo copies, or read before the writePassBuilder::readPrevious also takes a buffer. A buffer has one copy, so the read adds no edge from this frame's writers and runs before the first of them; its barrier still waits for last frame's write. The scene's occlusion culling reads its visibility flags this way (occlusion culling). A buffer with one copy per frame slot (BufferHandle[MAX_FRAMES_IN_FLIGHT]) is ping-pong too: readPrevious of the pair reads the slot the frame before wrote, which the Animate pass does for last frame's matrices (keyframe animation).
Barriersdrawn → sampled, sampled → drawnRenderer::endPass moves the colors to SAMPLED (B10). beginPass moves the copy back to COLOR_ATTACHMENT; texture states carry over between frames, so that barrier waits for last frame's reads. readPrevious of a drawn target records no barrier: the copy is already SAMPLED. A storage history target's last copy is still STORAGE from its compute writer, so the graph moves it to SAMPLED before the pass (storage targets).
First frameclear, or a "no history" flagClear. createAttachments queues a HistoryClear for each new copy in pendingClears, and for the color of any target that is not transient, such as a view texture that may be sampled before its first frame. Renderer::beginFrame records RenderContext::clearNewHistory before any pass: each copy is cleared to clearColor and left SAMPLED, so the previous copy is safe to sample, in a graph or not. Only the colors are cleared, not the depth.
A frame that is not submitted—Its clears move from recordedClears back to pendingClears (RenderContext::discardRecording) and run with the next frame. Destroying a copy drops its clear (destroyAttachments).
Resizenew copies, start overA target with swapchainScale is rebuilt by RenderContext::resizeRenderTargets, and its new copies are cleared again. They keep the old bindless indices. A target with a fixed size keeps its history.
Camera cutignore history for one frameFor TAA, Renderer::resetCameraHistory: the camera's next frame starts over; TAA also starts over after a resize or a camera jump (TAA). A pass of your own that must forget the past has to ignore the previous copy itself.
Reprojection, clampingmotion vectors, 3 × 3 clampTAA does both: the scene passes write a MOTION_FORMAT color, and Renderer::addTaaPass reprojects its history target with it and clips the history to the color box of the pixel's neighbourhood (TAA). The trail of the example samples the same pixel, which is what a trail wants.
Decay per framescale by the frame timeThe example uses a fixed 0.85 per frame, so its trail is shorter at a higher frame rate.
Format16-bit float for averagesAny color format. The example uses the swapchain's (getSwapchainImageFormat, usually B8G8R8A8_SRGB), which is fine for a short trail.
Memorytwo copies, no sharingTwo sets of colors and depth. RenderContext::createTransientRenderTarget rejects a history desc, and RenderGraph::createRenderTarget sends one to Renderer::createRenderTarget: own memory, never aliased, freed with the graph that made it (RenderGraph::historyTargets). One made with Renderer::createRenderTarget is kept until shutdown.

Because the copies swap, look up both textures and their bindless indices inside the pass's execute function, every frame, as the example does. See also the API reference and Render graphs.

Where it lives in code

WhatWhere
The flag and the clear colorRenderTargetDesc::history, RenderTargetDesc::clearColor in include/rasm/render/resource.h
The copiesRenderTarget::attachments in include/rasm/types.h
Making and freeing copiesRenderContext::createAttachments, RenderContext::destroyAttachments in src/rhi/renderContext.cpp
Clearing new copiesRenderContext::clearNewHistory, HistoryClear, RenderContext::discardRecording in src/rhi/renderContext.cpp; called by Renderer::beginFrame in src/renderer/renderer.cpp
ResizeRenderContext::resizeRenderTargets in src/rhi/renderContext.cpp
Not transientRenderContext::createTransientRenderTarget; RenderGraph::createRenderTarget in src/renderer/renderGraph.cpp
Picking the copyRenderer::getRenderTargetTexture, Renderer::getPreviousRenderTargetTexture in src/renderer/renderer.cpp
Drawn → sampledRenderer::endPass in src/renderer/renderer.cpp
Declaring the readPassBuilder::readPrevious, RenderGraph::readPrevious in src/renderer/renderGraph.cpp
The examplethe Trail pass in examples/01_render_graph/main.cpp
Keep these true
  • Look up getRenderTargetTexture, getPreviousRenderTargetTexture and their bindless indices every frame, inside execute. Fetched once, they point at the wrong copy every second frame.
  • Never read the target a pass draws to. Read last frame's copy with readPrevious.
  • Every new history copy must be cleared before a frame reads it. A new way to make copies goes through createAttachments, which queues the HistoryClear; destroying a copy must drop it.
  • clearNewHistory runs in beginFrame, before any pass. A frame that is not submitted gives its clears back (discardRecording).
  • endPass leaves every color SAMPLED. readPrevious of a drawn target records no barrier because it relies on that; a storage history target's last copy is moved from STORAGE.
  • A history target is never transient: its memory must survive to the next frame.

Further reading