Foundations

The swapchain and presenting

A program never draws straight onto the screen. It draws into an image, and hands the image to the system, which shows it at the next refresh. The swapchain is the small set of images that goes round between the two. This page explains the loop (acquire, render, present), the sync it needs, the present modes behind "vsync", and what to do when the window changes size. The last part shows how RASM does it.

In short

  • A swapchain is a ring of 2 to 4 images owned by the presentation engine (the OS compositor or display).
  • Each frame: acquire an image, render into it, present it.
  • Acquire returns before the image is really free. An acquire semaphore makes the GPU wait; a present semaphore makes the present wait for the rendering.
  • The present mode decides what happens at the refresh: wait for it (FIFO, vsync), replace the waiting image (MAILBOX), or show at once and tear (IMMEDIATE).
  • When the window changes, the swapchain becomes out of date or suboptimal. The program then builds a new one, and everything sized like it.
  • A minimized window has size 0 × 0: no swapchain can exist for it, so frames are skipped.

1Why not draw onto the screen

The display reads its picture from memory, line by line, about 60 to 240 times per second. What happens when the program draws into that same memory?

new frame old frame the display reads here

One image

The program draws into the memory the display reads. The display shows half-drawn frames.

on screen drawn into swap when the new one is done

Several images

The display shows one, while the program draws into another. When the new one is done, they swap.

That is the old idea of double buffering, and a swapchain is its modern, explicit form.

Free nobody uses it Drawn into owned by the program Queued waits for a refresh On screen the display reads it acquire present next refresh replaced The images never move or copy. Only their role changes.
With 3 images, one can be on screen, one queued and one drawn into, all at once. With 2, the program must wait whenever one is queued.

The images belong to the presentation engine, not to the program. The program asks for one, may draw into it until it gives it back, and must not touch it after that. The engine decides which image comes next, and when.

2The loop: acquire, render, present

  1. 1. AcquireAsk the swapchain for the next image. The answer is an index into its images. It may block when every image is in use.
  2. 2. RenderRecord commands that draw into that image, and submit them.
  3. 3. PresentGive the image back, with a request to show it.

There is a catch in step 1. Acquire returns as soon as the swapchain knows which image comes next, which can be before the display has stopped reading it. So the index alone does not make it safe to draw. The image becomes free at some later moment, and only the GPU timeline knows when.

Two semaphores handle this. A semaphore is a GPU-side signal: one submission signals it, and another one waits for it. The CPU never waits on it.

CPU GPU queue presentation engine acquire submit present culling, shadows, other passes draw into the image display done with it: signal acquire sem. show it returns an index at once wait present sem.
The GPU waits for the acquire semaphore only at the stage that writes the image (color output). Everything before that stage in the same submission already runs while the display still holds the image.
SemaphoreSignaled byWaited on byWait where
Acquire ("image available")the presentation engine, when the image is freethe submission that draws into the imagethe color output stage, so earlier work is not held back
Present ("render finished")that submission, when it is donethe present callthe presentation engine, before it reads the image

Before present, the image must also be in the layout the display can read (in Vulkan: PRESENT_SRC). Its old contents do not matter at acquire, so the first barrier of the frame can discard them. See GPU synchronization for layouts and barriers.

When may a semaphore be used again?

A binary semaphore must be waited on once before it is signaled again. That makes reuse the most common swapchain bug:

SemaphoreFree again whenSo keep
Acquirethe submission that waited on it has finished, which a fence tells the CPUone per frame in flight, reused after that frame's fence wait
Presentthe present has waited on it. The program cannot observe that directly (without an extension that gives present a fence).one per swapchain image. An image is acquired again only after its last present finished, so by then its semaphore is free.
present n: waits on S0 frame n + 2 signals S0 time S0 is used twice at once

One present semaphore per frame in flight

It looks right and works on many machines, but the present of frame n may still hold it when frame n + 2 signals it again. Validation layers now report this.

image 0 image 1 image 2 S0 S1 S2 a semaphore follows its image

One per swapchain image

An image is acquired again only after its last present finished. By then its semaphore is free.

3Present modes and vsync

The display refreshes at fixed times, the vertical blank (vblank). The present mode says what happens to a presented image between two of them.

dashed: a vblank, every 16.7 ms FIFO GPU 0 1 2 3 4 5 screen 0 1 2 3 4 every frame shown once, no tearing; the GPU idles 6.7 ms per refresh MAILBOX GPU 0 1 2 3 4 5 6 7 8 9 screen 0 2 3 5 7 newest frame at each refresh, no tearing; dashed frames are drawn and never shown IMMEDIATE GPU 0 1 2 3 4 5 6 7 8 9 screen 0 1 2 3 4 5 6 7 8 shown as soon as done: lowest latency, but a switch in the middle of a refresh is a tear line 0 16.7 33.3 50 66.7 83.3 100 ms
A 60 Hz display and a GPU that needs 10 ms per frame, 6 pixels per millisecond. In FIFO with two images, the GPU starts the next frame only when a refresh frees an image. Orange lines: the screen switches images while the display is drawing it.

The four modes, by their Vulkan names:

queue 2 1 vblank 1 screen

FIFO

At a refresh, shows the oldest queued image. A full queue makes acquire or present block.

"vsync on". Always supported. Saves power: the GPU does not render frames nobody sees.

Tearing: no · Latency: higher

queue empty vblank 1 late 0 1 screen

FIFO_RELAXED

Like FIFO, but an image that arrives late is shown at once.

Avoids a whole lost refresh when a frame is a little late.

Tearing: only when late · Latency: higher

one place 2 3 replaced vblank 3 screen

MAILBOX

At a refresh, shows the newest image. A new present replaces the queued one.

"Triple buffering" in the classic sense. The GPU runs flat out; frames are wasted.

Tearing: no · Latency: low

1 presented at once 1 0 tear line

IMMEDIATE

Does not wait for a refresh.

"vsync off". Liked by competitive games.

Tearing: yes · Latency: lowest

Worked example: when the GPU is too slow for FIFO

A 60 Hz display refreshes every 16.7 ms. With FIFO, a frame can only appear at a refresh. These numbers come from stepping the rules above with a fixed GPU time per frame:

60frames shown per second: GPU 10 ms per frame, 2 or 3 imageseach stays 16.7 ms, every time
30frames shown per second: GPU 20 ms per frame, 2 imageseach stays 33.3 ms, every time
about 50frames shown per second: GPU 20 ms per frame, 3 imagesmostly 16.7 ms, every fifth 33.3 ms
FIFO, 2 images, 20 ms per frame GPU 0 no free image 1 no free image 2 no free image screen 0 1 0 16.7 33.3 50 66.7 83.3 100 ms
Dashed: a vblank. A finished frame waits for the next refresh, and the GPU has no free image during that wait.

With 2 images and 20 ms frames, the GPU loses the rest of each refresh, so it drops all the way to 30. A third image lets the GPU start the next frame during the wait. The average is close to the GPU's own 50, but the timing is uneven, which the eye notices as judder.

Step the same rules yourself, for any GPU time. The display stays at 60 Hz.

the GPU draws a frame the frame on screen; dashed: a frame that is never shown the GPU waits: no free image a tear line
In FIFO, raise the GPU time past 16.7 ms with 2 images, then with 3. Then try MAILBOX and IMMEDIATE at 10 ms and watch the small screen.

4When the swapchain no longer fits

A swapchain is built for one window size and one surface. When the window changes, acquire and present report it:

swapchain image the window now stretched to fit

Suboptimal

The image was acquired or presented, but the swapchain no longer matches the surface exactly (for example, its size).

Do: finish and present this frame. Rebuild before the next one.

no image acquired

Out of date

The swapchain cannot be used any more. From acquire: no image was acquired.

Do: skip this frame. Rebuild.

surface: 0 × 0 the window

Surface size 0 × 0

The window is minimized. No swapchain can be built for it.

Do: skip frames, ideally sleeping until a window event, until the size is back.

Most programs also listen to the window system's own resize event, because not every platform reports out of date in time. Rebuilding works like this:

  1. Wait for the GPU. The old images may still be in use by frames in flight. The simple way is to wait until the device is idle; resize is rare, so the stall does not matter.
  2. Build the new swapchain with the new size, passing the old one as "old swapchain". That lets the system hand over smoothly, and retires the old one even if the build fails.
  3. Destroy the old swapchain and its image views.
  4. Rebuild what has the screen's size: depth buffers, full-screen render targets, the viewport, and the camera's aspect ratio.
  5. Use the swapchain's size, not the window's. The surface picks the final size, and on high-DPI screens it is in pixels, while the window size may be in points.
Signaled semaphores across a rebuild

A rebuild can happen between acquire and present. Then an acquire semaphore may be signaled and never waited on, and a binary semaphore in that state cannot be signaled again. A robust rebuild first makes sure every signaled semaphore is waited on (for example, with an empty submission that only waits), or destroys and recreates the semaphores.

5Format and color space

The swapchain also fixes the pixel format and the color space the display expects. A common choice is an 8-bit BGRA or RGBA format with an sRGB encoding.

  1. Shaderoutputs linear color
  2. sRGB formatthe hardware converts linear to sRGB when it writes
  3. Displaygets the sRGB it expects

HDR displays need other color spaces and wider formats. See color spaces: sRGB and linear.

6Pitfalls

Drawing as soon as acquire returns, with no semaphore wait
The display may still read the image: flicker or garbage, on some machines only.
Present semaphores per frame in flight
A semaphore is signaled while a present still waits on it (section 2).
Treating the image index as the frame slot
The order of images is up to the swapchain, and their count is not the number of frames in flight. Index frame resources by the slot (see frames in flight).
Ignoring suboptimal or out of date
A stretched picture after resize, or errors on every frame.
Forgetting the layout change to "present"
The display reads an image in a layout it does not understand.
Not presenting an acquired image
The image stays out of the ring. After a few such frames, acquire has no image left to give.

7In RASM

VulkanSwapchain builds the swapchain with vk-bootstrap and owns all of its sync objects. No semaphore crosses the RHI: a submit only names the swapchains, to wait for their images (SubmitDesc::acquireSwapchains) or to present them (SubmitDesc::presentSwapchains), and each swapchain fills in its waits and signals. Each window has its own swapchain (Renderer::addWindow): the main window's uses the surface the device was chosen for, another makes a surface of its own, and the device checks that its graphics queue can present to it (vkGetPhysicalDeviceSurfaceSupportKHR). A frame is one submit, or with async compute a few (the frame loop): the first graphics submit waits for every window's image, and the last one presents them all; each window is then presented with its own vkQueuePresentKHR. The engine's frame loop handles skipped frames and resize.

No window, no swapchain

A headless engine (PlatformType::HEADLESS) has no surface. RenderContext then makes an OffscreenSwapchain instead: two readable R8G8B8A8_SRGB images on the device, handed out in turn, each after the frame fence of the last submit that drew into it. Submits name no swapchain, and present does nothing. The window's images also get copy-source usage when the surface allows it, so readFrame can read either. See Headless rendering and readback.

CPU graphics queue presentation engine acquireNextImage vkAcquireNextImageKHR submit vkQueueSubmit2 per batch present vkQueuePresentKHR frame work one submit per batch image is free signals the acquire semaphore shows the image after the wait acquireSemaphores[slot] presentSemaphores[image] releaseTimeline frameFence signal first graphics submit waits at color output last one signals wait signal next value each signals a value a later acquire waits here (CPU)
The frame's submits wait on one semaphore and signal three: the first graphics submit waits, the last one presents. With one submit, it does both. Every graphics submit names the image for the wait, but only the first one waits: the semaphore is binary, so a second wait would never end. The release timeline tells acquireNextImage when an acquire semaphore is free again, without depending on how the engine paces its frames.
Sync objectKindHow manyFree again when
acquireSemaphoresbinaryMAX_FRAMES_IN_FLIGHT (2), used in turn by nextAcquireSlotreleaseTimeline reaches the value in acquireReleaseValues for that slot: the submit that waited on it is done
presentSemaphoresbinaryone per swapchain imagethe image is acquired again. They survive a resize; a swapchain with more images only adds more.
releaseTimelinetimeline1— (values only grow; releaseValue is the last one signaled)

The order is enforced

Idle acquiredSlot = NO_ACQUIRE presentPending = false Acquired acquiredSlot = the slot Submitted presentPending = true acquire: OK or SUBOPTIMAL onSubmitted present (any result) acquire again → the same image
The first submit that waits for the image sets acquireWaited (onAcquireWaited), so later submits of the frame skip the wait; present clears it. A call in the wrong state logs an error and fails: a submit that waits for or presents the image while Idle, an acquire while Submitted (FAILURE), a present that does not follow a successful submit. "Acquire again" happens after a failed submit: the image is still acquired and its semaphore still signaled, so it is handed out again.

The frame loop around it

beginFrame minimized, or pixel size 0? yes skip the frame resized, or swapchainOutOfDate? yes recreateSwapchain fails → skip the frame fence wait, then acquireNextImage record passes into the image OUT_OF_DATE: set the flag, skip SUBOPTIMAL: set the flag, go on FAILURE: skip endFrame nothing drew to the image? a "Clear" pass draws it image → PRESENT_SRC submitBatches the last one presents present if that submit worked SUBOPTIMAL or OUT_OF_DATE: set the flag, rebuild next frame
The window's WindowFrame::outOfDate carries the news to the next beginFrame, for that window only. The window sets resized on SDL's pixel-size event, or when a NATIVE application calls setWindowSize, so the swapchain follows the size in pixels (B17).

Resize, step by step

  1. Ask the surface. VulkanSwapchain::resize reads the surface size. A 0 × 0 surface returns OUT_OF_DATE and keeps the old swapchain (B5). A failed query returns FAILURE and keeps it too.
  2. Consume pending signals. releasePendingSemaphores submits a wait-only batch for an image that was acquired but not submitted, and for one submitted but not presented.
  3. Go idle and rebuild. The device waits idle, the old image views go, and the new swapchain is built with the old one as oldSwapchain. The old one is destroyed either way. If the build fails, there is no swapchain, and acquire reports OUT_OF_DATE until a rebuild works.
  4. New handles. RenderContext::recreateSwapchain registers the new images under new texture handles.
  5. Screen-sized resources. Renderer::createSwapchainResources rebuilds the render targets sized from the swapchain (RenderContext::resizeRenderTargets), which keep their bindless slots, and sets the camera aspect ratio from the swapchain's extent.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Present modea choice: FIFO, MAILBOX, IMMEDIATEAlways VK_PRESENT_MODE_FIFO_KHR, so the frame rate is capped at the refresh rate. Other modes crashed vkDestroyDevice on NVIDIA (B21). There is no vsync option.
Image count2 to 4vk-bootstrap's default; RASM does not ask for a count.
FormatsRGB or HDRAsks for VK_FORMAT_B8G8R8A8_SRGB with VK_COLOR_SPACE_SRGB_NONLINEAR_KHR. No HDR.
Acquire semaphoresone per frame in flight, freed by the frame fenceOne per frame in flight, but the swapchain tracks their reuse with its own releaseTimeline, so it does not rely on the engine's frame fence.
Present semaphoresone per imageThe same (presentSemaphores), kept across resizes.
Wait stagecolor outputColor attachment output. The barrier that moves the image out of UNKNOWN waits at the same stage, so the layout change comes after the acquire.
Layoutdiscard at acquire, "present" before presentRenderContext::acquireNextImage sets the image's state to UNKNOWN; beginPass moves it to COLOR_ATTACHMENT, discarding; endFrame moves it to PRESENT_SRC.
Every acquired image is presentedyesYes. A frame that only drew into render targets gets a "Clear" pass in endFrame. A failed submit keeps the image acquired for the next frame.
Suboptimalfinish the frame, rebuildThe same, through the window's WindowFrame::outOfDate.
Minimized windowskip frames, sleepThe same: beginFrame skips, and with SDL pollEvents waits up to 100 ms for an event while minimized. A NATIVE application reports a size of 0 with setWindowSize and sleeps in its own loop.
Rebuildwait idle, old swapchain, release signalsAll three.
Present queueany queue that can presentThe graphics queue. Compute queue submits never wait for the image or present it.
Submits per frameoneOne, or a few with EngineConfig::asyncCompute: the first graphics submit waits for the image, the last one presents.

Where it lives in code

WhatWhere
Building, acquire, present, resizeVulkanSwapchain in src/rhi/vulkan/vulkanSwapchain.cpp
The image wait, the present signalsgetAcquireWait, onAcquireWaited, getPresentSignals, onSubmitted; used by VulkanQueue::submit in src/rhi/vulkan/vulkanQueue.cpp
Result codesSwapchainStatus in include/rasm/types.h
Image handles, layout at acquireRenderContext::acquireNextImage, recreateSwapchain in src/rhi/renderContext.cpp
Skips, resize, presentRenderer::beginFrame, endFrame, submitBatches, recreateSwapchain, createSwapchainResources in src/renderer/renderer.cpp
Resize and minimize eventspollEvents in src/platform/sdlPlatform.cpp src/platform/platform.h
Keep these true
  • Swapchain calls handle VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR explicitly, and return a SwapchainStatus the engine acts on.
  • No semaphore crosses the RHI. The acquire → submit → present order lives inside VulkanSwapchain.
  • Everything sized like the screen comes from the swapchain's extent in pixels, not from the window's logical size.
  • Swapchain images belong to the swapchain: RenderContext::destroyTexture refuses them.

Further reading