Tools with Dear ImGui
Every engine grows tools: a stats overlay, an entity inspector, sliders for tuning, a console, a profiler view, a level editor. Dear ImGui (Omar Cornut, MIT) is how most of the industry builds the in-engine part of those tools. It is an immediate-mode GUI: there are no widget objects to create, store and destroy. Each frame your code simply calls ImGui::SliderFloat("speed", &speed, 0, 10), and the call both draws the slider and returns whether the user changed the value.
Immediate mode, modelled
How can a function call with no stored widget object know that the mouse button went down on this slider two frames ago? The library keeps a tiny amount of state keyed by a widget ID, a hash of the label (plus an ID stack for repeated labels). It tracks which ID is hot (under the mouse) and which is active (being clicked or dragged). Everything else is rebuilt each frame from your code.
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct Input { int mouseY; bool down; };
class Ui {
Input in{}, prev{};
std::uint32_t active = 0; // the only state that survives between frames
std::vector<std::uint32_t> idStack{2166136261u};
int cursorY = 0;
std::uint32_t hashId(const std::string& label) const {
std::uint32_t h = idStack.back();
for (char c : label) { h ^= std::uint8_t(c); h *= 16777619u; }
return h;
}
bool hovered() const { return in.mouseY >= cursorY && in.mouseY < cursorY + 20; }
public:
std::vector<std::string> drawList;
void newFrame(Input input) { prev = in; in = input; cursorY = 0; drawList.clear(); }
void endFrame() { if (!in.down) active = 0; } // button released: nothing is active any more
void pushId(int i) { idStack.push_back(idStack.back() * 31u + std::uint32_t(i)); }
void popId() { idStack.pop_back(); }
bool button(const std::string& label) {
std::uint32_t id = hashId(label);
bool pressedNow = in.down && !prev.down && hovered();
if (pressedNow) active = id;
bool clicked = active == id && !in.down && prev.down && hovered(); // released over the button
drawList.push_back("[" + label + "]");
cursorY += 20;
return clicked;
}
bool sliderInt(const std::string& label, int& v, int lo, int hi) {
std::uint32_t id = hashId(label);
if (in.down && !prev.down && hovered()) active = id;
bool changed = false;
if (active == id && in.down) { // dragging: map mouse to value
int nv = lo + (in.mouseY - cursorY) * (hi - lo) / 19;
nv = nv < lo ? lo : nv > hi ? hi : nv;
changed = nv != v;
v = nv;
}
drawList.push_back(label + " = " + std::to_string(v));
cursorY += 20;
return changed;
}
};
int main() {
Ui ui;
int speed = 5;
std::vector<int> spawned;
// scripted mouse input: y position and button state per frame
std::vector<Input> frames = {{5, false}, {5, true}, {5, false}, {25, true}, {39, true}, {39, false}, {65, true}, {65, false}};
for (int f = 0; f < int(frames.size()); f++) {
ui.newFrame(frames[f]);
// ---- this is the whole "UI declaration", re-run every frame ----
if (ui.button("Spawn")) spawned.push_back(speed);
if (ui.sliderInt("speed", speed, 0, 10)) std::cout << " frame " << f << ": speed changed to " << speed << "\n";
for (int i = 0; i < 2; i++) { // two buttons with the same label need different IDs
ui.pushId(i);
if (ui.button("Delete")) std::cout << " frame " << f << ": Delete clicked on row " << i << "\n";
ui.popId();
}
// -----------------------------------------------------------------
ui.endFrame();
std::cout << "frame " << f << ":";
for (auto& d : ui.drawList) std::cout << " " << d;
std::cout << "\n";
}
std::cout << "spawned " << spawned.size() << " enemy, with speed " << (spawned.empty() ? -1 : spawned[0]) << "\n";
}frame 0: [Spawn] speed = 5 [Delete] [Delete]
frame 1: [Spawn] speed = 5 [Delete] [Delete]
frame 2: [Spawn] speed = 5 [Delete] [Delete]
frame 3: speed changed to 2
frame 3: [Spawn] speed = 2 [Delete] [Delete]
frame 4: speed changed to 10
frame 4: [Spawn] speed = 10 [Delete] [Delete]
frame 5: [Spawn] speed = 10 [Delete] [Delete]
frame 6: [Spawn] speed = 10 [Delete] [Delete]
frame 7: Delete clicked on row 1
frame 7: [Spawn] speed = 10 [Delete] [Delete]
spawned 1 enemy, with speed 5
The button reports a click only on the frame the mouse is released over it, after being pressed on it. The slider changes while dragged, and the two Delete buttons are told apart by pushId, the same reason Dear ImGui has ImGui::PushID. Without it, two widgets with the same label share an ID and fight over input, which is the most common Dear ImGui bug.
Dear ImGui in an SDL3 + OpenGL engine
Dear ImGui is a set of source files you compile into your engine, plus backends: a platform backend (input, clipboard, cursors) and a renderer backend (draws the triangle lists Dear ImGui produces). With vcpkg, the imgui port has features such as sdl3-binding, opengl3-binding, vulkan-binding and docking-experimental; link imgui::imgui. The calls below follow the official example_sdl3_opengl3:
#include "imgui.h"
#include "imgui_impl_sdl3.h"
#include "imgui_impl_opengl3.h"
// once, after creating the window and GL context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
ImGui::StyleColorsDark();
ImGui_ImplSDL3_InitForOpenGL(window, glContext);
ImGui_ImplOpenGL3_Init("#version 330");
// in the event loop
SDL_Event e;
while (SDL_PollEvent(&e)) {
ImGui_ImplSDL3_ProcessEvent(&e);
if (io.WantCaptureMouse && isMouseEvent(e)) continue; // the UI has the mouse: don't shoot
if (io.WantCaptureKeyboard && isKeyEvent(e)) continue; // typing in a text box: don't move
input.handle(e);
}
// each frame, after rendering the scene
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL3_NewFrame();
ImGui::NewFrame();
ImGui::Begin("Debug");
ImGui::Text("%.2f ms/frame (%.0f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::SliderFloat("player speed", &tuning.playerSpeed, 0.0f, 20.0f);
ImGui::Checkbox("draw colliders", &debug.drawColliders);
if (ImGui::Button("Respawn")) game.respawnPlayer();
if (ImGui::CollapsingHeader("Entities")) {
for (Entity e : world.entities()) {
ImGui::PushID(int(e.index));
if (ImGui::TreeNode("entity", "Entity %u", e.index)) {
auto& t = world.get<Transform>(e);
ImGui::DragFloat3("position", &t.position.x, 0.1f);
ImGui::TreePop();
}
ImGui::PopID();
}
}
ImGui::End();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(window);
// shutdown
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL3_Shutdown();
ImGui::DestroyContext();Making it useful
- Compile it out of shipping builds with a define (
#if ENGINE_TOOLS) or keep only a minimal overlay. Debug UI that reaches players tends to become a support problem. ImGui::ShowDemoWindow()is the documentation. Searchimgui_demo.cppfor any widget you see there to get its code.- Reflection pays off. Once components describe their fields (a small reflection table or macros), one generic inspector function draws every component; you stop writing a panel per type.
- Docking and viewports (the
dockingbranch,docking-experimentalin vcpkg) turn ImGui windows into a dockable editor layout and even separate OS windows. - Extensions: ImPlot (charts), ImGuizmo (3D transform gizmos), imnodes / imgui-node-editor (node graphs), and Tracy's own profiler UI is built with Dear ImGui.
Note: Dear ImGui is aimed at programmer and developer tools. For the game's player-facing UI (menus, HUD with animation, localisation, gamepad navigation, accessibility), use a retained-mode UI system or middleware such as RmlUi, Noesis or your engine's own UI.
Keeping these tools separate from the shipped runtime is one of the architecture field notes.
Test yourself
What does 'immediate mode' mean for Dear ImGui?
- Widgets draw directly to the screen without the GPU
- Your code re-declares the UI every frame with function calls; there are no persistent widget objects
- The UI never keeps any state
- It only works in debug builds
Two buttons in a loop are both labelled "Delete" and clicking one seems to affect the other. What fixes it?
- Use
ImGui::Separator() - Push a unique ID per row with
ImGui::PushID(i)(or use labels like "Delete##3") - Call
ImGui::Render()twice - Disable keyboard navigation
Why check io.WantCaptureMouse before passing a click to gameplay?
- To save CPU
- So clicking a debug window doesn't also fire the player's weapon
- ImGui requires it to render
- It enables docking