ImGui.NET Documentation

repository·master·Indexed 25 days ago

https://github.com/imguinet/imgui.net

A .NET Standard wrapper for the Dear ImGui immediate-mode GUI library, built on top of cimgui. It enables the creation of graphical user interfaces for games, 3D applications, and developer tools. The library is renderer agnostic and supports integration with Veldrid, MonoGame, and OpenTK. It provides both a raw wrapper mapping to the native API and a managed API for convenience.

Tokens
2.1K
Snippets
2
Records
10
Agent score
80%

What's inside ImGui.NET

  1. Overview of ImGui.NET

    master

    ImGui.NET is a .NET Standard wrapper for the Dear ImGui immediate mode GUI library. It allows you to build graphical interfaces using an immediate-mode style, which is highly suitable for game engine tooling, real-time 3D applications, and debug tools.

    Key characteristics:

    • Renderer Agnostic: ImGui.NET outputs textured triangles; it does not dictate your rendering technology. Common implementations use Veldrid, MonoGame, or OpenTK (OpenGL).
    • Architecture: It is built on top of cimgui, which provides a C API for Dear ImGui.
    • Platform Support: Works on all major .NET runtimes and operating systems. For Windows, OSX, and mainline Linux, the NuGet package includes pre-built native libraries.
  2. How to use ImGui.NET APIs

    master

    ImGui.NET provides two layers of API:

    1. Raw Wrapper: A direct mapping to the ImGui native API.
    2. Managed API: A thin, safe, managed wrapper for convenience.

    Because the API closely mirrors the native library, the best way to learn the functions and usage patterns is to consult the original Dear ImGui documentation (specifically imgui.cpp and imgui.h) or the cimgui.h exported functions. You can also refer to the sample program code in the repository for basic usage patterns.

  3. Setup ImGui.NET with FNA

    master

    To use the ImGui.NET renderer with FNA, follow these steps to migrate from the default MonoGame configuration:

    1. Remove NuGet Packages: Remove the MonoGame.Framework.DesktopGL NuGet package.
    2. Add FNA Reference: Download FNA from https://github.com/FNA-XNA/FNA/releases and add a reference to it in your project.
    3. Add Native Dependencies: Download the native FNA dependencies from the FNA Wiki and copy them to your project's output directory.
    4. Update Code: Search for the comment // FNA-specific in the source code and replace the MonoGame-specific implementation blocks with the provided FNA counterparts.
  4. Initialize ImGui.NET with Veldrid and ImGuiController

    master

    To use ImGui.NET in a graphics application, you must set up a windowing system (like SDL2 via Veldrid), a graphics device, and an ImGuiController. The ImGuiController acts as the bridge between your engine's input/rendering and the ImGui state.

    Key lifecycle steps:

    1. Setup: Create the window and graphics device using VeldridStartup.CreateWindowAndGraphicsDevice.
    2. Controller Initialization: Instantiate ImGuiController with the graphics device, framebuffer description, and window dimensions.
    3. Input Handling: In your main loop, call _controller.Update(deltaTime, snapshot) where snapshot is the input state from your window.
    4. Rendering: Call _controller.Render(gd, commandList) within your command list recording to draw the UI.
    5. Cleanup: Dispose of the controller and graphics resources when the application exits.
    // 1. Setup
    VeldridStartup.CreateWindowAndGraphicsDevice(
        new WindowCreateInfo(50, 50, 1280, 720, WindowState.Normal, "ImGui.NET Sample Program"),
        new GraphicsDeviceOptions(true, null, true, ResourceBindingModel.Improved, true, true),
        out _window, 
        out _gd);
    
    // 2. Controller Initialization
    _controller = new ImGuiController(_gd, _gd.MainSwapchain.Framebuffer.OutputDescription, _window.Width, _window.Height);
    
    // 3. Main Loop
    while (_window.Exists)
    {
        InputSnapshot snapshot = _window.PumpEvents();
        _controller.Update(deltaTime, snapshot);
    
        _cl.Begin();
        _cl.SetFramebuffer(_gd.MainSwapchain.Framebuffer);
        _controller.Render(_gd, _cl);
        _cl.End();
        _gd.SubmitCommands(_cl);
        _gd.SwapBuffers(_gd.MainSwapchain);
    }
    
    // 4. Cleanup
    _controller.Dispose();
    _gd.Dispose();
  5. Create windows and widgets in ImGui.NET

    master

    ImGui uses an immediate mode paradigm. You define your UI every frame inside your main loop.

    • Windows: Use ImGui.Begin("Title", ref isOpen) to start a window and ImGui.End() to finish it. If isOpen is passed as a reference, ImGui will set it to false when the user clicks the close button.
    • Implicit Windows: If you call widgets (like ImGui.Text) without calling ImGui.Begin(), they will appear in a default window named "Debug".
    • Common Widgets:
      • ImGui.Text("string"): Displays text.
      • ImGui.Checkbox("label", ref bool): A toggle switch.
      • ImGui.Button("label"): Returns true when clicked.
      • ImGui.SliderFloat("label", ref float, min, max): A draggable slider for floats.
      • ImGui.DragInt("label", ref int): A draggable control for integers.
    • Layout: Use ImGui.SameLine() to place the next widget on the same line as the previous one.
    // Explicit window
    if (_showAnotherWindow)
    {
        ImGui.Begin("Another Window", ref _showAnotherWindow);
        ImGui.Text("Hello from another window!");
        if (ImGui.Button("Close Me"))
            _showAnotherWindow = false;
        ImGui.End();
    }
    
    // Simple widgets in the default window
    ImGui.Text("Hello, world!");
    ImGui.SliderFloat("float", ref _f, 0, 1);
    if (ImGui.Button("Button"))
        _counter++;
  6. Use Tab Bars and Tree Nodes for complex layouts

    master

    For organized UIs, use hierarchical structures like Tree Nodes and Tab Bars.

    • Tree Nodes: ImGui.TreeNode("label") creates a collapsible section. It returns true if the node is expanded. Always pair with ImGui.TreePop() if the node is open.
    • Tab Bars:
      • Use ImGui.BeginTabBar("ID", flags) to start a bar.
      • Use ImGui.BeginTabItem("Label", ref isOpen) to create individual tabs.
      • Use ImGui.EndTabItem() and ImGui.EndTabBar() to close them.
      • Passing a ref bool to BeginTabItem allows the tab to be closed programmatically or by the user.
  7. Debug native code in ImGui.NET

    master

    By default, the native code in ImGui.NET is released in an optimized form, which prevents effective debugging. To debug the native layer, you must build a debug version of the native binaries manually:

    1. Clone the ImGui.NET-nativebuild repository, ensuring you use the tag that matches your current ImGui.NET version.
    2. Build the debug binaries using the provided script:
      • Windows: build.cmd debug
      • Linux/macOS: build.sh debug
    3. Copy the resulting binaries (cimgui.dll, libcimgui.so, or libcimgui.dylib) into your application's output directory.
    4. Run your application using a native debugger or enable mixed-mode debugging in Visual Studio.
  8. Optimize string usage with ReadOnlySpan<char>

    master

    On .NET Standard 2.1 or greater, ImGui.NET supports ReadOnlySpan<char> for many text-related functions. Using spans can help reduce heap allocations compared to passing standard string objects, especially in high-frequency UI updates.

    Note: While passing a span avoids the string allocation itself, using string interpolation (e.g., `$