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.
Retained mode
Widgets live between frames. The program creates them, updates them and handles their events.
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:
- Input. Mouse, keys and text go to the library.
- New frame. It takes the display size and the time step.
- Build. Each widget checks the input and adds its triangles.
- Render. The draw data: every window's draw list.
- 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.
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.
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
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.
The atlas
Packed by the library. It grows when text needs a new size, and the renderer uploads it again.
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.
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.
Mixed in linear light
The edge is almost white. The strokes look thicker than designed.
Mixed as numbers
The edge is half way, as the font and the style were designed.
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.
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:
Mouse
Presses and the wheel over a window go to the UI only.
Keyboard
Keys for the camera are ignored while a window has the focus.
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.
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Library | an immediate-mode UI | Dear 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. |
| Input | events to the library, capture flags | processUiEvent 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 built | between input and drawing | In 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. |
| Buffers | vertex and index buffers | Host-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. |
| Vertices | a vertex layout | No 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. |
| Clip | clip rectangle → scissor | getUiScissor, the rule of the formula above, with io.DisplayFramebufferScale. |
| Textures | an atlas, IDs for images | ImGui'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. |
| Blending | as numbers, through a UNORM view | The 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 draws | last in the frame | The 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 frame | any texture, by its ID | The 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. |
| Scale | style and font by the display scale | Window::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. |
EngineConfig::ui off: no context, no pass, no zoneswith RASM_IMGUI=OFF not even linkedImDrawVertUI pass of 15_debug_uitwo windows and an image, 1280 × 720, RTX 3060UI zone, ImGui's frame and the copiesthe same frame, ReleaseEngineConfig::ui offno UI zone, no UI passWhere it lives in code
| What | Where |
|---|---|
| Setup, frame, draws | createUi, buildUi, drawUi, drawUiFallback, addUiPass in src/renderer/ui.cpp |
| Layout check, C | getUiLayout, findUiLayoutMismatch in src/renderer/ui.cpp; the C calls in src/c/cUi.cpp |
| State | Ui, UiDraw in src/renderer/ui.h |
| RASM window | drawEngineWindow in src/renderer/engineUi.cpp: the stats, the forced LOD, the debug views and Freeze culling, the graph dump |
| Input, scale | src/platform/uiPlatform.cpp, used by Renderer::pollEvents |
| Shader | shaders/passes/ui.slang, gfx::UiPushConstants |
| UNORM view | VulkanSwapchain::getEncodedFormat, OffscreenSwapchain::getEncodedFormat, AttachmentOps::encodedColor |
| Example | examples/15_debug_ui/main.cpp; from C through cimgui, examples/33_c_render_graph/main.c (RASM_C_IMGUI_EXAMPLE) |
gfx::UiPushConstantsandUiPushConstantsinui.slangchange together and stay 16 bytes;UiVertexmatchesImDrawVert(astatic_assertchecks 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, throughprocessUiEvent; 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
- Omar Cornut, Dear ImGui, its docs/BACKENDS.md and docs/FAQ.md.
- Casey Muratori, Immediate-Mode Graphical User Interfaces (2005), the talk that named the idea.
- Color spaces, Text from a bitmap font, Vertex pulling, Bindless resources.