Foundations
Headless rendering and readback
Not every frame is for a screen. A test compares a frame with a stored image, a tool makes thumbnails, a server renders a map tile. Such a program renders headless, with no window, and then reads the pixels back from the GPU to the CPU. This page explains both: what takes the place of the window, how a copy reaches the CPU without stopping the GPU, how to turn the GPU's formats into plain pixels, and how to get the same pixels on every run. The last part shows how RASM does it.
In short
- Headless: no window, no surface, no swapchain. The frame renders into images the program owns, which play the swapchain's role.
- The GPU's images live in its own memory, in a layout only it knows. A copy moves them, row by row, into a buffer the CPU can read.
- The copy is done only when the GPU has finished that frame. Wait on that frame's fence, a few frames later, and the CPU never stalls.
- The bytes come in the image's format: BGRA order, sRGB numbers, half floats, depth. Convert them to what a PNG or an HDR file needs.
- For a test, the same frame must give the same pixels on every run: wait for all loads, use a fixed time, and keep the GPU work in a fixed order.
1Why render without a window
A window is one place a frame can go. Many programs want the pixels themselves:
Image tests
A test renders a scene and compares it with an approved image. A shader change that breaks the picture fails the test.
Thumbnails and screenshots
An asset browser renders each model once into a small image and saves it. A game saves the frame on a key press.
Servers and CI machines
A build machine or a tile server has no display at all. A window can't even be opened there.
Offline video
Frames for a video are rendered as slowly as they need to be, each at its exact time, and written to files.
2What takes the place of the window
With a window, the frame's last pass draws into a swapchain image, and present hands it to the screen (The swapchain). Without one, there is no surface, so there can be no swapchain. The program makes its own images instead, and the last pass draws into them:
Window
Surface, swapchain, acquire and present. The system decides which image comes next.
Headless
No surface, no swapchain extension. The program takes its images in turn, and "present" does nothing.
Keep the same shape as a swapchain: a few images, one per frame in flight, handed out in turn. Then the rest of the renderer does not change: the tone map still writes "the output image", and only the end of the frame differs. An image is handed out again only once the GPU has finished the last frame that drew into it, as the presentation engine would do.
Once the renderer no longer assumes a window, the window becomes one choice among several: a window the engine opens, a window the application owns, or none. The engine only needs to know where the frame goes and where the input comes from.
3The copy to the CPU
A rendered image sits in GPU memory, and the GPU stores it in its own tiled order: small blocks of pixels together, often compressed. The CPU can't read that. A copy command rewrites the image into a buffer as plain rows, in memory the CPU can map:
- 1. BarrierThe image waits for its last writer, and moves to the copy-source layout.
- 2. CopyImage → buffer, one layer and one mip at a time.
- 3. BarrierThe image goes back to its layout; the buffer's bytes are made visible to the host.
- 4. ReadAfter the fence: map the buffer and read the rows.
The image must allow the copy: it is created with copy-source usage. That flag is not free on every GPU: some drivers keep less compression for an image that may be copied, so engines ask for it only on the images they will read.
4When are the pixels there?
The copy is only recorded in the frame's commands. It runs when the GPU reaches it, which is after the CPU has moved on (Frames in flight). The simple way, to wait for the GPU to be idle right after the submit, works but stops the whole pipeline. The better way is to wait for the fence of the frame that made the copy, later:
Wait at once
The CPU waits for frame F, then the GPU waits for the CPU. Fine for one screenshot, bad for every frame.
Wait on F's fence, later
With N frames in flight the CPU waits for frame F at the start of frame F + N anyway. Reading the copy then costs nothing.
So a readback is a small state machine: asked, then recorded into a frame, then done when that frame's fence value is reached, then taken. The program polls "is it done?" each frame and keeps rendering. Try it: the lab computes the same rule as the frame loop, with the CPU waiting for its frame slot at the start of each frame.
5Converting the pixels
The buffer holds the image's own format. A PNG wants 8-bit RGBA in sRGB; an HDR file or a test of light values wants linear floats. Each source needs its own small rule:
Byte order
Window images are often BGRA. Swap red and blue; the bytes stay exact.
sRGB curve
Linear light gets the sRGB curve for a PNG; an sRGB image is decoded for floats (Color spaces).
Half floats
HDR images hold 16-bit floats. Widen them to 32 bits; values above 1 stay, for HDR.
Two more rules. A depth image gives one float per pixel, so it reads as floats only. And an HDR value has no 8-bit form of its own: turning 25.0 into a byte means clamping it to 1 (or tone mapping it first), so a screenshot reads the tone-mapped frame, not the HDR target.
sRGB(c) = 12.92 · c, when c ≤ 0.0031308
sRGB(c) = 1.055 · c1/2.4 − 0.055, otherwise
- c
- a linear value, clamped to 0..1
- sRGB(c)
- the stored number, times 255 and rounded for 8 bits
6The same pixels on every run
An image test compares frame N of one run with frame N of another. Everything that decides what frame N shows must then be the same, not only the scene:
Background loads
A file that loads in the background shows from the frame its load ends, which depends on the clock. Wait for every load before frame 1.
Time
Animation and anything else driven by the wall clock moves by a different amount each run. Step time by a fixed amount per frame.
Order on the GPU
Threads that append with atomics land in any order. Where order changes pixels (blending, ties), use a fixed order: prefix sums, a stable sort.
History counts too. Temporal effects (TAA, occlusion culling from the last frame) make frame N depend on the frames before it, so a test renders the same number of frames, with the same inputs, every run. And the GPU and its driver are part of the result: two GPUs round some math differently, so stored images belong to one driver, and tests compare with a small tolerance.
7Pitfalls
- The frame rate drops while screenshots are taken
- The program waits for the copy in the frame that asked for it. Poll the fence and take the pixels a few frames later.
- The image is all black or random
- The copy ran before the frame's passes wrote the image, or the bytes were read before the fence. The copy goes after the last pass, and the read after the fence.
- Red and blue are swapped
- The image is BGRA and was written to a file as RGBA.
- The PNG is too dark or washed out
- The sRGB curve is applied twice, or not at all: an sRGB image's bytes are already encoded, a linear image's are not.
- Rows are shifted or slanted
- The row pitch is wider than width × bytes per pixel (padding), and the reader assumed none.
- The copy of a temporary target shows another image
- Its memory was shared with a later target (Memory aliasing), which overwrote it before the copy at the end of the frame. A target that is read back needs memory of its own.
- A multisampled image can't be copied
- Copy commands take one sample per pixel. Read the resolved image.
8In RASM
RASM chooses the platform in EngineConfig::platform. PlatformType::SDL opens a window, PlatformType::NATIVE draws into the application's (The platform layer); PlatformType::HEADLESS opens none, starts no SDL and creates a Vulkan device without a surface. The frames then render into an OffscreenSwapchain: two readable R8G8B8A8_SRGB images on the device, which the rest of the engine sees as the swapchain. A readback is asked for with Renderer::readFrame or Renderer::readTexture and recorded at the end of the next frame. Each window has its own swapchain, offscreen when headless (Renderer::addWindow), and readFrame(window) copies that window's image; a window with no image that frame (minimized) is copied in the next frame that has one.
readFrame copies the window's image. For a still larger than the window or than the device's largest image, with no seams and averaged samples, use exportView (Tiled offscreen export).endFrame skips the move to the present layout for an offscreen image.| This page | RASM |
|---|---|
| Images of your own instead of a swapchain | OffscreenSwapchain, an rhi::Swapchain on rhi::Device textures, so every backend gets it. MAX_FRAMES_IN_FLIGHT images, each handed out again after the frame fence of its last present submit (submitted). |
| Copy-source usage only where needed | TextureDesc::readable, RenderTargetDesc::readable (off by default). A window's swapchain images get it when the surface's supportedUsageFlags has TRANSFER_SRC; else readFrame returns invalid. |
| Barrier, copy, barrier | rhi::CommandBuffer::copyFromTexture: the image goes to the copy layout and back to its tracked state, then a copy → host barrier. Rows are tightly packed. |
| Wait on the frame's fence, later | Each readback keeps the frame fence value of the frame that copied it. isReadbackReady compares it with the fence; takeReadback waits only when called too early. |
| Read back only what you need | A pick copies only the rect it drew, through the same frame fence: isPickReady, takePick (Picking). |
| A temporary target needs memory of its own | A graph makes a readable target outside the shared transient memory, as it does a history target. |
| Convert on the CPU | convertReadback, when the image is taken: ReadbackFormat::RGBA8_SRGB or RGBA32_FLOAT. |
| Wait for all loads | Renderer::waitForLoads; the examples call it with --wait-for-loads (C16), which verify-change passes. |
| A fixed time step | EngineConfig::fixedDeltaTime: the cameras' easing, Dear ImGui and the stats' refresh step by it instead of the measured frame time (C15). The examples set 1/60 s with --fixed-step. |
| The UI without a window | Dear ImGui runs with no SDL: the display is the window's size (newUiPlatformFrame), its input is whatever the application sends with Renderer::addInputEvent (none by default), and the UI draws through the offscreen images' R8G8B8A8_UNORM view (TextureDesc::encodedView), so it looks as on a window. |
| Compare with a stored image, with a tolerance | readPng reads a stored PNG back as an RGBA8_SRGB image, the format writePng writes. The golden-image tests compare frames this way (Image tests). |
| A fixed GPU order | Culling compacts draws with prefix sums, the light clusters use integer atomics whose result does not depend on order, and the blend sort is a fixed bitonic network, so a frame does not depend on thread timing. |
| Bring your own window | PlatformType::NATIVE draws into the application's window, and the application sends the input (The platform layer). A native window's frames are read the same way when its surface allows copies: 19_embedding --headless renders into a hidden window and writes frame N. |
Every example runs headless
Each example takes --headless --frames N --out file.png (examples/exampleArgs.h). applyExampleArgs sets PlatformType::HEADLESS, and the frame loop runs on exampleRunning instead of Renderer::running: it asks for the copy right before frame N, takes it after frame N, writes the PNG and ends the loop. main returns exampleExit, which is 1 with an error when the frame was not written (the copy or the write failed, or the loop ended before frame N). So a run opens no window, and verify-change checks every example this way.
--fixed-step, EngineConfig::fixedDeltaTime is 1/60 s, so the cameras, the UI and the stats step the same way in every run.Code map
| What | Where |
|---|---|
| The platform choice, events | Platform in src/platform/platform.h; src/platform/sdlPlatform.cpp, src/platform/headlessPlatform.cpp, src/platform/nativePlatform.cpp; Renderer::pollEvents in src/renderer/renderer.cpp |
| A device without a surface | VulkanDevice::initialize in src/rhi/vulkan/vulkanDevice.cpp |
| The offscreen images | src/rhi/offscreenSwapchain.cpp; made in RenderContext::initialize (src/rhi/renderContext.cpp) |
| The copy | VulkanCommandBuffer::copyFromTexture, RenderContext::copyTextureToBuffer |
| Readbacks and conversion | src/renderer/readback.cpp: Renderer::readFrame, readTexture, isReadbackReady, takeReadback, recordReadbacks, convertReadback, writePng, readPng |
| The example | examples/16_headless/main.cpp: a PNG of the frame and the HDR target's brightest and mean values |
| Every example's flags | parseExampleArgs, applyExampleArgs, exampleRunning, exampleExit in examples/exampleArgs.h |
| The UI without a window | src/platform/uiPlatform.cpp |
| Tests | tests/readbackTests.cpp: every conversion, and a PNG written with writePng and read again with readPng |
A readback is recorded after every pass and the UI, before the image moves to the present layout. Never wait for a readback in the frame that asked for it. A render target that is read back is made readable; do not add copy-source usage to images nobody reads.
Further reading
- Vulkan specification, "Copying Data Between Buffers and Images" (
vkCmdCopyImageToBuffer2). - Khronos, "Synchronization examples": a transfer write read by the host.
- Frames in flight, The swapchain and presenting, Color spaces.