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:
Many well-known effects work this way. They differ in what they keep and how they mix it:
Trails, motion trails
Keeps: last frame's trail image.
Keeps the brighter of "new" and "old, a bit darker".
Accumulation (path tracing, a still camera)
Keeps: the average of all frames so far.
Adds one more noisy sample to the average.
Temporal anti-aliasing (TAA)
Keeps: last frame's smooth image.
Moves the camera by less than a pixel each frame and averages the results.
Temporal denoising
Keeps: last frame's filtered lighting.
Averages noisy lighting over time instead of over many rays.
Motion blur (simple)
Keeps: last frame's image.
Blends it in where things move.
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:
- The GPU shades many pixels at once, in an order you do not control. A pixel shader that samples the image may get the old value, the new value, or a value that is half written.
- Worse, the image is in a layout for drawing, not for sampling, and caches for the two are not kept in step.
This is a feedback loop, and graphics APIs call its result undefined. Validation layers report it.
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.
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.
4Other ways to keep the past
Ping-pong is the usual choice, but not the only one:
Ping-pong
Two copies, swap the roles each frame.
Good for: most temporal effects.
Cost: 2 images, no copy
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
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
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:
- After F0 draws A"A was drawn, now it is sampled". F1's read sees all of F0's pixels.
- Before F2 draws A"A was sampled, now it is drawn". F2 waits until F1 has read A.
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:
- Two copies are enough for any number of slots, because the GPU runs the frames one after the other. A copy per slot is a convenience: the index is already there. With exactly two slots, the two ideas are the same.
- The copies are written by the GPU only. Data the CPU writes every frame needs a copy per slot for another reason (the CPU must not overwrite what the GPU still reads). History needs its copies because one pass reads and draws it.
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:
The same two formulas on a whole image. A ball crosses a noisy background and covers each pixel for 10 frames.
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 later | 0.85n | Time at 60 fps | Time at 144 fps |
|---|---|---|---|
| 1 | 0.85 | 17 ms | 7 ms |
| 4.3 (half-life) | 0.50 | 71 ms | 30 ms |
| 5 | 0.44 | 83 ms | 35 ms |
| 14 | 0.10 | 233 ms | 97 ms |
| 28 | 0.011 | 467 ms | 194 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.
The same k every frame
The trail reaches 10% after 14 frames: 233 ms at 60 fps, but 97 ms at 144 fps.
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.
7When the history is wrong
The formulas trust that h really is "this pixel, last frame". Sometimes it is not:
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.
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.
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).
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:
Reprojection is not perfect, so the pass also checks the history value:
Disocclusion
A point that was hidden last frame (behind an object that moved away) has no history at all. Shading changes too.
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.
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:
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.
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
| Part | This page | RASM |
|---|---|---|
| Copies | two, ping-pong | One 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 copy | n mod 2 and (n + 1) mod 2 | Renderer::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 loop | never read and draw one image | RenderGraph::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 buffer | two copies, or read before the write | PassBuilder::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). |
| Barriers | drawn → sampled, sampled → drawn | Renderer::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 frame | clear, or a "no history" flag | Clear. 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). |
| Resize | new copies, start over | A 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 cut | ignore history for one frame | For 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, clamping | motion vectors, 3 × 3 clamp | TAA 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 frame | scale by the frame time | The example uses a fixed 0.85 per frame, so its trail is shorter at a higher frame rate. |
| Format | 16-bit float for averages | Any color format. The example uses the swapchain's (getSwapchainImageFormat, usually B8G8R8A8_SRGB), which is fine for a short trail. |
| Memory | two copies, no sharing | Two 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
| What | Where |
|---|---|
| The flag and the clear color | RenderTargetDesc::history, RenderTargetDesc::clearColor in include/rasm/render/resource.h |
| The copies | RenderTarget::attachments in include/rasm/types.h |
| Making and freeing copies | RenderContext::createAttachments, RenderContext::destroyAttachments in src/rhi/renderContext.cpp |
| Clearing new copies | RenderContext::clearNewHistory, HistoryClear, RenderContext::discardRecording in src/rhi/renderContext.cpp; called by Renderer::beginFrame in src/renderer/renderer.cpp |
| Resize | RenderContext::resizeRenderTargets in src/rhi/renderContext.cpp |
| Not transient | RenderContext::createTransientRenderTarget; RenderGraph::createRenderTarget in src/renderer/renderGraph.cpp |
| Picking the copy | Renderer::getRenderTargetTexture, Renderer::getPreviousRenderTargetTexture in src/renderer/renderer.cpp |
| Drawn → sampled | Renderer::endPass in src/renderer/renderer.cpp |
| Declaring the read | PassBuilder::readPrevious, RenderGraph::readPrevious in src/renderer/renderGraph.cpp |
| The example | the Trail pass in examples/01_render_graph/main.cpp |
- Look up
getRenderTargetTexture,getPreviousRenderTargetTextureand their bindless indices every frame, inside execute. Fetched once, they point at the wrong copy every second frame. - Never
readthe target a pass draws to. Read last frame's copy withreadPrevious. - Every new history copy must be cleared before a frame reads it. A new way to make copies goes through
createAttachments, which queues theHistoryClear; destroying a copy must drop it. clearNewHistoryruns inbeginFrame, before any pass. A frame that is not submitted gives its clears back (discardRecording).endPassleaves every colorSAMPLED.readPreviousof a drawn target records no barrier because it relies on that; a storage history target's last copy is moved fromSTORAGE.- A history target is never transient: its memory must survive to the next frame.
Further reading
- Brian Karis, High Quality Temporal Supersampling, SIGGRAPH 2014 course "Advances in Real-Time Rendering": TAA with reprojection and neighbourhood clamping.
- Lei Yang, Shiqiu Liu and Marco Salvi, A Survey of Temporal Antialiasing Techniques, Eurographics 2020: history validation, rejection and ghosting.
- Christoph Schied and others, Spatiotemporal Variance-Guided Filtering, HPG 2017: temporal accumulation for denoising.
- Yuriy O'Donnell, FrameGraph: Extensible Rendering Architecture in Frostbite, GDC 2017: history as an imported resource in a render graph.
- Frames in flight, GPU synchronization, Transient memory and aliasing.