Culling and the frame

Immediate-mode UI

Debug windows, sliders and tool panels are code that runs every frame. An immediate-mode UI library, like Dear ImGui, turns that code into a few buffers of triangles, and the engine draws them over its image. This page explains how the UI becomes triangles, how they are drawn, and what input and color need. The last part shows how RASM does it.

In short

  • In an immediate-mode UI, the program calls Button("Save") every frame. The call draws the button and returns true on the frame it is clicked. There are no widget objects to keep in sync.
  • Each window appends triangles to a draw list: a vertex buffer (position, UV, color), an index buffer, and draw commands.
  • A draw command is a range of indices with a clip rectangle and a texture. The renderer draws each range with the rectangle as its scissor.
  • One atlas texture holds the font and a white pixel, so most of the UI is a few draws.
  • The UI reads input first and says whether it wants the mouse or the keyboard, so a click on a window does not also turn the camera.
  • UI colors are sRGB numbers and are meant to be blended as numbers. Blending them in linear light makes light text on a dark window look bolder.

1Two ways to build a UI

A retained-mode UI keeps a tree of widget objects. The program creates them once, keeps them up to date, and reacts to their events. An immediate-mode UI keeps no widgets for the program: the program describes the UI again in every frame, and the library draws it at once.

Window Slider Button app's value two copies, synced by events

Retained mode

Widgets live between frames. The program creates them, updates them and handles their events.

Begin("Light"); SliderFloat("Power", &power, 0, 10); if (Button("Reset")) power = 1; End(); power one copy: the program's

Immediate mode

The program's code is the UI. It runs every frame and works on the program's own values.

The library still keeps a little state inside, keyed by each widget's label: which window is open, where it is, which slider is being dragged. The program does not see it. Immediate mode is the usual choice for engine tools and debug windows, because a new value on screen is one line of code.

2One UI frame

The UI is rebuilt between reading the input and drawing the frame:

  1. Input. Mouse, keys and text go to the library.
  2. New frame. It takes the display size and the time step.
  3. Build. Each widget checks the input and adds its triangles.
  4. Render. The draw data: every window's draw list.
  5. Draw. Copied to GPU buffers, drawn last in the frame.

A click is handled in the same frame it arrives: the button sees the press in step 3 and returns true. The program changes its values right there, before the frame is drawn.

3From widgets to triangles

Everything a UI shows is made of triangles: a window is a rectangle, a button is a rectangle with text, a letter is a small rectangle cut out of the font texture. A rectangle is 4 vertices and 6 indices.

A button: rectangles background: 4 vertices, 6 indices S a v e each letter: one more rectangle, its UVs point into the font texture 5 rectangles = 20 vertices, 30 indices One vertex: 20 bytes positionfloat x, y UVfloat u, v colorRGBA8 081620 Positions are in display points, from the top-left corner. A flat color uses the UV of a white texel; text uses the glyph's UVs. The shader multiplies the vertex color by the texel. Indices are 16 bits, so one draw reaches at most 65,536 vertices; a bigger list starts a new draw with a vertex offset.
Each widget appends its rectangles to the window's draw list. Rounded corners and lines are more triangles of the same kind.

4Draw commands and clip rectangles

A draw list is one vertex buffer, one index buffer, and a list of draw commands. A command says: draw these indices, with this texture, only inside this rectangle. A new command starts when the texture or the clip rectangle changes, for example when a scrolling child area begins.

A window with a scrolling list Window row 3row 4row 5row 6 row 7: outside, not drawn image orange: the list's clip rectangle Its draw commands frame list rows image the index buffer, split into ranges commandindicestextureclip rectangle 10..71atlasthe window 272..173atlasthe list area 3174..179photothe window The renderer draws each range with its clip rectangle as the scissor: row 7 is in the index buffer, but no pixel of it is drawn.
Clipping costs nothing per pixel: the GPU's scissor test drops the fragments outside the rectangle before they are shaded.

The clip rectangle is in display points. On a high-DPI screen a point is several pixels, so the renderer scales it by the framebuffer scale, rounds it outward to whole pixels (a pixel that is partly inside stays), and clamps it to the framebuffer. A rectangle with nothing left is not drawn at all.

x₀ = floor(max((clip.left − display.x) · s, 0))

x₁ = ceil(min((clip.right − display.x) · s, width))

s
the framebuffer scale: pixels per point (1 on a normal screen, 2 on most high-DPI laptops)
display.x
where the UI's display starts, usually 0
x₀, x₁
the scissor's left and right edge in pixels; y works the same way with the top and bottom
Drag the two corners of the clip rectangle, and change the framebuffer scale. The scissor (solid) covers every pixel the rectangle touches. Drag a corner out of the display, or make the rectangle empty.

5One texture for nearly everything

Switching textures needs a new draw command, so the library puts all its images into one atlas: every glyph of the font at the sizes in use, the mouse cursors, and one white texel. A flat rectangle samples the white texel, so its color is just the vertex color. Text samples its glyph. Then a whole window is usually one command.

ABCDEFGHIJ KLMNOPQRST abcdefg123 glyphs, and a white texel

The atlas

Packed by the library. It grows when text needs a new size, and the renderer uploads it again.

A alpha = how much the pixel is covered

Glyphs as coverage

A glyph's texels are white, and the alpha says how much of each one the letter covers. Edges are partly covered: that is the anti-aliasing.

its own texture, its own command

Images

A widget can show any texture of the program. The library only passes its texture ID through; what the ID means is up to the renderer.

6Colors are sRGB numbers

The UI's colors are the numbers the designer picked on screen: sRGB numbers (see Color spaces). Its anti-aliasing mixes them by coverage, and the look was tuned for mixing the numbers themselves. Mixed in linear light instead, an edge pixel comes out brighter. So light text on a dark window looks bolder and softer.

text 1.0 edge 0.74 window 0.10 decode, mix, encode: the bar is how bright

Mixed in linear light

The edge is almost white. The strokes look thicker than designed.

text 1.0 edge 0.55 window 0.10 mix the numbers: the bar is how bright

Mixed as numbers

The edge is half way, as the font and the style were designed.

0.55white over 0.10 at half coverage, mixed as numbers0.5 · 1 + 0.5 · 0.10; byte 140
0.74the same mixed in linear lightencode(0.5 · 1 + 0.5 · 0.010); byte 188
+48bytes brighter on every half-covered edge pixelabout a third of the way to white

The scene, on the other hand, must blend in linear light. So a renderer that draws the UI into an sRGB target has two ways out. The clean one: draw the UI through a second, UNORM view of the same image, where the hardware stores and blends the numbers as they are; the swapchain must allow a mutable format for that. The fallback: decode the UI's colors in the shader, and accept the bolder look.

A row of pixels across a glyph edge, from fully covered to empty. Change the coverage of the middle pixel and the colors, and compare the two rows.

7Who gets the input

The UI and the program share one mouse and one keyboard. After each frame the library says what it wants: the mouse (the pointer is over a window, or drags one), the keyboard (a window has the focus), or text (a text field takes typing). The program then keeps that input away from the rest:

camerastays wants the mouse

Mouse

Presses and the wheel over a window go to the UI only.

W A S D camerastays wants the keyboard

Keyboard

Keys for the camera are ignored while a window has the focus.

name: cube_ wants text

Text

Even Escape and the function keys belong to the text field.

The flags come from the last built frame, so they are one frame old. That is fine for input: a pointer that just entered a window is caught on the next event.

8Pitfalls

Light text looks bold and soft
The UI is blended in linear light. Draw it through a UNORM view of the target, so its colors blend as numbers.
Dragging a slider also turns the camera
The program ignores the library's capture flags. Check them before the camera takes the mouse.
The UI flickers or shows garbage after the font grows
The atlas was changed in place while the GPU still drew the last frame with it. Upload a new texture, and free the old one only when no frame in flight uses it.
Large lists draw wrong vertices
The renderer ignores a command's vertex offset, which the library uses to pass 65,536 vertices with 16-bit indices. On APIs where the vertex index does not include the base vertex, pass the offset to the shader yourself.
The UI is tiny on a 4K laptop
Sizes and fonts are in points, but were not scaled by the display's scale. Scale the style and the font by it.
Scene colors look washed out in an image widget
The texture is sampled as linear light but drawn as numbers, or the other way round. Convert by the texture's format, so the image shows its stored colors.

9In RASM

RASM uses Dear ImGui for the UI part, and draws its draw data with a small renderer of its own, through the RHI and the render graph. Its input is RASM's own InputEvents, from the SDL platform or from the application (The platform layer), so no ImGui platform backend runs. Turn it on with EngineConfig::ui; F1 shows the RASM window, and Renderer::setUiCallback adds the application's windows. The API: UI with Dear ImGui.

beginFrame (CPU) uiPlatformInputEvents → ImGui buildUiRASM window, your callback UI Vertices / Indicesper frame slot, grow ×2 UiDraw listaddress, range, slot, scissor UI pass (GPU), after the tone map per drawsetScissor · push 16 B · drawIndexed ui.slangvertices[SV_VertexID] via the address swapchain, UNORM viewblends the sRGB numbers Push constants: vertices (8 B, the draw's first vertex) · texture (4 B, bindless slot, bit 31 = sRGB) · displaySize (4 B, points) No vertex input, no depth, premultiplied alpha. Without the UNORM view the shader decodes the colors instead (D31).
The renderer uses only RHI calls (buffers, a pipeline, scissors, push constants, indexed draws), so it works on every backend the RHI gets, unlike ImGui's own Vulkan backend.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Libraryan immediate-mode UIDear ImGui from vcpkg (the imgui port, no backends, with IMGUI_DISABLE_OBSOLETE_FUNCTIONS on through the overlay ports/imgui), behind the CMake option RASM_IMGUI. One context, owned by the engine (Renderer::getUiContext); the application's ImGui:: calls use it. At start-up createUi checks that the linked library lays the context out as RASM's headers do, and keeps the UI off with an error naming the size that differs.
Other languages—A C program or a binding draws with its own Dear ImGui (cimgui, ImGui.NET, imgui-rs) into RASM's context: rasm_check_imgui_layout, then RASM's allocator and context, then ImGui calls in the rasm_set_ui_callback callback. RASM ships no ImGui wrapper. See Two copies of one library and the C API.
Inputevents to the library, capture flagsprocessUiEvent in src/platform/uiPlatform.cpp turns each InputEvent into ImGui's AddKeyEvent (with the modifiers first), AddMousePosEvent, AddMouseButtonEvent, AddMouseWheelEvent, AddInputCharacter and AddFocusEvent. Cursor shapes, the clipboard and starting text input go to the Platform (updateUiPlatform); the SDL platform does them, a NATIVE or headless one leaves them to the application. newUiPlatformFrame sets the display to the window's size in points and the framebuffer scale to its pixels per point. With or without a window, ImGui's time step is the engine's deltaTime, so EngineConfig::fixedDeltaTime steps it too. Renderer::pollEvents keeps the mouse, the W/A/S/D keys and, while typing, Escape and F1–F3 from the camera and the engine.
When it is builtbetween input and drawingIn beginFrame, after the slot's fence wait and before syncGpuScene, so the callback's changes show in the same frame. Only while the RASM window is shown or a callback is set; otherwise nothing runs.
Buffersvertex and index buffersHost-visible UI Vertices and UI Indices per frame slot, written with fillBuffer. They grow to the next power of two and are never made per frame.
Verticesa vertex layoutNo vertex input: vertex pulling through a device address. The address points at the draw's first vertex, so the base vertex works on D3D12 too.
Clipclip rectangle → scissorgetUiScissor, the rule of the formula above, with io.DisplayFramebufferScale.
Texturesan atlas, IDs for imagesImGui's texture requests (ImGuiBackendFlags_RendererHasTextures): a new texture for each request, in a bindless slot; the old one is freed once the graphics fence passes the last frame submitted with it. An ImTextureID is the slot + 1, with a bit for sRGB textures (Renderer::getUiTexture). A view texture (a camera's picture, Many views of one scene) is shown the same way, and its handle and slot stay when it is resized.
Blendingas numbers, through a UNORM viewThe swapchain's B8G8R8A8_UNORM view (VK_KHR_swapchain_mutable_format) when the device has it; headless, the offscreen images' R8G8B8A8_UNORM view (TextureDesc::encodedView); else colors decoded in the shader (D31).
Where it drawslast in the frameThe UI pass of Renderer::addUiPass, after the tone map. It reads the view textures it is given (shown), so it runs after their tone maps and shows this frame's picture; Renderer::render gives it every view texture of its list. A graph without it gets one from endFrame, at the cost of one more load and store of the image.
Images of the frameany texture, by its IDThe RASM window's Buffers section shows a render target, depth, Hi-Z level or light clusters of the running frame: an Inspect pass copies it into a storage target that the UI pass declares as a read, so the graph moves it to SAMPLED. The GPU tables section lists the GPU scene tables and an entity's rows. See Inspecting GPU resources.
Scalestyle and font by the display scaleWindow::contentScale: the SDL platform reads it from the display and again when the window moves to another one; a NATIVE application sets it (NativeWindow::contentScale, setWindowContentScale). A new scale scales the current style by the ratio of the new scale to the old (setUiScale), so the application's colors and sizes stay.
0cost with EngineConfig::ui off: no context, no pass, no zoneswith RASM_IMGUI=OFF not even linked
16 Bpush constants per drawaddress 8 + texture 4 + display size 4
20 Bper vertex, copied as ImGui writes itImDrawVert
0.12 msGPU: the UI pass of 15_debug_uitwo windows and an image, 1280 × 720, RTX 3060
0.17 msCPU: the UI zone, ImGui's frame and the copiesthe same frame, Release
0 msboth, with EngineConfig::ui offno UI zone, no UI pass

Where it lives in code

WhatWhere
Setup, frame, drawscreateUi, buildUi, drawUi, drawUiFallback, addUiPass in src/renderer/ui.cpp
Layout check, CgetUiLayout, findUiLayoutMismatch in src/renderer/ui.cpp; the C calls in src/c/cUi.cpp
StateUi, UiDraw in src/renderer/ui.h
RASM windowdrawEngineWindow in src/renderer/engineUi.cpp: the stats, the forced LOD, the debug views and Freeze culling, the graph dump
Input, scalesrc/platform/uiPlatform.cpp, used by Renderer::pollEvents
Shadershaders/passes/ui.slang, gfx::UiPushConstants
UNORM viewVulkanSwapchain::getEncodedFormat, OffscreenSwapchain::getEncodedFormat, AttachmentOps::encodedColor
Exampleexamples/15_debug_ui/main.cpp; from C through cimgui, examples/33_c_render_graph/main.c (RASM_C_IMGUI_EXAMPLE)
Keep these true
  • gfx::UiPushConstants and UiPushConstants in ui.slang change together and stay 16 bytes; UiVertex matches ImDrawVert (a static_assert checks the C++ side).
  • A UI texture is never changed in place: a change makes a new texture, and the old one is freed only when the fence says no submitted frame draws with it.
  • ImGui gets its input only from InputEvents, through processUiEvent; no ImGui platform backend runs, so every platform and the application feed it the same way.
  • With the UI off, nothing of it may run: no context, no pass, no buffers.
  • RASM's Dear ImGui keeps the layout of cimgui's headers: the same version, IMGUI_DISABLE_OBSOLETE_FUNCTIONS on, 16-bit indices. A layout mismatch is an error message, never an assert.

Further reading