From 332bf51ee9ba61a68f2c66124bf5342fb490104c Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Fri, 24 Apr 2020 18:16:48 +0200 Subject: [PATCH 001/245] Shadows: Added experimental texture-based shadows (stripped of dynamic tex config and back-end code) (merged 10 commits, removing dynamic tex config, moved tex config to internal structs, removed back-end changes) (squashed 2025-06-11, fixed conflict, doesn't build as-is) Shadows: Added IMGUI_HAS_SHADOWS Shadows: Demo code in Custom Rendering section. Added AddShadowRectFilled() variant. BeginMainMenuBar() disable shadows. Shadows: Added initial version of convex shape shadow code. (+stripped out of original polygon generation demo, moved to imgui_dev) Shadows: Tweak demo to use AddShadowCircle() functions + fix warnings. (+ stripped old polygon generation code from commits) Shadows: Convex shape shadow improvement/fixes - Fixed pixel cracking on convex shadow edges - Added convex shadow offset support - Fixed some convex shadow fringing issues - Added convex shadow demo code Shadows: Added ImDrawShadowFlags, simplified API surface, reordered parameters + fix minor warnings + removed NGon variant for now. Shadows: Re-added AddShadowNGon(). Shadows: Shallow styling tweaks and renaming for consistency. Shadows: Fixes + two fixes for PVS Studio static analyzer. Shadows: Fix for latest, reuse ImDrawList, remove ImDrawShadowFlags. Shadows: Fix to support for colored-only font atlas. (4202) Shadows: Fix broken shadows due to zero-clear added in 9417acc2. Shadows: remove use of GetWindowContentRegionMax(). Shadows: WIP fixes for latest. (broken UV caching) Shadows: WIP for latest (refreshing UV coordinates). Demo: Add missing trailing null terminator to convex shape combo (9434) --- imgui.cpp | 26 ++ imgui.h | 47 +++ imgui_demo.cpp | 178 ++++++++ imgui_draw.cpp | 1010 +++++++++++++++++++++++++++++++++++++++++++++ imgui_internal.h | 5 + imgui_widgets.cpp | 4 + 6 files changed, 1270 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 9e5880ebd..64bbe4fb3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1445,6 +1445,7 @@ static void UpdateTexturesNewFrame(); static void UpdateTexturesEndFrame(); static void UpdateSettings(); static int UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); +static void RenderWindowShadow(ImGuiWindow* window); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); @@ -1578,6 +1579,9 @@ ImGuiStyle::ImGuiStyle() AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationMaxError = 1.12f; // Maximum error (in pixels) when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + WindowShadowSize = 100.0f; // Size (in pixels) of window shadows. + WindowShadowOffsetDist = 0.0f; // Offset distance (in pixels) of window shadows from casting window. + WindowShadowOffsetAngle = IM_PI * 0.25f; // Offset angle of window shadows from casting window (0.0f = left, 0.5f*PI = bottom, 1.0f*PI = right, 1.5f*PI = top). // Behaviors HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. @@ -3872,6 +3876,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg"; case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg"; + case ImGuiCol_WindowShadow: return "WindowShadow"; } IM_ASSERT(0); return "Unknown"; @@ -7325,6 +7330,11 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar } } + // Draw window shadow + if (style.WindowShadowSize > 0.0f && (!(flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_Popup))) + if (style.Colors[ImGuiCol_WindowShadow].w > 0.0f) + RenderWindowShadow(window); + // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { @@ -7373,6 +7383,16 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar window->DC.NavLayerCurrent = ImGuiNavLayer_Main; } +void ImGui::RenderWindowShadow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + float shadow_size = style.WindowShadowSize; + ImU32 shadow_col = GetColorU32(ImGuiCol_WindowShadow); + ImVec2 shadow_offset = ImVec2(ImCos(style.WindowShadowOffsetAngle), ImSin(style.WindowShadowOffsetAngle)) * style.WindowShadowOffsetDist; + window->DrawList->AddShadowRect(window->Pos, window->Pos + window->Size, shadow_col, shadow_size, shadow_offset, ImDrawFlags_ShadowCutOutShapeBackground, window->WindowRounding); +} + // Render title text, collapse button, close button void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) { @@ -9282,6 +9302,12 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL; g.FontBakedScale = (g.FontBaked != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; g.DrawListSharedData.FontScale = g.FontBakedScale; + if (g.Font) + { + ImFontAtlas* atlas = g.Font->OwnerAtlas; + g.DrawListSharedData.ShadowRectIds = &atlas->ShadowRectIds[0]; + g.DrawListSharedData.ShadowRectUvs = &atlas->ShadowRectUvs[0]; + } } // Exposed in case user may want to override setting density. diff --git a/imgui.h b/imgui.h index fe8531083..4dfd47e4c 100644 --- a/imgui.h +++ b/imgui.h @@ -1837,6 +1837,7 @@ enum ImGuiCol_ ImGuiCol_NavWindowingHighlight, // Highlight window when using Ctrl+Tab ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the Ctrl+Tab window list, when active ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active + ImGuiCol_WindowShadow, // Window shadows ImGuiCol_COUNT, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -2402,6 +2403,10 @@ struct ImGuiStyle float CurveTessellationMaxError; // Maximum error (in pixels) when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + float WindowShadowSize; // Size (in pixels) of window shadows. Set this to zero to disable shadows. + float WindowShadowOffsetDist; // Offset distance (in pixels) of window shadows from casting window. + float WindowShadowOffsetAngle; // Offset angle of window shadows from casting window (0.0f = left, 0.5f*PI = bottom, 1.0f*PI = right, 1.5f*PI = top). + // Colors ImVec4 Colors[ImGuiCol_COUNT]; @@ -3325,6 +3330,8 @@ enum ImDrawFlags_ //ImDrawFlags_Closed = 1, // Prior to 1.92.8 (May 2026), ImDrawFlags_Closed was guaranteed to be == 1<<0 == 1 for legacy compatibility reason. Hardcoded use of 1 or true should be replaced. ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, + + ImDrawFlags_ShadowCutOutShapeBackground = 1 << 20, // Do not render the shadow shape under the objects to be shadowed to save on fill-rate or facilitate blending. Slower on CPU. }; // Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. @@ -3427,6 +3434,23 @@ struct ImDrawList IMGUI_API void AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); IMGUI_API void AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + // Shadows primitives + // [BETA] API + // - Add shadow for a object, with min/max or center/radius describing the object extents, and offset shifting the shadow. + // - Rounding parameters refer to the object itself, not the shadow! + // - By default, the area under the object is filled, because this is simpler to process. + // Using the ImDrawFlags_ShadowCutOutShapeBackground flag makes the function not render this area and leave a hole under the object. + // - Shadows w/ fill under the object: a bit faster for CPU, more pixels rendered, visible/darkening if used behind a transparent shape. + // Typically used by: small, frequent objects, opaque objects, transparent objects if shadow darkening isn't an issue. + // - Shadows w/ hole under the object: a bit slower for CPU, less pixels rendered, no difference if used behind a transparent shape. + // Typically used by: large, infrequent objects, transparent objects if exact blending/color matter. + // - FIXME-SHADOWS: 'offset' + ImDrawFlags_ShadowCutOutShapeBackground are not currently supported together with AddShadowCircle(), AddShadowConvexPoly(), AddShadowNGon(). + #define IMGUI_HAS_SHADOWS 1 + IMGUI_API void AddShadowRect(const ImVec2& obj_min, const ImVec2& obj_max, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags = 0, float obj_rounding = 0.0f); + IMGUI_API void AddShadowCircle(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags = 0, int obj_num_segments = 12); + IMGUI_API void AddShadowConvexPoly(const ImVec2* points, int points_count, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags = 0); + IMGUI_API void AddShadowNGon(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, int obj_num_segments); + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() // - Important: filled shapes must always use clockwise winding order! The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. // so e.g. 'PathArcTo(center, radius, PI * -0.5f, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5f)' won't have correct anti-aliasing when followed by PathFillConvex(). @@ -3632,6 +3656,24 @@ struct ImTextureData // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) //----------------------------------------------------------------------------- +// [Internal] Shadow texture baking config +struct ImFontAtlasShadowTexConfig +{ + int TexCornerSize; // Size of the corner areas. + int TexEdgeSize; // Size of the edge areas (and by extension the center). Changing this is normally unnecessary. + float TexFalloffPower; // The power factor for the shadow falloff curve. + float TexDistanceFieldOffset; // How much to offset the distance field by (allows over/under-shadowing, potentially useful for accommodating rounded corners on the "casting" shape). + bool TexBlur; // Do we want to Gaussian blur the shadow texture? + + inline ImFontAtlasShadowTexConfig() { memset(this, 0, sizeof(*this)); } + IMGUI_API void SetupDefaults(); + int GetRectTexPadding() const { return 2; } // Number of pixels of padding to add to the rectangular texture to avoid sampling artifacts at the edges. + int CalcRectTexSize() const { return TexCornerSize + TexEdgeSize + GetRectTexPadding(); } // The size of the texture area required for the actual 2x2 rectangle shadow texture (after the redundant corners have been removed). Padding is required here to avoid sampling artifacts at the edge adjoining the removed corners. int CalcConvexTexWidth() const; // The width of the texture area required for the convex shape shadow texture. + int GetConvexTexPadding() const { return 8; } // Number of pixels of padding to add to the convex shape texture to avoid sampling artifacts at the edges. This also acts as padding for the expanded corner triangles. + int CalcConvexTexWidth() const; // The width of the texture area required for the convex shape shadow texture. + int CalcConvexTexHeight() const; // The height of the texture area required for the convex shape shadow texture. +}; + // A font input/source (we may rename this to ImFontSource in the future) struct ImFontConfig { @@ -3885,6 +3927,11 @@ struct ImFontAtlas int RefCount; // Number of contexts using this atlas ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it. + // [Internal] Shadow data + ImFontAtlasRectId ShadowRectIds[2]; // IDs of rect for shadow textures + ImVec4 ShadowRectUvs[10]; // UV coordinates for shadow textures, 9 for the rectangle shadows and the final entry for the convex shape shadows + ImFontAtlasShadowTexConfig ShadowTexConfig; // Shadow texture baking config + // [Obsolete] #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7478a99ee..7aeff1fbe 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8961,6 +8961,22 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) EndTabItem(); } + if (BeginTabItem("Shadows")) + { + Text("Window shadows:"); + ColorEdit4("Color", (float*)&style.Colors[ImGuiCol_WindowShadow], ImGuiColorEditFlags_AlphaBar); + SameLine(); + HelpMarker("Same as 'WindowShadow' in Colors tab."); + + SliderFloat("Size", &style.WindowShadowSize, 0.0f, 128.0f, "%.1f"); + SameLine(); + HelpMarker("Set shadow size to zero to disable shadows."); + SliderFloat("Offset distance", &style.WindowShadowOffsetDist, 0.0f, 64.0f, "%.0f"); + SliderAngle("Offset angle", &style.WindowShadowOffsetAngle); + + EndTabItem(); + } + EndTabBar(); } PopItemWidth(); @@ -10568,6 +10584,168 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("Shadows")) + { + static float shadow_thickness = 40.0f; + static ImVec4 shadow_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + static bool shadow_filled = false; + static ImVec4 shape_color = ImVec4(0.9f, 0.6f, 0.3f, 1.0f); + static float shape_rounding = 0.0f; + static ImVec2 shadow_offset(0.0f, 0.0f); + static ImVec4 background_color = ImVec4(0.5f, 0.5f, 0.7f, 1.0f); + static bool wireframe = false; + static bool aa = true; + static int poly_shape_index = 0; + ImGui::Checkbox("Shadow filled", &shadow_filled); + ImGui::SameLine(); + HelpMarker("This will fill the section behind the shape to shadow. It's often unnecessary and wasteful but provided for consistency."); + ImGui::Checkbox("Wireframe shapes", &wireframe); + ImGui::SameLine(); + HelpMarker("This draws the shapes in wireframe so you can see the shadow underneath."); + ImGui::Checkbox("Anti-aliasing", &aa); + + ImGui::DragFloat("Shadow Thickness", &shadow_thickness, 1.0f, 0.0f, 100.0f, "%.02f"); + ImGui::SliderFloat2("Offset", (float*)&shadow_offset, -32.0f, 32.0f); + ImGui::SameLine(); + HelpMarker("Note that currently circles/convex shapes do not support non-zero offsets for unfilled shadows."); + ImGui::ColorEdit4("Background Color", &background_color.x); + ImGui::ColorEdit4("Shadow Color", &shadow_color.x); + ImGui::ColorEdit4("Shape Color", &shape_color.x); + ImGui::DragFloat("Shape Rounding", &shape_rounding, 1.0f, 0.0f, 20.0f, "%.02f"); + ImGui::Combo("Convex shape", &poly_shape_index, "Shape 1\0Shape 2\0Shape 3\0Shape 4\0Shape 4 (winding reversed)\0"); + + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + ImDrawListFlags old_flags = draw_list->Flags; + + if (aa) + draw_list->Flags |= ~ImDrawListFlags_AntiAliasedFill; + else + draw_list->Flags &= ~ImDrawListFlags_AntiAliasedFill; + + // Fill a strip of background + { + ImVec2 p = ImGui::GetCursorScreenPos(); + draw_list->AddRectFilled(p, ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 200.0f), ImGui::GetColorU32(background_color)); + } + + // Rectangle + { + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::Dummy(ImVec2(200.0f, 200.0f)); + + ImVec2 r1(p.x + 50.0f, p.y + 50.0f); + ImVec2 r2(p.x + 150.0f, p.y + 150.0f); + ImDrawFlags draw_flags = shadow_filled ? ImDrawFlags_None : ImDrawFlags_ShadowCutOutShapeBackground; + draw_list->AddShadowRect(r1, r2, ImGui::GetColorU32(shadow_color), shadow_thickness, shadow_offset, draw_flags, shape_rounding); + + if (wireframe) + draw_list->AddRect(r1, r2, ImGui::GetColorU32(shape_color), shape_rounding); + else + draw_list->AddRectFilled(r1, r2, ImGui::GetColorU32(shape_color), shape_rounding); + } + + ImGui::SameLine(); + + // Circle + { + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::Dummy(ImVec2(200.0f, 200.0f)); + + // FIXME-SHADOWS: Offset forced to zero when shadow is not filled because it isn't supported + float off = 10.0f; + ImVec2 r1(p.x + 50.0f + off, p.y + 50.0f + off); + ImVec2 r2(p.x + 150.0f - off, p.y + 150.0f - off); + ImVec2 center(p.x + 100.0f, p.y + 100.0f); + ImDrawFlags draw_flags = shadow_filled ? ImDrawFlags_None : ImDrawFlags_ShadowCutOutShapeBackground; + draw_list->AddShadowCircle(center, 50.0f, ImGui::GetColorU32(shadow_color), shadow_thickness, shadow_filled ? shadow_offset : ImVec2(0.0f, 0.0f), draw_flags, 0); + + if (wireframe) + draw_list->AddCircle(center, 50.0f, ImGui::GetColorU32(shape_color), 0); + else + draw_list->AddCircleFilled(center, 50.0f, ImGui::GetColorU32(shape_color), 0); + } + + ImGui::SameLine(); + + // Convex shape + { + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::Dummy(ImVec2(200.0f, 200.0f)); + + const ImVec2 poly_centre(pos.x + 50.0f, pos.y + 100.0f); + ImVec2 poly_points[8]; + int poly_points_count = 0; + + switch (poly_shape_index) + { + default: + case 0: + { + poly_points[0] = ImVec2(poly_centre.x - 32.0f, poly_centre.y); + poly_points[1] = ImVec2(poly_centre.x - 24.0f, poly_centre.y + 24.0f); + poly_points[2] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[3] = ImVec2(poly_centre.x + 24.0f, poly_centre.y + 24.0f); + poly_points[4] = ImVec2(poly_centre.x + 32.0f, poly_centre.y); + poly_points[5] = ImVec2(poly_centre.x + 24.0f, poly_centre.y - 24.0f); + poly_points[6] = ImVec2(poly_centre.x, poly_centre.y - 32.0f); + poly_points[7] = ImVec2(poly_centre.x - 32.0f, poly_centre.y - 32.0f); + poly_points_count = 8; + break; + } + case 1: + { + poly_points[0] = ImVec2(poly_centre.x + 40.0f, poly_centre.y - 20.0f); + poly_points[1] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[2] = ImVec2(poly_centre.x - 24.0f, poly_centre.y - 32.0f); + poly_points_count = 3; + break; + } + case 2: + { + poly_points[0] = ImVec2(poly_centre.x - 32.0f, poly_centre.y); + poly_points[1] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[2] = ImVec2(poly_centre.x + 32.0f, poly_centre.y); + poly_points[3] = ImVec2(poly_centre.x, poly_centre.y - 32.0f); + poly_points_count = 4; + break; + } + case 3: + { + poly_points[0] = ImVec2(poly_centre.x - 4.0f, poly_centre.y - 20.0f); + poly_points[1] = ImVec2(poly_centre.x + 12.0f, poly_centre.y + 2.0f); + poly_points[2] = ImVec2(poly_centre.x + 8.0f, poly_centre.y + 16.0f); + poly_points[3] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[4] = ImVec2(poly_centre.x - 16.0f, poly_centre.y - 32.0f); + poly_points_count = 5; + break; + } + case 4: // Same as test case 3 but with reversed winding + { + poly_points[0] = ImVec2(poly_centre.x - 16.0f, poly_centre.y - 32.0f); + poly_points[1] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[2] = ImVec2(poly_centre.x + 8.0f, poly_centre.y + 16.0f); + poly_points[3] = ImVec2(poly_centre.x + 12.0f, poly_centre.y + 2.0f); + poly_points[4] = ImVec2(poly_centre.x - 4.0f, poly_centre.y - 20.0f); + poly_points_count = 5; + break; + } + } + + // FIXME-SHADOWS: Offset forced to zero when shadow is not filled because it isn't supported + ImDrawFlags draw_flags = shadow_filled ? ImDrawFlags_None : ImDrawFlags_ShadowCutOutShapeBackground; + draw_list->AddShadowConvexPoly(poly_points, poly_points_count, ImGui::GetColorU32(shadow_color), shadow_thickness, shadow_filled ? shadow_offset : ImVec2(0.0f, 0.0f), draw_flags); + + if (wireframe) + draw_list->AddPolyline(poly_points, poly_points_count, ImGui::GetColorU32(shape_color), 1.0f, ImDrawFlags_Closed); + else + draw_list->AddConvexPolyFilled(poly_points, poly_points_count, ImGui::GetColorU32(shape_color)); + } + + draw_list->Flags = old_flags; + + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("BG/FG draw lists")) { IMGUI_DEMO_MARKER("Examples/Custom rendering/BG & FG draw lists"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bf7aebad1..b77fb38cd 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -9,9 +9,11 @@ Index of this file: // [SECTION] Style functions // [SECTION] ImDrawList // [SECTION] ImTriangulator, ImDrawList concave polygon fill +// [SECTION] ImDrawList Shadow Primitives // [SECTION] ImDrawListSplitter // [SECTION] ImDrawData // [SECTION] Helpers ShadeVertsXXX functions +// [SECTION] ImFontAtlasShadowTexConfig // [SECTION] ImFontConfig // [SECTION] ImFontAtlas, ImFontAtlasBuilder // [SECTION] ImFontAtlas: backend for stb_truetype @@ -250,6 +252,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); + colors[ImGuiCol_WindowShadow] = ImVec4(0.08f, 0.08f, 0.08f, 0.35f); } void ImGui::StyleColorsClassic(ImGuiStyle* dst) @@ -318,6 +321,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); + colors[ImGuiCol_WindowShadow] = ImVec4(0.08f, 0.08f, 0.08f, 0.35f); } // Those light colors are better suited with a thicker font than the default one + FrameBorder @@ -387,6 +391,31 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); + colors[ImGuiCol_WindowShadow] = ImVec4(0.08f, 0.08f, 0.08f, 0.35f); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlasShadowTexConfig +//----------------------------------------------------------------------------- + +void ImFontAtlasShadowTexConfig::SetupDefaults() +{ + TexCornerSize = 16; + TexEdgeSize = 1; + TexFalloffPower = 4.8f; + TexDistanceFieldOffset = 3.8f; + TexBlur = true; +} + +int ImFontAtlasShadowTexConfig::CalcConvexTexWidth() const +{ + // We have to pad the texture enough that we don't go off the edges when we expand the corner triangles + return (int)((TexCornerSize / ImCos(IM_PI * 0.25f)) + (GetConvexTexPadding() * 2)); +} + +int ImFontAtlasShadowTexConfig::CalcConvexTexHeight() const +{ + return CalcConvexTexWidth(); // Same value } //----------------------------------------------------------------------------- @@ -2137,6 +2166,724 @@ void ImDrawList::AddConcavePolyFilled(const ImVec2* points, const int points_cou } } +//----------------------------------------------------------------------------- +// [SECTION] ImDrawList Shadow Primitives +//----------------------------------------------------------------------------- +// - AddSubtractedRect() [Internal] +// - ClipPolygonShape() [Internal] +// - AddSubtractedRect() [Internal] +// - AddRectShadow() +//----------------------------------------------------------------------------- + +// Adds a rectangle (A) with another rectangle (B) subtracted from it (i.e. the portion of A covered by B is not drawn). Does not handle rounded corners (use the version that takes a convex polygon for that). +static void AddSubtractedRect(ImDrawList* draw_list, const ImVec2& a_min, const ImVec2& a_max, const ImVec2& a_min_uv, const ImVec2& a_max_uv, ImVec2 b_min, ImVec2 b_max, ImU32 col) +{ + // Early out without drawing anything if A is zero-size + if (a_min.x >= a_max.x || a_min.y >= a_max.y) + return; + + // Early out without drawing anything if B covers A entirely + if (a_min.x >= b_min.x && a_max.x <= b_max.x && a_min.y >= b_min.y && a_max.y <= b_max.y) + return; + + // First clip the extents of B to A + b_min = ImMax(b_min, a_min); + b_max = ImMin(b_max, a_max); + if (b_min.x >= b_max.x || b_min.y >= b_max.y) + { + // B is entirely outside A, so just draw A as-is + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(a_min, a_max, a_min_uv, a_max_uv, col); + return; + } + + // Otherwise we need to emit (up to) four quads to cover the visible area... + // Our layout looks like this (numbers are vertex indices, letters are quads): + // + // 0---8------9-----1 + // | | B | | + // + 4------5 + + // | A |xxxxxx| C | + // | |xxxxxx| | + // + 7------6 + + // | | D | | + // 3---11-----10----2 + + const int max_verts = 12; + const int max_indices = 6 * 4; // At most four quads + draw_list->PrimReserve(max_indices, max_verts); + + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx idx = (ImDrawIdx)draw_list->_VtxCurrentIdx; + + // Write vertices + vtx_write[0].pos = ImVec2(a_min.x, a_min.y); vtx_write[0].uv = ImVec2(a_min_uv.x, a_min_uv.y); vtx_write[0].col = col; + vtx_write[1].pos = ImVec2(a_max.x, a_min.y); vtx_write[1].uv = ImVec2(a_max_uv.x, a_min_uv.y); vtx_write[1].col = col; + vtx_write[2].pos = ImVec2(a_max.x, a_max.y); vtx_write[2].uv = ImVec2(a_max_uv.x, a_max_uv.y); vtx_write[2].col = col; + vtx_write[3].pos = ImVec2(a_min.x, a_max.y); vtx_write[3].uv = ImVec2(a_min_uv.x, a_max_uv.y); vtx_write[3].col = col; + + const ImVec2 pos_to_uv_scale = (a_max_uv - a_min_uv) / (a_max - a_min); // Guaranteed never to be a /0 because we check for zero-size A above + const ImVec2 pos_to_uv_offset = (a_min_uv / pos_to_uv_scale) - a_min; + + // Helper that generates an interpolated UV based on position +#define LERP_UV(x_pos, y_pos) (ImVec2(((x_pos) + pos_to_uv_offset.x) * pos_to_uv_scale.x, ((y_pos) + pos_to_uv_offset.y) * pos_to_uv_scale.y)) + vtx_write[4].pos = ImVec2(b_min.x, b_min.y); vtx_write[4].uv = LERP_UV(b_min.x, b_min.y); vtx_write[4].col = col; + vtx_write[5].pos = ImVec2(b_max.x, b_min.y); vtx_write[5].uv = LERP_UV(b_max.x, b_min.y); vtx_write[5].col = col; + vtx_write[6].pos = ImVec2(b_max.x, b_max.y); vtx_write[6].uv = LERP_UV(b_max.x, b_max.y); vtx_write[6].col = col; + vtx_write[7].pos = ImVec2(b_min.x, b_max.y); vtx_write[7].uv = LERP_UV(b_min.x, b_max.y); vtx_write[7].col = col; + vtx_write[8].pos = ImVec2(b_min.x, a_min.y); vtx_write[8].uv = LERP_UV(b_min.x, a_min.y); vtx_write[8].col = col; + vtx_write[9].pos = ImVec2(b_max.x, a_min.y); vtx_write[9].uv = LERP_UV(b_max.x, a_min.y); vtx_write[9].col = col; + vtx_write[10].pos = ImVec2(b_max.x, a_max.y); vtx_write[10].uv = LERP_UV(b_max.x, a_max.y); vtx_write[10].col = col; + vtx_write[11].pos = ImVec2(b_min.x, a_max.y); vtx_write[11].uv = LERP_UV(b_min.x, a_max.y); vtx_write[11].col = col; +#undef LERP_UV + draw_list->_VtxWritePtr += 12; + draw_list->_VtxCurrentIdx += 12; + + // Write indices for each quad (if it is visible) + if (b_min.x > a_min.x) // A + { + idx_write[0] = (ImDrawIdx)(idx + 0); idx_write[1] = (ImDrawIdx)(idx + 8); idx_write[2] = (ImDrawIdx)(idx + 11); + idx_write[3] = (ImDrawIdx)(idx + 0); idx_write[4] = (ImDrawIdx)(idx + 11); idx_write[5] = (ImDrawIdx)(idx + 3); + idx_write += 6; + } + if (b_min.y > a_min.y) // B + { + idx_write[0] = (ImDrawIdx)(idx + 8); idx_write[1] = (ImDrawIdx)(idx + 9); idx_write[2] = (ImDrawIdx)(idx + 5); + idx_write[3] = (ImDrawIdx)(idx + 8); idx_write[4] = (ImDrawIdx)(idx + 5); idx_write[5] = (ImDrawIdx)(idx + 4); + idx_write += 6; + } + if (a_max.x > b_max.x) // C + { + idx_write[0] = (ImDrawIdx)(idx + 9); idx_write[1] = (ImDrawIdx)(idx + 1); idx_write[2] = (ImDrawIdx)(idx + 2); + idx_write[3] = (ImDrawIdx)(idx + 9); idx_write[4] = (ImDrawIdx)(idx + 2); idx_write[5] = (ImDrawIdx)(idx + 10); + idx_write += 6; + } + if (a_max.y > b_max.y) // D + { + idx_write[0] = (ImDrawIdx)(idx + 7); idx_write[1] = (ImDrawIdx)(idx + 6); idx_write[2] = (ImDrawIdx)(idx + 10); + idx_write[3] = (ImDrawIdx)(idx + 7); idx_write[4] = (ImDrawIdx)(idx + 10); idx_write[5] = (ImDrawIdx)(idx + 11); + idx_write += 6; + } + + const int used_indices = (int)(idx_write - draw_list->_IdxWritePtr); + draw_list->_IdxWritePtr = idx_write; + draw_list->PrimUnreserve(max_indices - used_indices, 0); +} + +// Clip a polygonal shape to a rectangle, writing the results into dest_points. The number of points emitted is returned (may be zero if the polygon was entirely outside the rectangle, or the source polygon was not valid). dest_points may still be written to even if zero was returned. +// allocated_dest_points should contain the number of allocated points in dest_points - in general this should be the number of source points + 4 to accommodate the worst case. If this is exceeded data will be truncated and -1 returned. Stack space work area is allocated based on this value so it shouldn't be too large. +static int ClipPolygonShape(ImVec2* src_points, int num_src_points, ImVec2* dest_points, int allocated_dest_points, ImVec2 clip_rect_min, ImVec2 clip_rect_max) +{ + // Early-out with an empty result if clipping region is zero-sized + if (clip_rect_max.x <= clip_rect_min.x || clip_rect_max.y <= clip_rect_min.y) + return 0; + + // Early-out if there is no source geometry + if (num_src_points < 3) + return 0; + + // The four clip planes here are indexed as: + // 0 = X-, 1 = X+, 2 = Y-, 3 = Y+ + ImU8* outflags[2]; // Double-buffered flags for each vertex indicating which of the four clip planes it is outside of + outflags[0] = (ImU8*)alloca(2 * allocated_dest_points * sizeof(ImU8)); + outflags[1] = outflags[0] + allocated_dest_points; + + // Calculate initial outflags + ImU8 outflags_anded = 0xFF; + ImU8 outflags_ored = 0; + for (int point_idx = 0; point_idx < num_src_points; point_idx++) + { + const ImVec2 pos = src_points[point_idx]; + const ImU8 point_outflags = (pos.x < clip_rect_min.x ? 1 : 0) | (pos.x > clip_rect_max.x ? 2 : 0) | (pos.y < clip_rect_min.y ? 4 : 0) | (pos.y > clip_rect_max.y ? 8 : 0); + outflags[0][point_idx] = point_outflags; // Writing to buffer 0 + outflags_anded &= point_outflags; + outflags_ored |= point_outflags; + } + if (outflags_anded != 0) // Entirely clipped by any one plane, so nothing remains + return 0; + + if (outflags_ored == 0) // Entirely within bounds, so trivial accept + { + if (allocated_dest_points < num_src_points) + return -1; // Not sure what the caller was thinking if this happens, but we should handle it gracefully + + memcpy(dest_points, src_points, num_src_points * sizeof(ImVec2)); + return num_src_points; + } + + // Shape needs clipping + ImVec2* clip_buf[2]; // Double-buffered work area + clip_buf[0] = (ImVec2*)alloca(2 * allocated_dest_points * sizeof(ImVec2)); //-V630 + clip_buf[1] = clip_buf[0] + allocated_dest_points; + + memcpy(clip_buf[0], src_points, num_src_points * sizeof(ImVec2)); + int clip_buf_size = num_src_points; // Number of vertices currently in the clip buffer + + int read_buffer_idx = 0; // The index of the clip buffer/out-flags we are reading (0 or 1) + + for (int clip_plane = 0; clip_plane < 4; clip_plane++) // 0 = X-, 1 = X+, 2 = Y-, 3 = Y+ + { + const int clip_plane_bit = 1 << clip_plane; // Bit mask for our current plane in out-flags + if ((outflags_ored & clip_plane_bit) == 0) + continue; // All vertices are inside this plane, so no need to clip + + ImVec2* read_vert = &clip_buf[read_buffer_idx][0]; // Clip buffer vertex we are currently reading + ImVec2* write_vert = &clip_buf[1 - read_buffer_idx][0]; // Clip buffer vertex we are currently writing + ImVec2* write_vert_end = write_vert + allocated_dest_points; // End of the write buffer + ImU8* read_outflags = &outflags[read_buffer_idx][0]; // Out-flag we are currently reading + ImU8* write_outflags = &outflags[1 - read_buffer_idx][0]; // Out-flag we are currently writing + + // Keep track of the last vertex visited, initially the last in the list + ImVec2* last_vert = &read_vert[clip_buf_size - 1]; + ImU8 last_outflags = read_outflags[clip_buf_size - 1]; + + for (int vert = 0; vert < clip_buf_size; vert++) + { + ImU8 current_outflags = *(read_outflags++); + bool out = (current_outflags & clip_plane_bit) != 0; + if (((current_outflags ^ last_outflags) & clip_plane_bit) == 0) // We haven't crossed the clip plane + { + if (!out) + { + // Emit vertex as-is + if (write_vert >= write_vert_end) + return -1; // Ran out of buffer space, so abort + *(write_vert++) = *read_vert; + *(write_outflags++) = current_outflags; + } + } + else + { + // Emit a vertex at the intersection point + float t = 0.0f; + ImVec2 pos0 = *last_vert; + ImVec2 pos1 = *read_vert; + ImVec2 intersect_pos; + switch (clip_plane) + { + case 0: t = (clip_rect_min.x - pos0.x) / (pos1.x - pos0.x); intersect_pos = ImVec2(clip_rect_min.x, pos0.y + ((pos1.y - pos0.y) * t)); break; // X- + case 1: t = (clip_rect_max.x - pos0.x) / (pos1.x - pos0.x); intersect_pos = ImVec2(clip_rect_max.x, pos0.y + ((pos1.y - pos0.y) * t)); break; // X+ + case 2: t = (clip_rect_min.y - pos0.y) / (pos1.y - pos0.y); intersect_pos = ImVec2(pos0.x + ((pos1.x - pos0.x) * t), clip_rect_min.y); break; // Y- + case 3: t = (clip_rect_max.y - pos0.y) / (pos1.y - pos0.y); intersect_pos = ImVec2(pos0.x + ((pos1.x - pos0.x) * t), clip_rect_max.y); break; // Y+ + } + + if (write_vert >= write_vert_end) + return -1; // Ran out of buffer space, so abort + + // Write new out-flags for the vertex we just emitted + *(write_vert++) = intersect_pos; + *(write_outflags++) = (intersect_pos.x < clip_rect_min.x ? 1 : 0) | (intersect_pos.x > clip_rect_max.x ? 2 : 0) | (intersect_pos.y < clip_rect_min.y ? 4 : 0) | (intersect_pos.y > clip_rect_max.y ? 8 : 0); + + if (!out) + { + // When coming back in, also emit the actual vertex + if (write_vert >= write_vert_end) + return -1; // Ran out of buffer space, so abort + *(write_vert++) = *read_vert; + *(write_outflags++) = current_outflags; + } + + last_outflags = current_outflags; + } + + last_vert = read_vert; + read_vert++; // Advance to next vertex + } + + clip_buf_size = (int)(write_vert - &clip_buf[1 - read_buffer_idx][0]); // Update buffer size + read_buffer_idx = 1 - read_buffer_idx; // Swap buffers + } + + if (clip_buf_size < 3) + return 0; // Nothing to return + + // Copy results to output buffer, removing any redundant vertices + int num_out_verts = 0; + ImVec2 last_vert = clip_buf[read_buffer_idx][clip_buf_size - 1]; + for (int i = 0; i < clip_buf_size; i++) + { + ImVec2 vert = clip_buf[read_buffer_idx][i]; + if (ImLengthSqr(vert - last_vert) <= 0.00001f) + continue; + dest_points[num_out_verts++] = vert; + last_vert = vert; + } + + // Return size (IF this is still a valid shape) + return (num_out_verts > 2) ? num_out_verts : 0; +} + +// Adds a rectangle (A) with a convex shape (B) subtracted from it (i.e. the portion of A covered by B is not drawn). +static void AddSubtractedRect(ImDrawList* draw_list, const ImVec2& a_min, const ImVec2& a_max, const ImVec2& a_min_uv, const ImVec2& a_max_uv, ImVec2* b_points, int num_b_points, ImU32 col) +{ + // Early out without drawing anything if A is zero-size + if (a_min.x >= a_max.x || a_min.y >= a_max.y) + return; + + // First clip B to A + const int max_clipped_points = num_b_points + 4; + ImVec2* clipped_b_points = (ImVec2*)alloca(max_clipped_points * sizeof(ImVec2)); //-V630 + const int num_clipped_points = ClipPolygonShape(b_points, num_b_points, clipped_b_points, max_clipped_points, a_min, a_max); + IM_ASSERT(num_clipped_points >= 0); // -1 would indicate max_clipped_points was too small, which shouldn't happen + + b_points = clipped_b_points; + num_b_points = num_clipped_points; + + if (num_clipped_points == 0) + { + // B is entirely outside A, so just draw A as-is + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(a_min, a_max, a_min_uv, a_max_uv, col); + } + else + { + // We need to generate clipped geometry + // To do this we walk the inner polygon and connect each edge to one of the four corners of our rectangle based on the quadrant their normal points at + const int max_verts = num_b_points + 4; // Inner points plus the four corners + const int max_indices = (num_b_points * 3) + (4 * 3); // Worst case is one triangle per inner edge and then four filler triangles + draw_list->PrimReserve(max_indices, max_verts); + + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx inner_idx = (ImDrawIdx)draw_list->_VtxCurrentIdx; // Starting index for inner vertices + + // Write inner vertices + const ImVec2 pos_to_uv_scale = (a_max_uv - a_min_uv) / (a_max - a_min); // Guaranteed never to be a /0 because we check for zero-size A above + const ImVec2 pos_to_uv_offset = (a_min_uv / pos_to_uv_scale) - a_min; + + // Helper that generates an interpolated UV based on position +#define LERP_UV(x_pos, y_pos) (ImVec2(((x_pos) + pos_to_uv_offset.x) * pos_to_uv_scale.x, ((y_pos) + pos_to_uv_offset.y) * pos_to_uv_scale.y)) + for (int i = 0; i < num_b_points; i++) + { + vtx_write[i].pos = b_points[i]; + vtx_write[i].uv = LERP_UV(b_points[i].x, b_points[i].y); + vtx_write[i].col = col; + } +#undef LERP_UV + + vtx_write += num_b_points; + + // Write outer vertices + ImDrawIdx outer_idx = (ImDrawIdx)(inner_idx + num_b_points); // Starting index for outer vertices + + ImVec2 outer_verts[4]; + outer_verts[0] = ImVec2(a_min.x, a_min.y); // X- Y- (quadrant 0, top left) + outer_verts[1] = ImVec2(a_max.x, a_min.y); // X+ Y- (quadrant 1, top right) + outer_verts[2] = ImVec2(a_max.x, a_max.y); // X+ Y+ (quadrant 2, bottom right) + outer_verts[3] = ImVec2(a_min.x, a_max.y); // X- Y+ (quadrant 3, bottom left) + + vtx_write[0].pos = outer_verts[0]; vtx_write[0].uv = ImVec2(a_min_uv.x, a_min_uv.y); vtx_write[0].col = col; + vtx_write[1].pos = outer_verts[1]; vtx_write[1].uv = ImVec2(a_max_uv.x, a_min_uv.y); vtx_write[1].col = col; + vtx_write[2].pos = outer_verts[2]; vtx_write[2].uv = ImVec2(a_max_uv.x, a_max_uv.y); vtx_write[2].col = col; + vtx_write[3].pos = outer_verts[3]; vtx_write[3].uv = ImVec2(a_min_uv.x, a_max_uv.y); vtx_write[3].col = col; + + draw_list->_VtxCurrentIdx += num_b_points + 4; + draw_list->_VtxWritePtr += num_b_points + 4; + + // Now walk the inner vertices in order + ImVec2 last_inner_vert = b_points[num_b_points - 1]; + int last_inner_vert_idx = num_b_points - 1; + int last_outer_vert_idx = -1; + int first_outer_vert_idx = -1; + + // Triangle-area based check for degenerate triangles + // Min area (0.1f) is doubled (* 2.0f) because we're calculating (area * 2) here +#define IS_DEGENERATE(a, b, c) (ImFabs((((a).x * ((b).y - (c).y)) + ((b).x * ((c).y - (a).y)) + ((c).x * ((a).y - (b).y)))) < (0.1f * 2.0f)) + + // Check the winding order of the inner vertices using the sign of the triangle area, and set the outer vertex winding to match + int outer_vertex_winding = (((b_points[0].x * (b_points[1].y - b_points[2].y)) + (b_points[1].x * (b_points[2].y - b_points[0].y)) + (b_points[2].x * (b_points[0].y - b_points[1].y))) < 0.0f) ? -1 : 1; + for (int inner_vert_idx = 0; inner_vert_idx < num_b_points; inner_vert_idx++) + { + ImVec2 current_inner_vert = b_points[inner_vert_idx]; + + // Calculate normal (not actually normalized, as for our purposes here it doesn't need to be) + ImVec2 normal(current_inner_vert.y - last_inner_vert.y, -(current_inner_vert.x - last_inner_vert.x)); + + // Calculate the outer vertex index based on the quadrant the normal points at (0=top left, 1=top right, 2=bottom right, 3=bottom left) + int outer_vert_idx = (ImFabs(normal.x) > ImFabs(normal.y)) ? ((normal.x >= 0.0f) ? ((normal.y > 0.0f) ? 2 : 1) : ((normal.y > 0.0f) ? 3 : 0)) : ((normal.y >= 0.0f) ? ((normal.x > 0.0f) ? 2 : 3) : ((normal.x > 0.0f) ? 1 : 0)); + ImVec2 outer_vert = outer_verts[outer_vert_idx]; + + // Write the main triangle (connecting the inner edge to the corner) + if (!IS_DEGENERATE(last_inner_vert, current_inner_vert, outer_vert)) + { + idx_write[0] = (ImDrawIdx)(inner_idx + last_inner_vert_idx); + idx_write[1] = (ImDrawIdx)(inner_idx + inner_vert_idx); + idx_write[2] = (ImDrawIdx)(outer_idx + outer_vert_idx); + idx_write += 3; + } + + // We don't initially know which outer vertex we are going to start from, so set that here when processing the first inner vertex + if (first_outer_vert_idx == -1) + { + first_outer_vert_idx = outer_vert_idx; + last_outer_vert_idx = outer_vert_idx; + } + + // Now walk the outer edge and write any filler triangles needed (connecting outer edges to the inner vertex) + while (outer_vert_idx != last_outer_vert_idx) + { + int next_outer_vert_idx = (last_outer_vert_idx + outer_vertex_winding) & 3; + if (!IS_DEGENERATE(outer_verts[last_outer_vert_idx], outer_verts[next_outer_vert_idx], last_inner_vert)) + { + idx_write[0] = (ImDrawIdx)(outer_idx + last_outer_vert_idx); + idx_write[1] = (ImDrawIdx)(outer_idx + next_outer_vert_idx); + idx_write[2] = (ImDrawIdx)(inner_idx + last_inner_vert_idx); + idx_write += 3; + } + last_outer_vert_idx = next_outer_vert_idx; + } + + last_inner_vert = current_inner_vert; + last_inner_vert_idx = inner_vert_idx; + } + + // Write remaining filler triangles for any un-traversed outer edges + if (first_outer_vert_idx != -1) + { + while (first_outer_vert_idx != last_outer_vert_idx) + { + int next_outer_vert_idx = (last_outer_vert_idx + outer_vertex_winding) & 3; + if (!IS_DEGENERATE(outer_verts[last_outer_vert_idx], outer_verts[next_outer_vert_idx], last_inner_vert)) + { + idx_write[0] = (ImDrawIdx)(outer_idx + last_outer_vert_idx); + idx_write[1] = (ImDrawIdx)(outer_idx + next_outer_vert_idx); + idx_write[2] = (ImDrawIdx)(inner_idx + last_inner_vert_idx); + idx_write += 3; + } + last_outer_vert_idx = next_outer_vert_idx; + } + } +#undef IS_DEGENERATE + + int used_indices = (int)(idx_write - draw_list->_IdxWritePtr); + draw_list->_IdxWritePtr = idx_write; + draw_list->PrimUnreserve(max_indices - used_indices, 0); + } +} + +void ImDrawList::AddShadowRect(const ImVec2& obj_min, const ImVec2& obj_max, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, float obj_rounding) +{ + if ((shadow_col & IM_COL32_A_MASK) == 0) + return; + + ImVec2* inner_rect_points = NULL; // Points that make up the shape of the inner rectangle (used when it has rounded corners) + int inner_rect_points_count = 0; + + // Generate a path describing the inner rectangle and copy it to our buffer + const bool is_filled = (flags & ImDrawFlags_ShadowCutOutShapeBackground) == 0; + const bool is_rounded = (obj_rounding > 0.0f) && ((flags & ImDrawFlags_RoundCornersMask_) != ImDrawFlags_RoundCornersNone); // Do we have rounded corners? + if (is_rounded && !is_filled) + { + IM_ASSERT(_Path.Size == 0); + PathRect(obj_min, obj_max, obj_rounding, flags); + inner_rect_points_count = _Path.Size; + inner_rect_points = (ImVec2*)alloca(inner_rect_points_count * sizeof(ImVec2)); //-V630 + memcpy(inner_rect_points, _Path.Data, inner_rect_points_count * sizeof(ImVec2)); + _Path.Size = 0; + } + + if (is_filled) + PrimReserve(6 * 9, 4 * 9); // Reserve space for adding unclipped chunks + + // Draw the relevant chunks of the texture (the texture is split into a 3x3 grid) + // FIXME-OPT: Might make sense to optimize/unroll for the fast paths (filled or not rounded) + for (int x = 0; x < 3; x++) + { + for (int y = 0; y < 3; y++) + { + const int uv_index = x + (y + y + y); // y*3 formatted so as to ensure the compiler avoids an actual multiply + const ImVec4 uvs = _Data->ShadowRectUvs[uv_index]; + + ImVec2 draw_min, draw_max; + switch (x) + { + case 0: draw_min.x = obj_min.x - shadow_thickness; draw_max.x = obj_min.x; break; + case 1: draw_min.x = obj_min.x; draw_max.x = obj_max.x; break; + case 2: draw_min.x = obj_max.x; draw_max.x = obj_max.x + shadow_thickness; break; + } + switch (y) + { + case 0: draw_min.y = obj_min.y - shadow_thickness; draw_max.y = obj_min.y; break; + case 1: draw_min.y = obj_min.y; draw_max.y = obj_max.y; break; + case 2: draw_min.y = obj_max.y; draw_max.y = obj_max.y + shadow_thickness; break; + } + + ImVec2 uv_min(uvs.x, uvs.y); + ImVec2 uv_max(uvs.z, uvs.w); + if (is_filled) + PrimRectUV(draw_min + shadow_offset, draw_max + shadow_offset, uv_min, uv_max, shadow_col); // No clipping path (draw entire shadow) + else if (is_rounded) + AddSubtractedRect(this, draw_min + shadow_offset, draw_max + shadow_offset, uv_min, uv_max, inner_rect_points, inner_rect_points_count, shadow_col); // Complex path for rounded rectangles + else + AddSubtractedRect(this, draw_min + shadow_offset, draw_max + shadow_offset, uv_min, uv_max, obj_min, obj_max, shadow_col); // Simple fast path for non-rounded rectangles + } + } +} + +// Add a shadow for a convex shape described by points and num_points +void ImDrawList::AddShadowConvexPoly(const ImVec2* points, int points_count, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags) +{ + const bool is_filled = (flags & ImDrawFlags_ShadowCutOutShapeBackground) == 0; + IM_ASSERT((is_filled || (ImLengthSqr(shadow_offset) < 0.00001f)) && "Drawing circle/convex shape shadows with no center fill and an offset is not currently supported"); + IM_ASSERT(points_count >= 3); + + // Calculate poly vertex order + const int vertex_winding = (((points[0].x * (points[1].y - points[2].y)) + (points[1].x * (points[2].y - points[0].y)) + (points[2].x * (points[0].y - points[1].y))) < 0.0f) ? -1 : 1; + + // If we're using anti-aliasing, then inset the shadow by 0.5 pixels to avoid unpleasant fringing artifacts + const bool use_inset_distance = (Flags & ImDrawListFlags_AntiAliasedFill) && (!is_filled); + const float inset_distance = 0.5f; + + const ImVec4 uvs = _Data->ShadowRectUvs[9]; + + int tex_width = _Data->Font->OwnerAtlas->TexData->Width; + int tex_height = _Data->Font->OwnerAtlas->TexData->Height; + float inv_tex_width = 1.0f / (float)tex_width; + float inv_tex_height = 1.0f / (float)tex_height; + + ImVec2 solid_uv = ImVec2(uvs.z, uvs.w); // UV at the inside of an edge + ImVec2 edge_uv = ImVec2(uvs.x, uvs.w); // UV at the outside of an edge + + ImVec2 solid_to_edge_delta_texels = edge_uv - solid_uv; // Delta between the solid/edge points in texel-space (we need this in pixels - or, to be more precise, to be at a 1:1 aspect ratio - for the rotation to work) + solid_to_edge_delta_texels.x *= (float)tex_width; + solid_to_edge_delta_texels.y *= (float)tex_height; + + // Our basic algorithm here is that we generate a straight section along each edge, and then either one or two curved corner triangles at the corners, + // which use an appropriate chunk of the texture to generate a smooth curve. + const int num_edges = points_count; + + // Normalize a vector +#define NORMALIZE(vec) ((vec) / ImLength((vec), 0.001f)) + + const int required_stack_mem = (num_edges * sizeof(ImVec2)) + (num_edges * sizeof(float)); + ImU8* base_mem_for_normals_and_edges = (ImU8*)alloca(required_stack_mem); + ImU8* mem_for_normals_and_edges = (ImU8*)base_mem_for_normals_and_edges; + + // Calculate edge normals + ImVec2* edge_normals = (ImVec2*)(void*)mem_for_normals_and_edges; + mem_for_normals_and_edges += num_edges * sizeof(ImVec2); + + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + ImVec2 edge_start = points[edge_index]; // No need to apply offset here because the normal is unaffected + ImVec2 edge_end = points[(edge_index + 1) % num_edges]; + ImVec2 edge_normal = NORMALIZE(ImVec2(edge_end.y - edge_start.y, -(edge_end.x - edge_start.x))); + edge_normals[edge_index] = edge_normal * (float)vertex_winding; // Flip normals for reverse winding + } + + // Pre-calculate edge scales + // We need to do this because we need the edge strips to have widths that match up with the corner sections, otherwise pixel cracking can occur along the boundaries + float* edge_size_scales = (float*)(void*)mem_for_normals_and_edges; + mem_for_normals_and_edges += num_edges * sizeof(float); + IM_ASSERT_PARANOID(mem_for_normals_and_edges == (base_mem_for_normals_and_edges + required_stack_mem)); // Check we used exactly what we allocated + + { + ImVec2 prev_edge_normal = edge_normals[num_edges - 1]; + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + ImVec2 edge_normal = edge_normals[edge_index]; + float cos_angle_coverage = ImDot(edge_normal, prev_edge_normal); + + if (cos_angle_coverage < 0.999999f) + { + // If we are covering more than 90 degrees we need an intermediate vertex to stop the required expansion tending towards infinity. + // And thus the effective angle will be halved (matches the similar code in loop below) + float angle_coverage = ImAcos(cos_angle_coverage); + if (cos_angle_coverage <= 0.0f) // -V1051 + angle_coverage *= 0.5f; + edge_size_scales[edge_index] = 1.0f / ImCos(angle_coverage * 0.5f); // How much we need to expand our size by to avoid clipping the corner of the texture off + } + else + { + edge_size_scales[edge_index] = 1.0f; // No corner, thus default scale + } + + prev_edge_normal = edge_normal; + } + } + + const int max_vertices = (4 + (3 * 2) + (is_filled ? 1 : 0)) * num_edges; // 4 vertices per edge plus 3*2 for potentially two corner triangles, plus one per vertex for fill + const int max_indices = ((6 + (3 * 2)) * num_edges) + (is_filled ? ((num_edges - 2) * 3) : 0); // 2 tris per edge plus up to two corner triangles, plus fill triangles + PrimReserve(max_indices, max_vertices); + ImDrawIdx* idx_write = _IdxWritePtr; + ImDrawVert* vtx_write = _VtxWritePtr; + ImDrawIdx current_idx = (ImDrawIdx)_VtxCurrentIdx; + + //ImVec2 previous_edge_start = points[0] + offset; + ImVec2 prev_edge_normal = edge_normals[num_edges - 1]; + ImVec2 edge_start = points[0] + shadow_offset; + + if (use_inset_distance) + edge_start -= NORMALIZE(edge_normals[0] + prev_edge_normal) * inset_distance; + + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + ImVec2 edge_end = points[(edge_index + 1) % num_edges] + shadow_offset; + ImVec2 edge_normal = edge_normals[edge_index]; + const float size_scale_start = edge_size_scales[edge_index]; + const float size_scale_end = edge_size_scales[(edge_index + 1) % num_edges]; + + if (use_inset_distance) + edge_end -= NORMALIZE(edge_normals[(edge_index + 1) % num_edges] + edge_normal) * inset_distance; + + // Add corner section + float cos_angle_coverage = ImDot(edge_normal, prev_edge_normal); + if (cos_angle_coverage < 0.999999f) // Don't fill if the corner is actually straight + { + // If we are covering more than 90 degrees we need an intermediate vertex to stop the required expansion tending towards infinity. + // And thus the effective angle has been halved (matches the similar code in loop above) + int num_steps = (cos_angle_coverage <= 0.0f) ? 2 : 1; + + for (int step = 0; step < num_steps; step++) + { + if (num_steps > 1) + { + if (step == 0) + edge_normal = NORMALIZE(edge_normal + prev_edge_normal); // Use half-way normal for first step + else + edge_normal = edge_normals[edge_index]; // Then use the "real" next edge normal for the second + + cos_angle_coverage = ImDot(edge_normal, prev_edge_normal); // Recalculate angle + } + + // Calculate UV for the section of the curved texture + + const float angle_coverage = ImAcos(cos_angle_coverage); + const float sin_angle_coverage = ImSin(angle_coverage); + + ImVec2 edge_delta = solid_to_edge_delta_texels; + edge_delta *= size_scale_start; + + ImVec2 rotated_edge_delta = ImVec2((edge_delta.x * cos_angle_coverage) + (edge_delta.y * sin_angle_coverage), (edge_delta.x * sin_angle_coverage) + (edge_delta.y * cos_angle_coverage)); + + // Convert from texels back into UV space + edge_delta.x *= inv_tex_width; + edge_delta.y *= inv_tex_height; + rotated_edge_delta.x *= inv_tex_width; + rotated_edge_delta.y *= inv_tex_height; + + ImVec2 expanded_edge_uv = solid_uv + edge_delta; + ImVec2 other_edge_uv = solid_uv + rotated_edge_delta; // Rotated UV to encompass the necessary section of the curve + + float expanded_thickness = shadow_thickness * size_scale_start; + + // Add a triangle to fill the corner + ImVec2 outer_edge_start = edge_start + (prev_edge_normal * expanded_thickness); + ImVec2 outer_edge_end = edge_start + (edge_normal * expanded_thickness); + + vtx_write->pos = edge_start; vtx_write->col = shadow_col; vtx_write->uv = solid_uv; vtx_write++; + vtx_write->pos = outer_edge_end; vtx_write->col = shadow_col; vtx_write->uv = expanded_edge_uv; vtx_write++; + vtx_write->pos = outer_edge_start; vtx_write->col = shadow_col; vtx_write->uv = other_edge_uv; vtx_write++; + + *(idx_write++) = current_idx; + *(idx_write++) = current_idx + 1; + *(idx_write++) = current_idx + 2; + current_idx += 3; + + prev_edge_normal = edge_normal; + } + } + + // Add section along edge + const float edge_length = ImLength(edge_end - edge_start, 0.0f); + if (edge_length > 0.00001f) // Don't try and process degenerate edges + { + ImVec2 outer_edge_start = edge_start + (edge_normal * shadow_thickness * size_scale_start); + ImVec2 outer_edge_end = edge_end + (edge_normal * shadow_thickness * size_scale_end); + ImVec2 scaled_edge_uv_start = solid_uv + ((edge_uv - solid_uv) * size_scale_start); + ImVec2 scaled_edge_uv_end = solid_uv + ((edge_uv - solid_uv) * size_scale_end); + + // Write vertices, inner first, then outer + vtx_write->pos = edge_start; vtx_write->col = shadow_col; vtx_write->uv = solid_uv; vtx_write++; + vtx_write->pos = edge_end; vtx_write->col = shadow_col; vtx_write->uv = solid_uv; vtx_write++; + vtx_write->pos = outer_edge_end; vtx_write->col = shadow_col; vtx_write->uv = scaled_edge_uv_end; vtx_write++; + vtx_write->pos = outer_edge_start; vtx_write->col = shadow_col; vtx_write->uv = scaled_edge_uv_start; vtx_write++; + + *(idx_write++) = current_idx; + *(idx_write++) = current_idx + 1; + *(idx_write++) = current_idx + 2; + *(idx_write++) = current_idx; + *(idx_write++) = current_idx + 2; + *(idx_write++) = current_idx + 3; + current_idx += 4; + } + + edge_start = edge_end; + } + + // Fill if requested + if (is_filled) + { + // Add vertices + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + vtx_write->pos = points[edge_index] + shadow_offset; + vtx_write->col = shadow_col; + vtx_write->uv = solid_uv; + vtx_write++; + } + + // Add triangles + for (int edge_index = 2; edge_index < num_edges; edge_index++) + { + *(idx_write++) = current_idx; + *(idx_write++) = (ImDrawIdx)(current_idx + edge_index - 1); + *(idx_write++) = (ImDrawIdx)(current_idx + edge_index); + } + + current_idx += (ImDrawIdx)num_edges; + } + + // Release any unused vertices/indices + int used_indices = (int)(idx_write - _IdxWritePtr); + int used_vertices = (int)(vtx_write - _VtxWritePtr); + _IdxWritePtr = idx_write; + _VtxWritePtr = vtx_write; + _VtxCurrentIdx = current_idx; + PrimUnreserve(max_indices - used_indices, max_vertices - used_vertices); +#undef NORMALIZE +} + +// Draw a shadow for a circular object +// Uses the draw path and so wipes any existing data there +void ImDrawList::AddShadowCircle(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, int num_segments) +{ + // Obtain segment count + if (num_segments <= 0) + { + // Automatic segment count + const int radius_idx = (int)obj_radius - 1; + if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts)) + num_segments = _Data->CircleSegmentCounts[radius_idx]; // Use cached value + else + num_segments = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(obj_radius, _Data->CircleTessellationMaxError); + } + else + { + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); + } + + // Generate a path describing the inner circle and copy it to our buffer + IM_ASSERT(_Path.Size == 0); + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + if (num_segments == 12) + PathArcToFast(obj_center, obj_radius, 0, 12 - 1); + else + PathArcTo(obj_center, obj_radius, 0.0f, a_max, num_segments - 1); + + // Draw the shadow using the convex shape code + AddShadowConvexPoly(_Path.Data, _Path.Size, shadow_col, shadow_thickness, shadow_offset, flags); + _Path.Size = 0; +} + +void ImDrawList::AddShadowNGon(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, int num_segments) +{ + IM_ASSERT(num_segments != 0); + AddShadowCircle(obj_center, obj_radius, shadow_col, shadow_thickness, shadow_offset, flags, num_segments); +} + //----------------------------------------------------------------------------- // [SECTION] ImDrawListSplitter //----------------------------------------------------------------------------- @@ -2683,6 +3430,10 @@ ImFontAtlas::ImFontAtlas() TexNextUniqueID = 1; FontNextUniqueID = 1; Builder = NULL; + + // FIXME-SHADOWS: move elsewhere? + ShadowRectIds[0] = ShadowRectIds[1] = -1; + ShadowTexConfig.SetupDefaults(); } ImFontAtlas::~ImFontAtlas() @@ -2741,6 +3492,9 @@ void ImFontAtlas::ClearInputData() font->Flags |= ImFontFlags_NoLoadGlyphs; } Sources.clear(); + + // FIXME-SHADOWS: Move elsewhere? + ShadowRectIds[0] = ShadowRectIds[1] = -1; } // Clear CPU-side copy of the texture data. @@ -3702,6 +4456,8 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) } } +static void ImFontAtlasBuildUpdateTexDataShadow(ImFontAtlas* atlas); // FIXME-SHADOWS: Move impl here. + //----------------------------------------------------------------------------------------------------------------------------- // Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() @@ -4091,6 +4847,7 @@ static void ImFontAtlasBuildUpdateTexData(ImFontAtlas* atlas) { ImFontAtlasBuildUpdateTexDataBasic(atlas); ImFontAtlasBuildUpdateTexDataLines(atlas); + ImFontAtlasBuildUpdateTexDataShadow(atlas); } // Create a new texture, discard previous one @@ -4324,6 +5081,259 @@ void ImFontAtlasTextureCompact(ImFontAtlas* atlas) ImFontAtlasTextureRepack(atlas, new_tex_size.x, new_tex_size.y); } +// Calculates the signed distance from sample_pos to the nearest point on the rectangle defined by rect_min->rect_max +static float DistanceFromRectangle(const ImVec2& sample_pos, const ImVec2& rect_min, const ImVec2& rect_max) +{ + ImVec2 rect_centre = (rect_min + rect_max) * 0.5f; + ImVec2 rect_half_size = (rect_max - rect_min) * 0.5f; + ImVec2 local_sample_pos = sample_pos - rect_centre; + ImVec2 axis_dist = ImVec2(ImFabs(local_sample_pos.x), ImFabs(local_sample_pos.y)) - rect_half_size; + float out_dist = ImLength(ImVec2(ImMax(axis_dist.x, 0.0f), ImMax(axis_dist.y, 0.0f)), 0.00001f); + float in_dist = ImMin(ImMax(axis_dist.x, axis_dist.y), 0.0f); + return out_dist + in_dist; +} + +// Calculates the signed distance from sample_pos to the point given +static float DistanceFromPoint(const ImVec2& sample_pos, const ImVec2& point) +{ + return ImLength(sample_pos - point, 0.0f); +} + +// Perform a single Gaussian blur pass with a fixed kernel size and sigma +static void GaussianBlurPass(float* src, float* dest, int size, bool horizontal) +{ + // See http://dev.theomader.com/gaussian-kernel-calculator/ + const float coefficients[] = { 0.0f, 0.0f, 0.000003f, 0.000229f, 0.005977f, 0.060598f, 0.24173f, 0.382925f, 0.24173f, 0.060598f, 0.005977f, 0.000229f, 0.000003f, 0.0f, 0.0f }; + const int kernel_size = IM_ARRAYSIZE(coefficients); + const int sample_step = horizontal ? 1 : size; + + float* read_ptr = src; + float* write_ptr = dest; + for (int y = 0; y < size; y++) + for (int x = 0; x < size; x++) + { + float result = 0.0f; + int current_offset = (horizontal ? x : y) - ((kernel_size - 1) >> 1); + float* sample_ptr = read_ptr - (((kernel_size - 1) >> 1) * sample_step); + for (int j = 0; j < kernel_size; j++) + { + if (current_offset >= 0 && current_offset < size) + result += (*sample_ptr) * coefficients[j]; + current_offset++; + sample_ptr += sample_step; + } + read_ptr++; + *(write_ptr++) = result; + } +} + +// Perform an in-place Gaussian blur of a square array of floats with a fixed kernel size and sigma +// Uses a stack allocation for the temporary data so potentially dangerous with large size values +static void GaussianBlur(float* data, int size) +{ + // Do two passes, one from data into temp and then the second back to data again + float* temp = (float*)alloca(size * size * sizeof(float)); + GaussianBlurPass(data, temp, size, true); + GaussianBlurPass(temp, data, size, false); +} + +// Generate the actual pixel data for rounded corners in the atlas +static void ImFontAtlasBuildUpdateTexDataShadow(ImFontAtlas* atlas) +{ + // The actual size we want to reserve, including padding + const ImFontAtlasShadowTexConfig* shadow_cfg = &atlas->ShadowTexConfig; + const unsigned int effective_size = shadow_cfg->CalcRectTexSize() + shadow_cfg->GetRectTexPadding(); + const int corner_size = shadow_cfg->TexCornerSize; + const int edge_size = shadow_cfg->TexEdgeSize; + + // Because of the blur, we have to generate the full 3x3 texture here, and then we chop that down to just the 2x2 section we need later. + // 'size' correspond to the our 3x3 size, whereas 'shadow_tex_size' correspond to our 2x2 version where duplicate mirrored corners are not stored. + + // The rectangular shadow texture + ImFontAtlasRect r; + bool add_and_draw = (atlas->GetCustomRect(atlas->ShadowRectIds[0], &r) == false); + if (add_and_draw) + { + atlas->ShadowRectIds[0] = atlas->AddCustomRect(effective_size, effective_size, &r); + IM_ASSERT(atlas->ShadowRectIds[0] != ImFontAtlasRectId_Invalid); + + const int size = shadow_cfg->TexCornerSize + shadow_cfg->TexEdgeSize + shadow_cfg->TexCornerSize; + + // The bounds of the rectangle we are generating the shadow from + const ImVec2 shadow_rect_min((float)corner_size, (float)corner_size); + const ImVec2 shadow_rect_max((float)(corner_size + edge_size), (float)(corner_size + edge_size)); + + // Remove the padding we added + const int padding = shadow_cfg->GetRectTexPadding(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w -= (unsigned short)padding * 2; + r.h -= (unsigned short)padding * 2; + + // Generate distance field + // We draw the actual texture content by evaluating the distance field for the inner rectangle + float* tex_data = (float*)alloca(size * size * sizeof(float)); + for (int y = 0; y < size; y++) + for (int x = 0; x < size; x++) + { + float dist = DistanceFromRectangle(ImVec2((float)x, (float)y), shadow_rect_min, shadow_rect_max); + float alpha = 1.0f - ImMin(ImMax(dist + shadow_cfg->TexDistanceFieldOffset, 0.0f) / ImMax(shadow_cfg->TexCornerSize + shadow_cfg->TexDistanceFieldOffset, 0.001f), 1.0f); + alpha = ImPow(alpha, shadow_cfg->TexFalloffPower); // Apply power curve to give a nicer falloff + tex_data[x + (y * size)] = alpha; + } + + // Blur + if (shadow_cfg->TexBlur) + GaussianBlur(tex_data, size); + + // Copy to texture, truncating to the actual required texture size (the bottom/right of the source data is chopped off, as we don't need it - see below). The truncated size is essentially the top 2x2 of our data, plus a little bit of padding for sampling. + ImTextureData* tex = atlas->TexData; + const int shadow_tex_size = shadow_cfg->CalcRectTexSize(); + for (int y = 0; y < shadow_tex_size; y++) + for (int x = 0; x < shadow_tex_size; x++) + { + const float alpha_f = tex_data[x + (y * size)]; + const unsigned char alpha_8 = (unsigned char)(0xFF * alpha_f); + + // FIXME-SHADOWS: May be optimized. + switch (atlas->TexData->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = alpha_8; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = IM_COL32(255, 255, 255, alpha_8);; + break; + } + } + } + } + + // Refresh UV coordinates + // Generate UVs for each of the nine sections, which are arranged in a 3x3 grid starting from 0 in the top-left and going across then down + if (atlas->GetCustomRect(atlas->ShadowRectIds[0], &r)) + { + // Remove the padding we added + const int padding = shadow_cfg->GetRectTexPadding(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w -= (unsigned short)padding * 2; + r.h -= (unsigned short)padding * 2; + + for (int i = 0; i < 9; i++) + { + // The third row/column of the 3x3 grid are generated by flipping the appropriate chunks of the upper 2x2 grid. + bool flip_h = false; // Do we need to flip the UVs horizontally? + bool flip_v = false; // Do we need to flip the UVs vertically? + + ImFontAtlasRect sub_rect = r; + switch (i % 3) + { + case 0: sub_rect.w = (unsigned short)corner_size; break; + case 1: sub_rect.x += (unsigned short)corner_size; sub_rect.w = (unsigned short)edge_size; break; + case 2: sub_rect.w = (unsigned short)corner_size; flip_h = true; break; + } + + switch (i / 3) + { + case 0: sub_rect.h = (unsigned short)corner_size; break; + case 1: sub_rect.y += (unsigned short)corner_size; sub_rect.h = (unsigned short)edge_size; break; + case 2: sub_rect.h = (unsigned short)corner_size; flip_v = true; break; + } + + // FIXME-SHADOWS: caching UV !! + ImVec2 uv0 = ImVec2((float)(sub_rect.x), (float)(sub_rect.y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(sub_rect.x + sub_rect.w), (float)(sub_rect.y + sub_rect.h)) * atlas->TexUvScale; + atlas->ShadowRectUvs[i] = ImVec4(flip_h ? uv1.x : uv0.x, flip_v ? uv1.y : uv0.y, flip_h ? uv0.x : uv1.x, flip_v ? uv0.y : uv1.y); + } + } + + // The convex shape shadow texture + add_and_draw = (atlas->GetCustomRect(atlas->ShadowRectIds[1], &r) == false); + if (add_and_draw) + { + atlas->ShadowRectIds[1] = atlas->AddCustomRect(shadow_cfg->CalcConvexTexWidth() + shadow_cfg->GetConvexTexPadding(), shadow_cfg->CalcConvexTexHeight() + shadow_cfg->GetConvexTexPadding(), &r); + IM_ASSERT(atlas->ShadowRectIds[1] != ImFontAtlasRectId_Invalid); + + const int size = shadow_cfg->TexCornerSize * 2; + const int padding = shadow_cfg->GetConvexTexPadding(); + + // Generate distance field + // We draw the actual texture content by evaluating the distance field for the distance from a center point + ImVec2 center_point(size * 0.5f, size * 0.5f); + float* tex_data = (float*)alloca(size * size * sizeof(float)); + for (int y = 0; y < size; y++) + for (int x = 0; x < size; x++) + { + float dist = DistanceFromPoint(ImVec2((float)x, (float)y), center_point); + float alpha = 1.0f - ImMin(ImMax((float)dist + shadow_cfg->TexDistanceFieldOffset, 0.0f) / ImMax((float)shadow_cfg->TexCornerSize + shadow_cfg->TexDistanceFieldOffset, 0.001f), 1.0f); + alpha = ImPow(alpha, shadow_cfg->TexFalloffPower); // Apply power curve to give a nicer falloff + tex_data[x + (y * size)] = alpha; + } + + // Blur + if (shadow_cfg->TexBlur) + GaussianBlur(tex_data, size); + + // Copy to texture, truncating to the actual required texture size (the bottom/right of the source data is chopped off, as we don't need it - see below) + // We push the data down and right by the amount we padded the top of the texture (see CalcConvexTexWidth/CalcConvexTexHeight) for details + const int padded_size = (int)(shadow_cfg->TexCornerSize / ImCos(IM_PI * 0.25f)); + const int src_x_offset = padding + (padded_size - shadow_cfg->TexCornerSize); + const int src_y_offset = padding + (padded_size - shadow_cfg->TexCornerSize); + + const int tex_width = shadow_cfg->CalcConvexTexWidth(); + const int tex_height = shadow_cfg->CalcConvexTexHeight(); + ImTextureData* tex = atlas->TexData; + for (int y = 0; y < tex_height; y++) + for (int x = 0; x < tex_width; x++) + { + const int src_x = ImClamp(x - src_x_offset, 0, size - 1); + const int src_y = ImClamp(y - src_y_offset, 0, size - 1); + const float alpha_f = tex_data[src_x + (src_y * size)]; + const unsigned char alpha_8 = (unsigned char)(0xFF * alpha_f); + + // FIXME-SHADOWS: May be optimized. + switch (atlas->TexData->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = alpha_8; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = IM_COL32(255, 255, 255, alpha_8);; + break; + } + } + } + } + + // Refresh UV coordinates + if (atlas->GetCustomRect(atlas->ShadowRectIds[1], &r)) + { + // Remove the padding we added + const int padding = shadow_cfg->GetConvexTexPadding(); + const int tex_width = shadow_cfg->CalcConvexTexWidth(); + const int tex_height = shadow_cfg->CalcConvexTexHeight(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w = (unsigned short)(tex_width - (padding * 2)); + r.h = (unsigned short)(tex_height - (padding * 2)); + + ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + r.w), (float)(r.y + r.h)) * atlas->TexUvScale; + atlas->ShadowRectUvs[9] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + } +} + // Start packing over current empty texture void ImFontAtlasBuildInit(ImFontAtlas* atlas) { diff --git a/imgui_internal.h b/imgui_internal.h index a248fc800..96f52bce3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -173,6 +173,7 @@ struct ImGuiOldColumns; // Storage data for a columns set for legacy struct ImGuiPopupData; // Storage for current popup stack struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it +struct ImGuiStyleShadowTexConfig; // Shadow Texture baking config struct ImGuiStyleVarInfo; // Style variable information (e.g. to access style variables from an enum) struct ImGuiTabBar; // Storage for a tab bar struct ImGuiTabItem; // Storage for a tab item (within a tab bar) @@ -530,6 +531,7 @@ inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } +inline float ImLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImSqrt(d); return fail_value; } inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; } inline float ImTrunc(float f) { return (float)(int)(f); } inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } @@ -909,6 +911,9 @@ struct IMGUI_API ImDrawListSharedData float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) + int* ShadowRectIds; // IDs of rects for shadow texture (2 entries) + const ImVec4* ShadowRectUvs; // UV coordinates for shadow texture (10 entries) + ImDrawListSharedData(); ~ImDrawListSharedData(); void SetCircleTessellationMaxError(float max_error); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0c6c31f5f..2403fdd5c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9423,10 +9423,14 @@ bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, Im } window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; + + // Create window + PushStyleColor(ImGuiCol_WindowShadow, ImVec4(0, 0, 0, 0)); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint bool is_open = Begin(name, NULL, window_flags); PopStyleVar(2); + PopStyleColor(); return is_open; } From 6d07f6eb09b8046269a94902d508f24c594db09c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 15:49:00 +0200 Subject: [PATCH 002/245] Selectable: fixed `ImGuiSelectableFlags_SelectOnNav` triggering during NavInit. Style Editor: fixed style/colors combo box applying style when opening Combo. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 4 +++- imgui_internal.h | 1 + imgui_widgets.cpp | 2 +- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c83710ec0..6ec0298bd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,8 @@ Other Changes: - Using <> scrolling buttons while the selected Tab is at either end of the section mid-section but not fully visible always makes it fully visible (before eventually selecting a Tab in the leading/trailing section) +- Selectable: + - Fixed `ImGuiSelectableFlags_SelectOnNav` triggering during NavInit. - Fonts: - Reworked `AddFontDefault()` to use `io.DisplayFrameBufferScale` as part of the heuristic to select `AddFontDefaultVector()` by default, effectively using ProggyForever instead of @@ -105,6 +107,7 @@ Other Changes: Currently only supported by the OpenGL2/3 and SDLRenderer3 backend. (#9378) - Demo: - Added `Widgets->Mixed Values` section. (#5518, #5677, #6865) + - Style Editor: fixed style/colors combo box applying style when opening Combo. - Backends: - QNX: added QNX Screen backend. (#9492) [@mgorchak-blackberry] - OpenGL2, OpenGL3: added support for `platform_io.DrawCallback_SetSamplerFromTex` draw diff --git a/imgui.cpp b/imgui.cpp index 9e5880ebd..c6decca34 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4337,7 +4337,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0; NavJustMovedToKeyMods = ImGuiMod_None; - NavJustMovedToIsTabbing = false; + NavJustMovedToIsTabbing = NavJustMovedToIsInit = false; NavJustMovedToHasSelectionData = false; // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... @@ -14174,6 +14174,7 @@ void ImGui::NavInitRequestApplyResult() g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = 0; g.NavJustMovedToIsTabbing = false; + g.NavJustMovedToIsInit = true; g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0; } @@ -14441,6 +14442,7 @@ void ImGui::NavMoveRequestApplyResult() g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = g.NavMoveKeyMods; g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0; + g.NavJustMovedToIsInit = false; g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0; //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId); } diff --git a/imgui_internal.h b/imgui_internal.h index a248fc800..4a3fdca18 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2445,6 +2445,7 @@ struct ImGuiContext ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). ImGuiKeyChord NavJustMovedToKeyMods; bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. + bool NavJustMovedToIsInit; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. // Navigation: extra config options (will be made public eventually) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0c6c31f5f..1f60853b6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7616,7 +7616,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope()) // - (2) usage will fail with clipped items // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. - if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId) + if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId && !g.NavJustMovedToIsInit) if (g.NavJustMovedToId == id && (g.NavJustMovedToKeyMods & ImGuiMod_Ctrl) == 0) selected = pressed = auto_selected = true; } From f09485d7bed3cc471d2a1310e4fa5b1693af03b7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 16:05:56 +0200 Subject: [PATCH 003/245] Style: inverted ImGuiCol_TitleBgXXX colors for StyleColorsLight(). So that the selected window title bar appears brighter. --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ec0298bd..c5c131930 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,9 @@ Other Changes: - Amended context menu right-click opening code to check that the right-click hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) +- Style: + - Inverted `ImGuiCol_TitleBgXXX` colors for `StyleColorsLight()` so that the selected + window title bar appears brighter. - Misc: - Added `ImGuiItemFlags_MixedValue` flag for representing mixed/indeterminate values. Supported by: Checkbox(), RadioButton(), DragXXX(), SliderXXX(), InputXXX(), ColorXXX() diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bf7aebad1..0e76fcefc 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -336,9 +336,9 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); - colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); - colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); - colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); + colors[ImGuiCol_TitleBg] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.43f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); From c8fc1829d0253edaa5b0e5c92a1e8f17b7d15f14 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 16:51:18 +0200 Subject: [PATCH 004/245] ImGuiTextFilter: minor tweaks, made ImGuiTextRange fields match upcoming ImStrv. Removed exposed ImGuiTextRange helpers. Rename CountGrep to CountInclude (#3906) Toward #2435 --- imgui.cpp | 36 ++++++++++++++++++------------------ imgui.h | 26 +++++++++++++------------- 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c6decca34..43594c4ab 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3093,7 +3093,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; - CountGrep = 0; + CountInclude = 0; if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf)); @@ -3111,7 +3111,7 @@ bool ImGuiTextFilter::Draw(const char* label, float width) return value_changed; } -void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector* out) const +static void ImStrSplit(const char* b, const char* e, char separator, ImVector* out) { out->resize(0); const char* wb = b; @@ -3120,32 +3120,32 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVectorpush_back(ImGuiTextRange(wb, we)); + out->push_back(ImGuiTextFilter::ImGuiTextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) - out->push_back(ImGuiTextRange(wb, we)); + out->push_back(ImGuiTextFilter::ImGuiTextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf)); - input_range.split(',', &Filters); + ImStrSplit(InputBuf, InputBuf + ImStrlen(InputBuf), ',', &Filters); - CountGrep = 0; + CountInclude = 0; for (ImGuiTextRange& f : Filters) { - while (f.b < f.e && ImCharIsBlankA(f.b[0])) - f.b++; - while (f.e > f.b && ImCharIsBlankA(f.e[-1])) - f.e--; - if (f.empty()) + while (f.Begin < f.End && ImCharIsBlankA(f.Begin[0])) + f.Begin++; + while (f.End > f.Begin && ImCharIsBlankA(f.End[-1])) + f.End--; + if (f.Begin == f.End) continue; - if (f.b[0] != '-') - CountGrep += 1; + if (f.Begin[0] != '-') + CountInclude += 1; } } @@ -3159,24 +3159,24 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const for (const ImGuiTextRange& f : Filters) { - if (f.b == f.e) + if (f.Begin == f.End) continue; - if (f.b[0] == '-') + if (f.Begin[0] == '-') { // Subtract - if (ImStristr(text, text_end, f.b + 1, f.e) != NULL) + if (ImStristr(text, text_end, f.Begin + 1, f.End) != NULL) return false; } else { // Grep - if (ImStristr(text, text_end, f.b, f.e) != NULL) + if (ImStristr(text, text_end, f.Begin, f.End) != NULL) return true; } } // Implicit * grep - if (CountGrep == 0) + if (CountInclude == 0) return true; return false; diff --git a/imgui.h b/imgui.h index fe8531083..a58e944ef 100644 --- a/imgui.h +++ b/imgui.h @@ -2789,26 +2789,26 @@ struct ImGuiOnceUponAFrame struct ImGuiTextFilter { IMGUI_API ImGuiTextFilter(const char* default_filter = ""); - IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; - IMGUI_API void Build(); - void Clear() { InputBuf[0] = 0; Build(); } - bool IsActive() const { return !Filters.empty(); } + IMGUI_API void Build(); // Update internal data when filter changes + inline void Clear() { InputBuf[0] = 0; Build(); } // Clear filter + inline bool IsActive() const { return Filters.Size != 0; } // Useful if you need e.g. an alternative code-path when there are no filters - // [Internal] + // Helper to call InputText() + Build() when buffer is changed. + IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); + + // [Internal] Don't use! Will be replaced with ImStrv. struct ImGuiTextRange { - const char* b; - const char* e; - - ImGuiTextRange() { b = e = NULL; } - ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; } - bool empty() const { return b == e; } - IMGUI_API void split(char separator, ImVector* out) const; + const char* Begin; + const char* End; + ImGuiTextRange(const char* b, const char* e) { Begin = b; End = e; } }; + + // [Internal] Members char InputBuf[256]; ImVectorFilters; - int CountGrep; + int CountInclude; }; // Helper: Growable text buffer for logging/accumulating text From f7ada78e32a1e0758ca209aba7f4ceb2fa9e5b7e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 17:38:24 +0200 Subject: [PATCH 005/245] ImGuiTextFilter: added DrawWithHint(). (#6206, #6395, #6447) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 8 +++++++- imgui.h | 3 ++- imgui_demo.cpp | 21 ++++++++++++++------- 4 files changed, 26 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c5c131930..3eecd0dba 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,9 @@ Other Changes: - Amended context menu right-click opening code to check that the right-click hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) +- ImGuiTextFilter: + - Added `DrawWithHint()` function. (#6206, #6395, #6447) + - Added a "incl,-excl" hint by default when the search field is empty. (#6206, #6395, #6447) - Style: - Inverted `ImGuiCol_TitleBgXXX` colors for `StyleColorsLight()` so that the selected window title bar appears brighter. diff --git a/imgui.cpp b/imgui.cpp index 43594c4ab..aabf2e942 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3105,7 +3105,13 @@ bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); - bool value_changed = ImGui::InputText(label, InputBuf, IM_COUNTOF(InputBuf)); + return DrawWithHint(label); +} + +// Use ImGui::SetNextItemWidth() manually if you want to use this. +bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) +{ + bool value_changed = ImGui::InputTextWithHint(label, hint, InputBuf, IM_COUNTOF(InputBuf)); if (value_changed) Build(); return value_changed; diff --git a/imgui.h b/imgui.h index a58e944ef..12b0dfb1b 100644 --- a/imgui.h +++ b/imgui.h @@ -2795,7 +2795,8 @@ struct ImGuiTextFilter inline bool IsActive() const { return Filters.Size != 0; } // Useful if you need e.g. an alternative code-path when there are no filters // Helper to call InputText() + Build() when buffer is changed. - IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); + IMGUI_API bool Draw(const char* label = "Filter", float width = 0.0f); + IMGUI_API bool DrawWithHint(const char* label = "Filter", const char* hint = "incl,-excl"); // [Internal] Don't use! Will be replaced with ImStrv. struct ImGuiTextRange diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7478a99ee..c5e0697aa 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1452,7 +1452,8 @@ static void DemoWindowWidgetsComboBoxes() filter.Clear(); } ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); - filter.Draw("##Filter", -FLT_MIN); + ImGui::SetNextItemWidth(-FLT_MIN); + filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); for (int n = 0; n < IM_COUNTOF(items); n++) { @@ -3945,7 +3946,8 @@ static void DemoWindowWidgetsTextFilter() " \"xxx\" display lines containing \"xxx\"\n" " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" " \"-xxx\" hide lines containing \"xxx\""); - filter.Draw(); + ImGui::SetNextItemWidth(-FLT_MIN); + filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; for (int i = 0; i < IM_COUNTOF(lines); i++) if (filter.PassFilter(lines[i])) @@ -8820,9 +8822,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SameLine(); SetNextItemWidth(GetFontSize() * 10); Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); SameLine(); Checkbox("Only Modified Colors", &output_only_modified); - static ImGuiTextFilter filter; - filter.Draw("Filter colors", GetFontSize() * 16); - static ImGuiColorEditFlags alpha_flags = 0; if (RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } SameLine(); if (RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } SameLine(); @@ -8832,6 +8831,10 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "Left-click on color square to open color picker,\n" "Right-click to open edit options menu."); + static ImGuiTextFilter filter; + SetNextItemWidth(-FLT_MIN); + filter.DrawWithHint("##FilterColors", "Filter Colors (incl,-excl)"); + SetNextWindowSizeConstraints(ImVec2(0.0f, GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); PushItemWidth(GetFontSize() * -12); @@ -9244,7 +9247,10 @@ struct ExampleAppConsole if (ImGui::Button("Options")) ImGui::OpenPopup("Options"); ImGui::SameLine(); - Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + + ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); + ImGui::SetNextItemWidth(-FLT_MIN); + Filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); ImGui::Separator(); // Reserve enough left-over height for 1 separator + 1 input text @@ -9579,7 +9585,8 @@ struct ExampleAppLog ImGui::SameLine(); bool copy = ImGui::Button("Copy"); ImGui::SameLine(); - Filter.Draw("Filter", -100.0f); + ImGui::SetNextItemWidth(-FLT_MIN); + Filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); ImGui::Separator(); From a14bebd948e021a7801a9d987f135332dc514519 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 17:50:29 +0200 Subject: [PATCH 006/245] (Breaking) ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`. (#6206, #6395, #6447) The reasoning is to (1) keep things consistent with DrawWithHint() without polluting the new function with width. (2) keep things consistent with other items. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 7 +++---- imgui.h | 5 ++++- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3eecd0dba..e0d1b70d8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,8 @@ Breaking Changes: favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. It is easier to tweak + this allows us to easily scale error threshold on high density screens. - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). +- ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: + prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - Backends: - DirectX12: Removed support for legacy `ImGui_ImplDX12_Init()` signature, which was obsoleted in 1.91.6 (December 2014), because it needed to forcefully disable support diff --git a/imgui.cpp b/imgui.cpp index aabf2e942..d41f4d3fa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -395,6 +395,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). - 2026/07/20 (1.92.9) - DragXXX, SliderXXX, InputScalar: with `ImGuiItemFlags_LiveEditOnInputScalar` now defaulting to being disabled: @@ -3101,11 +3102,9 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 } } -bool ImGuiTextFilter::Draw(const char* label, float width) +bool ImGuiTextFilter::Draw(const char* label) { - if (width != 0.0f) - ImGui::SetNextItemWidth(width); - return DrawWithHint(label); + return DrawWithHint(label, "incl,-excl"); } // Use ImGui::SetNextItemWidth() manually if you want to use this. diff --git a/imgui.h b/imgui.h index 12b0dfb1b..ce48dca17 100644 --- a/imgui.h +++ b/imgui.h @@ -2795,8 +2795,11 @@ struct ImGuiTextFilter inline bool IsActive() const { return Filters.Size != 0; } // Useful if you need e.g. an alternative code-path when there are no filters // Helper to call InputText() + Build() when buffer is changed. - IMGUI_API bool Draw(const char* label = "Filter", float width = 0.0f); + IMGUI_API bool Draw(const char* label = "Filter"); IMGUI_API bool DrawWithHint(const char* label = "Filter", const char* hint = "incl,-excl"); +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + inline bool Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); return Draw(label); } +#endif // [Internal] Don't use! Will be replaced with ImStrv. struct ImGuiTextRange From fc98dc4a72e196a4a3cb721861651ff882490cac Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 18:31:50 +0200 Subject: [PATCH 007/245] (Internal) ImGuiTextFilter: renaming ImGuiTextRange->ImGuiTextFilterItem, Filters->Items. (#2435) --- imgui.cpp | 26 +++++++++++++------------- imgui.h | 16 ++++++++-------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d41f4d3fa..b2bdf55f0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3094,7 +3094,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; - CountInclude = 0; + _CountInclude = 0; if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf)); @@ -3116,7 +3116,7 @@ bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) return value_changed; } -static void ImStrSplit(const char* b, const char* e, char separator, ImVector* out) +static void ImStrSplit(const char* b, const char* e, char separator, ImVector* out) { out->resize(0); const char* wb = b; @@ -3125,23 +3125,23 @@ static void ImStrSplit(const char* b, const char* e, char separator, ImVectorpush_back(ImGuiTextFilter::ImGuiTextRange(wb, we)); + out->push_back(ImGuiTextFilter::ImGuiTextFilterItem(wb, we)); wb = we + 1; } we++; } if (wb != we) - out->push_back(ImGuiTextFilter::ImGuiTextRange(wb, we)); + out->push_back(ImGuiTextFilter::ImGuiTextFilterItem(wb, we)); } void ImGuiTextFilter::Build() { - Filters.resize(0); - ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf)); - ImStrSplit(InputBuf, InputBuf + ImStrlen(InputBuf), ',', &Filters); + _Items.resize(0); + ImGuiTextFilterItem input_range(InputBuf, InputBuf + ImStrlen(InputBuf)); + ImStrSplit(InputBuf, InputBuf + ImStrlen(InputBuf), ',', &_Items); - CountInclude = 0; - for (ImGuiTextRange& f : Filters) + _CountInclude = 0; + for (ImGuiTextFilterItem& f : _Items) { while (f.Begin < f.End && ImCharIsBlankA(f.Begin[0])) f.Begin++; @@ -3150,19 +3150,19 @@ void ImGuiTextFilter::Build() if (f.Begin == f.End) continue; if (f.Begin[0] != '-') - CountInclude += 1; + _CountInclude += 1; } } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { - if (Filters.Size == 0) + if (_Items.Size == 0) return true; if (text == NULL) text = text_end = ""; - for (const ImGuiTextRange& f : Filters) + for (const ImGuiTextFilterItem& f : _Items) { if (f.Begin == f.End) continue; @@ -3181,7 +3181,7 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const } // Implicit * grep - if (CountInclude == 0) + if (_CountInclude == 0) return true; return false; diff --git a/imgui.h b/imgui.h index ce48dca17..786afe386 100644 --- a/imgui.h +++ b/imgui.h @@ -2792,7 +2792,7 @@ struct ImGuiTextFilter IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; IMGUI_API void Build(); // Update internal data when filter changes inline void Clear() { InputBuf[0] = 0; Build(); } // Clear filter - inline bool IsActive() const { return Filters.Size != 0; } // Useful if you need e.g. an alternative code-path when there are no filters + inline bool IsActive() const { return _Items.Size != 0; } // Useful if you need e.g. an alternative code-path when there are no filters // Helper to call InputText() + Build() when buffer is changed. IMGUI_API bool Draw(const char* label = "Filter"); @@ -2802,17 +2802,17 @@ struct ImGuiTextFilter #endif // [Internal] Don't use! Will be replaced with ImStrv. - struct ImGuiTextRange + struct ImGuiTextFilterItem { - const char* Begin; - const char* End; - ImGuiTextRange(const char* b, const char* e) { Begin = b; End = e; } + const char* Begin; + const char* End; + ImGuiTextFilterItem(const char* b, const char* e) { Begin = b; End = e; } }; // [Internal] Members - char InputBuf[256]; - ImVectorFilters; - int CountInclude; + char InputBuf[256]; // User input buffer + int _CountInclude; // >= 0 + ImVector _Items; // Pre-parsed, trimmed items }; // Helper: Growable text buffer for logging/accumulating text From 54f86be71ea73b457cf66db600ca881725030131 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 22:02:57 +0200 Subject: [PATCH 008/245] ImGuiTextFilter: fixed filtering when mixing "include" and "-exclude" keyword so that an "-exclude" match always filters out. (#2435) + fix typo in ImToUpper --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 71 +++++++++++++++++++++------------------------- imgui.h | 2 +- imgui_internal.h | 2 +- 4 files changed, 37 insertions(+), 40 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e0d1b70d8..672c24c30 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -84,6 +84,8 @@ Other Changes: hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) - ImGuiTextFilter: + - Fixed filtering when mixing "include" and "-exclude" keyword so that an "-exclude" + match always filters out. (#2435) [@kudaba, @ocornut] - Added `DrawWithHint()` function. (#6206, #6395, #6447) - Added a "incl,-excl" hint by default when the search field is empty. (#6206, #6395, #6447) - Style: diff --git a/imgui.cpp b/imgui.cpp index b2bdf55f0..8968a8f3f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3116,74 +3116,69 @@ bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) return value_changed; } -static void ImStrSplit(const char* b, const char* e, char separator, ImVector* out) +static void ImGuiTextFilter_BuildAddItem(ImGuiTextFilter* f, const char* word_b, const char* word_e) { - out->resize(0); - const char* wb = b; - const char* we = wb; - while (we < e) - { - if (*we == separator) - { - out->push_back(ImGuiTextFilter::ImGuiTextFilterItem(wb, we)); - wb = we + 1; - } - we++; - } - if (wb != we) - out->push_back(ImGuiTextFilter::ImGuiTextFilterItem(wb, we)); + // Trim (FIXME: UTF-8 support?) + while (word_b < word_e && ImCharIsBlankA(word_b[0])) + word_b++; + while (word_e > word_b && ImCharIsBlankA(word_e[-1])) + word_e--; + if (word_e - word_b <= 0) + return; + + // Add to list + // FIXME-OPT: on push_front(): as N is derived from user inputs we expect this to be fine. + const bool is_excl = (word_b[0] == '-'); + f->_Items.insert(is_excl ? f->_Items.Data : f->_Items.end(), ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); + if (!is_excl) + f->_CountInclude++; } void ImGuiTextFilter::Build() { + // Parse filters _Items.resize(0); - ImGuiTextFilterItem input_range(InputBuf, InputBuf + ImStrlen(InputBuf)); - ImStrSplit(InputBuf, InputBuf + ImStrlen(InputBuf), ',', &_Items); - _CountInclude = 0; - for (ImGuiTextFilterItem& f : _Items) + const char* buf_e = InputBuf + ImStrlen(InputBuf); + const char* word_b = InputBuf; + const char* word_e = word_b; + while (word_e < buf_e) { - while (f.Begin < f.End && ImCharIsBlankA(f.Begin[0])) - f.Begin++; - while (f.End > f.Begin && ImCharIsBlankA(f.End[-1])) - f.End--; - if (f.Begin == f.End) - continue; - if (f.Begin[0] != '-') - _CountInclude += 1; + if (*word_e == ',') + { + ImGuiTextFilter_BuildAddItem(this, word_b, word_e); + word_b = word_e + 1; + } + word_e++; } + ImGuiTextFilter_BuildAddItem(this, word_b, word_e); } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (_Items.Size == 0) return true; - if (text == NULL) text = text_end = ""; - for (const ImGuiTextFilterItem& f : _Items) + // Filters are sorted so that '-' ones are always leading. + for (const ImGuiTextFilterItem& item : _Items) { - if (f.Begin == f.End) - continue; - if (f.Begin[0] == '-') + if (item.Begin[0] == '-') { - // Subtract - if (ImStristr(text, text_end, f.Begin + 1, f.End) != NULL) + if (ImStristr(text, text_end, item.Begin + 1, item.End) != NULL) // Exclude return false; } else { - // Grep - if (ImStristr(text, text_end, f.Begin, f.End) != NULL) + if (ImStristr(text, text_end, item.Begin, item.End) != NULL) // Include return true; } } - // Implicit * grep + // When no inclusion are specified (only exclusions) we implicitly pass if (_CountInclude == 0) return true; - return false; } diff --git a/imgui.h b/imgui.h index 786afe386..d66f70d24 100644 --- a/imgui.h +++ b/imgui.h @@ -2812,7 +2812,7 @@ struct ImGuiTextFilter // [Internal] Members char InputBuf[256]; // User input buffer int _CountInclude; // >= 0 - ImVector _Items; // Pre-parsed, trimmed items + ImVector _Items; // Pre-parsed, trimmed, reordered items }; // Helper: Growable text buffer for logging/accumulating text diff --git a/imgui_internal.h b/imgui_internal.h index 4a3fdca18..8b6ffb796 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -407,7 +407,7 @@ IMGUI_API const char* ImStrSkipBlank(const char* str); IMGUI_API int ImStrlenW(const ImWchar* str); // Computer string length (ImWchar string) IMGUI_API const char* ImStrbol(const char* buf_mid_line, const char* buf_begin); // Find beginning-of-line IM_MSVC_RUNTIME_CHECKS_OFF -inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; } +inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c & ~32 : c; } inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } From c74e7e93a3e0b92bf5da4ebf63f05284c1d32c9b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 19:20:42 +0200 Subject: [PATCH 009/245] ImGuiTextFilter: Added support for space ' ' as separator. Added support for quoted "xxx" blocks. (#2435, #30) --- docs/CHANGELOG.txt | 4 ++- imgui.cpp | 66 ++++++++++++++++++++++++++-------------------- imgui.h | 4 +-- imgui_demo.cpp | 12 ++++----- 4 files changed, 49 insertions(+), 37 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 672c24c30..82c2ffe00 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -84,10 +84,12 @@ Other Changes: hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) - ImGuiTextFilter: + - Added support for space ' ' as separator, which is more standard. (#2435, #30) + - Added support for quoted "xxx" blocks to e.g. match words sequences. (#2435) - Fixed filtering when mixing "include" and "-exclude" keyword so that an "-exclude" match always filters out. (#2435) [@kudaba, @ocornut] - Added `DrawWithHint()` function. (#6206, #6395, #6447) - - Added a "incl,-excl" hint by default when the search field is empty. (#6206, #6395, #6447) + - Added a "incl -excl" hint by default when the search field is empty. (#6206, #6395, #6447) - Style: - Inverted `ImGuiCol_TitleBgXXX` colors for `StyleColorsLight()` so that the selected window title bar appears brighter. diff --git a/imgui.cpp b/imgui.cpp index 8968a8f3f..e0065362c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3090,7 +3090,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // [SECTION] ImGuiTextFilter //----------------------------------------------------------------------------- -// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +// Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; @@ -3104,7 +3104,7 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 bool ImGuiTextFilter::Draw(const char* label) { - return DrawWithHint(label, "incl,-excl"); + return DrawWithHint(label, "incl -excl"); } // Use ImGui::SetNextItemWidth() manually if you want to use this. @@ -3118,17 +3118,20 @@ bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) static void ImGuiTextFilter_BuildAddItem(ImGuiTextFilter* f, const char* word_b, const char* word_e) { - // Trim (FIXME: UTF-8 support?) - while (word_b < word_e && ImCharIsBlankA(word_b[0])) - word_b++; - while (word_e > word_b && ImCharIsBlankA(word_e[-1])) - word_e--; - if (word_e - word_b <= 0) + // Trim blanks + if (word_b < word_e && word_b[0] != '\"') + { + while (word_b < word_e && ImCharIsBlankA(word_b[0])) // FIXME: UTF-8 support + word_b++; + while (word_e > word_b && ImCharIsBlankA(word_e[-1])) + word_e--; + } + const bool is_excl = (word_b < word_e && word_b[0] == '-'); + if (word_e - word_b - (is_excl ? 1 : 0) <= 0) return; // Add to list - // FIXME-OPT: on push_front(): as N is derived from user inputs we expect this to be fine. - const bool is_excl = (word_b[0] == '-'); + // FIXME-OPT: about ~push_front(): as N is derived from user inputs we expect this to be fine. f->_Items.insert(is_excl ? f->_Items.Data : f->_Items.end(), ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); if (!is_excl) f->_CountInclude++; @@ -3140,18 +3143,26 @@ void ImGuiTextFilter::Build() _Items.resize(0); _CountInclude = 0; const char* buf_e = InputBuf + ImStrlen(InputBuf); - const char* word_b = InputBuf; - const char* word_e = word_b; - while (word_e < buf_e) + const char* word_e; + for (const char* word_b = InputBuf; word_b < buf_e; word_b = word_e + 1) { - if (*word_e == ',') + const bool is_excl = (word_b[0] == '-'); + if (word_b[0] == '\"' || (is_excl && word_b + 1 < buf_e && word_b[1] == '\"')) { - ImGuiTextFilter_BuildAddItem(this, word_b, word_e); - word_b = word_e + 1; + // Parsing "word". Store leading " to distinguish -"word" from "-word", but omit trailing ". + word_e = ImStrchrRange(word_b + (is_excl ? 2 : 1), buf_e, '\"'); + if (word_e == NULL) + word_e = buf_e; } - word_e++; + else + { + // Handle both ' ' and ',' separators. + for (word_e = word_b; word_e < buf_e; word_e++) + if (*word_e == ' ' || *word_e == ',') + break; + } + ImGuiTextFilter_BuildAddItem(this, word_b, word_e); } - ImGuiTextFilter_BuildAddItem(this, word_b, word_e); } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const @@ -3164,16 +3175,15 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const // Filters are sorted so that '-' ones are always leading. for (const ImGuiTextFilterItem& item : _Items) { - if (item.Begin[0] == '-') - { - if (ImStristr(text, text_end, item.Begin + 1, item.End) != NULL) // Exclude - return false; - } - else - { - if (ImStristr(text, text_end, item.Begin, item.End) != NULL) // Include - return true; - } + const char* word_b = item.Begin; + const char* word_e = item.End; + const bool is_excl = (word_b[0] == '-'); + if (is_excl) + word_b++; + if (word_b < word_e && word_b[0] == '\"') + word_b++; + if (ImStristr(text, text_end, word_b, word_e) != NULL) + return is_excl ? false : true; } // When no inclusion are specified (only exclusions) we implicitly pass diff --git a/imgui.h b/imgui.h index d66f70d24..20fb5fc96 100644 --- a/imgui.h +++ b/imgui.h @@ -2785,7 +2785,7 @@ struct ImGuiOnceUponAFrame operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; -// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +// Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. struct ImGuiTextFilter { IMGUI_API ImGuiTextFilter(const char* default_filter = ""); @@ -2796,7 +2796,7 @@ struct ImGuiTextFilter // Helper to call InputText() + Build() when buffer is changed. IMGUI_API bool Draw(const char* label = "Filter"); - IMGUI_API bool DrawWithHint(const char* label = "Filter", const char* hint = "incl,-excl"); + IMGUI_API bool DrawWithHint(const char* label = "Filter", const char* hint = "incl -excl"); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline bool Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); return Draw(label); } #endif diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c5e0697aa..5ef47f3af 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1453,7 +1453,7 @@ static void DemoWindowWidgetsComboBoxes() } ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); ImGui::SetNextItemWidth(-FLT_MIN); - filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); + filter.DrawWithHint("##Filter", "Filter (incl -excl)"); for (int n = 0; n < IM_COUNTOF(items); n++) { @@ -3947,7 +3947,7 @@ static void DemoWindowWidgetsTextFilter() " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" " \"-xxx\" hide lines containing \"xxx\""); ImGui::SetNextItemWidth(-FLT_MIN); - filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); + filter.DrawWithHint("##Filter", "Filter (incl -excl)"); const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; for (int i = 0; i < IM_COUNTOF(lines); i++) if (filter.PassFilter(lines[i])) @@ -8833,7 +8833,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) static ImGuiTextFilter filter; SetNextItemWidth(-FLT_MIN); - filter.DrawWithHint("##FilterColors", "Filter Colors (incl,-excl)"); + filter.DrawWithHint("##FilterColors", "Filter Colors (incl -excl)"); SetNextWindowSizeConstraints(ImVec2(0.0f, GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); @@ -9250,7 +9250,7 @@ struct ExampleAppConsole ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); ImGui::SetNextItemWidth(-FLT_MIN); - Filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); + Filter.DrawWithHint("##Filter", "Filter (incl -excl)"); ImGui::Separator(); // Reserve enough left-over height for 1 separator + 1 input text @@ -9586,7 +9586,7 @@ struct ExampleAppLog bool copy = ImGui::Button("Copy"); ImGui::SameLine(); ImGui::SetNextItemWidth(-FLT_MIN); - Filter.DrawWithHint("##Filter", "Filter (incl,-excl)"); + Filter.DrawWithHint("##Filter", "Filter (incl -excl)"); ImGui::Separator(); @@ -9781,7 +9781,7 @@ struct ExampleAppPropertyEditor ImGui::Text("(%d root nodes)", root_node->Childs.Size); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); - if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_COUNTOF(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) + if (ImGui::InputTextWithHint("##Filter", "incl -excl", Filter.InputBuf, IM_COUNTOF(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) Filter.Build(); ImGui::PopItemFlag(); From c0041b7d3c1e29dda8f173f54dbbe15b285ff62b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 19:29:02 +0200 Subject: [PATCH 010/245] ImGuiTextFilter: added undocumented MinWordSize support. (#2435) --- imgui.cpp | 3 ++- imgui.h | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index e0065362c..171097ef4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3094,6 +3094,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; + MinWordSize = 1; _CountInclude = 0; if (default_filter) { @@ -3127,7 +3128,7 @@ static void ImGuiTextFilter_BuildAddItem(ImGuiTextFilter* f, const char* word_b, word_e--; } const bool is_excl = (word_b < word_e && word_b[0] == '-'); - if (word_e - word_b - (is_excl ? 1 : 0) <= 0) + if (word_e - word_b - (is_excl ? 1 : 0) < f->MinWordSize) return; // Add to list diff --git a/imgui.h b/imgui.h index 20fb5fc96..c29e97d9d 100644 --- a/imgui.h +++ b/imgui.h @@ -2811,6 +2811,7 @@ struct ImGuiTextFilter // [Internal] Members char InputBuf[256]; // User input buffer + ImU8 MinWordSize; // == 1 int _CountInclude; // >= 0 ImVector _Items; // Pre-parsed, trimmed, reordered items }; From 565564bb5ce7ef0b194ed935e5d002d1ee499cd1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 20:41:16 +0200 Subject: [PATCH 011/245] ImGuiTextFilter: reworked items parsing/storage to be able to simplify PassFilter(). As PassFilter() is the bottleneck. --- imgui.cpp | 69 ++++++++++++++++++++++++------------------------------- imgui.h | 1 + 2 files changed, 31 insertions(+), 39 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 171097ef4..b017bcd5f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3095,7 +3095,7 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; MinWordSize = 1; - _CountInclude = 0; + _CountExclude = _CountInclude = 0; if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf)); @@ -3117,41 +3117,26 @@ bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) return value_changed; } -static void ImGuiTextFilter_BuildAddItem(ImGuiTextFilter* f, const char* word_b, const char* word_e) -{ - // Trim blanks - if (word_b < word_e && word_b[0] != '\"') - { - while (word_b < word_e && ImCharIsBlankA(word_b[0])) // FIXME: UTF-8 support - word_b++; - while (word_e > word_b && ImCharIsBlankA(word_e[-1])) - word_e--; - } - const bool is_excl = (word_b < word_e && word_b[0] == '-'); - if (word_e - word_b - (is_excl ? 1 : 0) < f->MinWordSize) - return; - - // Add to list - // FIXME-OPT: about ~push_front(): as N is derived from user inputs we expect this to be fine. - f->_Items.insert(is_excl ? f->_Items.Data : f->_Items.end(), ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); - if (!is_excl) - f->_CountInclude++; -} - +// Parse filter and split into items void ImGuiTextFilter::Build() { - // Parse filters _Items.resize(0); - _CountInclude = 0; + _CountExclude = _CountInclude = 0; const char* buf_e = InputBuf + ImStrlen(InputBuf); const char* word_e; for (const char* word_b = InputBuf; word_b < buf_e; word_b = word_e + 1) { - const bool is_excl = (word_b[0] == '-'); - if (word_b[0] == '\"' || (is_excl && word_b + 1 < buf_e && word_b[1] == '\"')) + // Trim blanks + while (word_b < buf_e && ImCharIsBlankA(word_b[0])) // FIXME: UTF-8 support + word_b++; + const bool is_excl = (word_b < buf_e && word_b[0] == '-'); + if (is_excl) + word_b++; + const bool is_quote = (word_b < buf_e && word_b[0] == '\"'); + if (is_quote) { - // Parsing "word". Store leading " to distinguish -"word" from "-word", but omit trailing ". - word_e = ImStrchrRange(word_b + (is_excl ? 2 : 1), buf_e, '\"'); + // Parsing quotes. Omit storing leading/trailing quotes. + word_e = ImStrchrRange(++word_b, buf_e, '\"'); if (word_e == NULL) word_e = buf_e; } @@ -3162,7 +3147,19 @@ void ImGuiTextFilter::Build() if (*word_e == ' ' || *word_e == ',') break; } - ImGuiTextFilter_BuildAddItem(this, word_b, word_e); + + // Min length + if (word_e - word_b < MinWordSize) + continue; + + // Add to list + // The '-' is not stored in items but implicitly inferred using (n < CountExclude). + // FIXME-OPT: about ~push_front(): as N is derived from user inputs we expect this to be fine. + _Items.insert(is_excl ? _Items.Data : _Items.Data + _Items.Size, ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); + if (is_excl) + _CountExclude++; + else + _CountInclude++; } } @@ -3174,17 +3171,11 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const text = text_end = ""; // Filters are sorted so that '-' ones are always leading. - for (const ImGuiTextFilterItem& item : _Items) + for (int n = 0; n < _Items.Size; n++) { - const char* word_b = item.Begin; - const char* word_e = item.End; - const bool is_excl = (word_b[0] == '-'); - if (is_excl) - word_b++; - if (word_b < word_e && word_b[0] == '\"') - word_b++; - if (ImStristr(text, text_end, word_b, word_e) != NULL) - return is_excl ? false : true; + const ImGuiTextFilterItem& item = _Items[n]; + if (ImStristr(text, text_end, item.Begin, item.End) != NULL) + return (n < _CountExclude) ? false : true; } // When no inclusion are specified (only exclusions) we implicitly pass diff --git a/imgui.h b/imgui.h index c29e97d9d..26afa5e7a 100644 --- a/imgui.h +++ b/imgui.h @@ -2812,6 +2812,7 @@ struct ImGuiTextFilter // [Internal] Members char InputBuf[256]; // User input buffer ImU8 MinWordSize; // == 1 + int _CountExclude; // >= 0 int _CountInclude; // >= 0 ImVector _Items; // Pre-parsed, trimmed, reordered items }; From 249e5a939dc6df0c31ac5d5a117ab27d3dc8ae2f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 21:04:32 +0200 Subject: [PATCH 012/245] ImGuiTextFilter: added undocumented FilterOp support. (#2435) --- imgui.cpp | 19 ++++++++++++++----- imgui.h | 1 + 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b017bcd5f..f9dc89e53 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3094,6 +3094,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; + FilterOp = '|'; MinWordSize = 1; _CountExclude = _CountInclude = 0; if (default_filter) @@ -3122,6 +3123,7 @@ void ImGuiTextFilter::Build() { _Items.resize(0); _CountExclude = _CountInclude = 0; + IM_ASSERT(FilterOp == '|' || FilterOp == '&'); const char* buf_e = InputBuf + ImStrlen(InputBuf); const char* word_e; for (const char* word_b = InputBuf; word_b < buf_e; word_b = word_e + 1) @@ -3171,17 +3173,24 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const text = text_end = ""; // Filters are sorted so that '-' ones are always leading. - for (int n = 0; n < _Items.Size; n++) + int n; + for (n = 0; n < _CountExclude; n++) + if (ImStristr(text, text_end, _Items.Data[n].Begin, _Items.Data[n].End) != NULL) + return false; + const bool is_and_filter = (FilterOp == '&'); + for (; n < _Items.Size; n++) { - const ImGuiTextFilterItem& item = _Items[n]; - if (ImStristr(text, text_end, item.Begin, item.End) != NULL) - return (n < _CountExclude) ? false : true; + const bool is_match = ImStristr(text, text_end, _Items.Data[n].Begin, _Items.Data[n].End) != NULL; + if (is_match && !is_and_filter) // or incl 1 -> true + return true; // or incl 0 -> continue + if (!is_match && is_and_filter) // and incl 1 -> continue + return false; // and incl 0 -> false } // When no inclusion are specified (only exclusions) we implicitly pass if (_CountInclude == 0) return true; - return false; + return is_and_filter; } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 26afa5e7a..2ad3b91fb 100644 --- a/imgui.h +++ b/imgui.h @@ -2811,6 +2811,7 @@ struct ImGuiTextFilter // [Internal] Members char InputBuf[256]; // User input buffer + char FilterOp; // == '|' (any) pr '&' (all) ImU8 MinWordSize; // == 1 int _CountExclude; // >= 0 int _CountInclude; // >= 0 From 420f1793417e39560ca39a4209c55a9f204fde13 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2026 22:26:25 +0200 Subject: [PATCH 013/245] Backends: fixed Clang -Wold-style-cast warnings. Amend 8e17468 --- backends/imgui_impl_dx10.cpp | 5 +++++ backends/imgui_impl_dx10.h | 3 +-- backends/imgui_impl_dx11.cpp | 5 +++++ backends/imgui_impl_dx11.h | 3 +-- backends/imgui_impl_dx12.cpp | 5 +++++ backends/imgui_impl_dx12.h | 3 +-- backends/imgui_impl_opengl3.cpp | 5 +++++ backends/imgui_impl_opengl3.h | 3 +-- backends/imgui_impl_sdlgpu3.cpp | 5 +++++ backends/imgui_impl_sdlgpu3.h | 3 +-- backends/imgui_impl_sdlrenderer2.cpp | 5 +++++ backends/imgui_impl_sdlrenderer2.h | 3 +-- backends/imgui_impl_sdlrenderer3.cpp | 5 +++++ backends/imgui_impl_sdlrenderer3.h | 3 +-- backends/imgui_impl_vulkan.cpp | 5 +++++ backends/imgui_impl_vulkan.h | 3 +-- backends/imgui_impl_wgpu.cpp | 5 +++++ backends/imgui_impl_wgpu.h | 3 +-- 18 files changed, 54 insertions(+), 18 deletions(-) diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index cb767d6ac..a81d81305 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -101,6 +101,11 @@ static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplDX10_RenderState* ImGui_ImplDX10_GetRenderState() +{ + return (ImGui_ImplDX10_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + // Functions static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device) { diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index 6f75693f0..3ab1669a9 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -46,7 +46,6 @@ struct ImGui_ImplDX10_RenderState //ID3D10SamplerState* SamplerLinear; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerLinear) //ID3D10SamplerState* SamplerNearest; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerNearest) }; - -static inline ImGui_ImplDX10_RenderState* ImGui_ImplDX10_GetRenderState() { return (ImGui_ImplDX10_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplDX10_RenderState* ImGui_ImplDX10_GetRenderState(); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index ff0a607c4..a7d2cdf73 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -103,6 +103,11 @@ static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplDX11_RenderState* ImGui_ImplDX11_GetRenderState() +{ + return (ImGui_ImplDX11_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + // Functions static void ImGui_ImplDX11_SetupRenderState(const ImDrawData* draw_data, ID3D11DeviceContext* device_ctx) { diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index 2fe392dfa..5fd8ddca9 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -48,7 +48,6 @@ struct ImGui_ImplDX11_RenderState //ID3D11SamplerState* SamplerLinear; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerLinear) //ID3D11SamplerState* SamplerNearest; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerNearest) }; - -static inline ImGui_ImplDX11_RenderState* ImGui_ImplDX11_GetRenderState() { return (ImGui_ImplDX11_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplDX11_RenderState* ImGui_ImplDX11_GetRenderState(); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index e5b314eb1..22a9bdc97 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -133,6 +133,11 @@ static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplDX12_RenderState* ImGui_ImplDX12_GetRenderState() +{ + return (ImGui_ImplDX12_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + // Buffers used during the rendering of a frame struct ImGui_ImplDX12_RenderBuffers { diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index a8f3a6cf6..106b4b4d2 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -74,8 +74,7 @@ struct ImGui_ImplDX12_RenderState ID3D12Device* Device; ID3D12GraphicsCommandList* CommandList; }; - -static inline ImGui_ImplDX12_RenderState* ImGui_ImplDX12_GetRenderState() { return (ImGui_ImplDX12_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplDX12_RenderState* ImGui_ImplDX12_GetRenderState(); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy initialization API Obsoleted in 1.91.5 diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 1d340f637..73dc349d8 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -276,6 +276,11 @@ static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplOpenGL3_RenderState* ImGui_ImplOpenGL3_GetRenderState() +{ + return (ImGui_ImplOpenGL3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + // OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only) #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY struct ImGui_ImplOpenGL3_VtxAttribState diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h index b5bcc7400..e1d999bd3 100644 --- a/backends/imgui_impl_opengl3.h +++ b/backends/imgui_impl_opengl3.h @@ -76,7 +76,6 @@ struct ImGui_ImplOpenGL3_RenderState unsigned int CurrentSampler; // (GLuint) Used if UseBindSampler == true (and are available), otherwise always 0 unsigned int CurrentTexParameterFilter; // (GLuint) Used if UseTexParameterFilter == true }; - -static inline ImGui_ImplOpenGL3_RenderState* ImGui_ImplOpenGL3_GetRenderState() { return (ImGui_ImplOpenGL3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplOpenGL3_RenderState* ImGui_ImplOpenGL3_GetRenderState(); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 53b47d434..2f6b25015 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -94,6 +94,11 @@ static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplSDLGPU3_RenderState* ImGui_ImplSDLGPU3_GetRenderState() +{ + return (ImGui_ImplSDLGPU3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index ce216fef0..a517c43b1 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -59,7 +59,6 @@ struct ImGui_ImplSDLGPU3_RenderState { SDL_GPUDevice* Device; }; - -static inline ImGui_ImplSDLGPU3_RenderState* ImGui_ImplSDLGPU3_GetRenderState() { return (ImGui_ImplSDLGPU3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplSDLGPU3_RenderState* ImGui_ImplSDLGPU3_GetRenderState(); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index e66150e57..d8dcfb154 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -76,6 +76,11 @@ static ImGui_ImplSDLRenderer2_Data* ImGui_ImplSDLRenderer2_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplSDLRenderer2_RenderState* ImGui_ImplSDLRenderer2_GetRenderState() +{ + return (ImGui_ImplSDLRenderer2_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + // Functions static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer) { diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h index 0c14912db..e16b8cae9 100644 --- a/backends/imgui_impl_sdlrenderer2.h +++ b/backends/imgui_impl_sdlrenderer2.h @@ -51,7 +51,6 @@ struct ImGui_ImplSDLRenderer2_RenderState { SDL_Renderer* Renderer; }; - -static inline ImGui_ImplSDLRenderer2_RenderState* ImGui_ImplSDLRenderer2_GetRenderState() { return (ImGui_ImplSDLRenderer2_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplSDLRenderer2_RenderState* ImGui_ImplSDLRenderer2_GetRenderState(); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 121ce59c8..6dd4c14fe 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -81,6 +81,11 @@ static ImGui_ImplSDLRenderer3_Data* ImGui_ImplSDLRenderer3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplSDLRenderer3_RenderState* ImGui_ImplSDLRenderer3_GetRenderState() +{ + return (ImGui_ImplSDLRenderer3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + // Functions static void ImGui_ImplSDLRenderer3_SetupRenderState(SDL_Renderer* renderer) { diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index 019def26a..ee701be38 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -51,7 +51,6 @@ struct ImGui_ImplSDLRenderer3_RenderState SDL_Renderer* Renderer; SDL_ScaleMode CurrentScaleMode; // Current scale mode during render. Set to SDL_SCALEMODE_INVALID to use "SetSamplerFromTex" mode. }; - -static inline ImGui_ImplSDLRenderer3_RenderState* ImGui_ImplSDLRenderer3_GetRenderState() { return (ImGui_ImplSDLRenderer3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplSDLRenderer3_RenderState* ImGui_ImplSDLRenderer3_GetRenderState(); #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 9eca9a767..80b9d58ab 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -459,6 +459,11 @@ static ImGui_ImplVulkan_Data* ImGui_ImplVulkan_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplVulkan_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplVulkan_RenderState* ImGui_ImplVulkan_GetRenderState() +{ + return (ImGui_ImplVulkan_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + #ifdef IMGUI_IMPL_VULKAN_USE_LOADER // Get the Vulkan function pointers used by the current backend. // If no backend is available, return the currently loaded global function pointers (ImGuiImplVulkanFuncs). diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index a48dae3ec..0f2da5e2d 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -175,8 +175,7 @@ struct ImGui_ImplVulkan_RenderState VkPipeline Pipeline; VkPipelineLayout PipelineLayout; }; - -static inline ImGui_ImplVulkan_RenderState* ImGui_ImplVulkan_GetRenderState() { return (ImGui_ImplVulkan_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplVulkan_RenderState* ImGui_ImplVulkan_GetRenderState(); //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index bdc4d434b..002967b92 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -129,6 +129,11 @@ static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +ImGui_ImplWGPU_RenderState* ImGui_ImplWGPU_GetRenderState() +{ + return (ImGui_ImplWGPU_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; +} + //----------------------------------------------------------------------------- // SHADERS //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index a5867c923..9f206db32 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -81,8 +81,7 @@ struct ImGui_ImplWGPU_RenderState WGPUDevice Device; WGPURenderPassEncoder RenderPassEncoder; }; - -static inline ImGui_ImplWGPU_RenderState* ImGui_ImplWGPU_GetRenderState() { return (ImGui_ImplWGPU_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } +IMGUI_IMPL_API ImGui_ImplWGPU_RenderState* ImGui_ImplWGPU_GetRenderState(); //------------------------------------------------------------------------- // Internal Helpers From d5c68c301a3d564e54051a7a78ee7858c4b821fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2026 14:16:55 +0200 Subject: [PATCH 014/245] ImGuiTextFilter: reworked filter to make space an AND operator. Demo: tweaked demo. Removed FilterOp, MinWordSize added a few commits ago. --- docs/CHANGELOG.txt | 6 ++-- imgui.cpp | 78 ++++++++++++++++++++++++++++------------------ imgui.h | 14 ++++----- imgui_demo.cpp | 23 +++++++++----- 4 files changed, 73 insertions(+), 48 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 82c2ffe00..ca1e27e49 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -84,8 +84,10 @@ Other Changes: hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) - ImGuiTextFilter: - - Added support for space ' ' as separator, which is more standard. (#2435, #30) - - Added support for quoted "xxx" blocks to e.g. match words sequences. (#2435) + - Added support for space as an "and" filter, which is the standard. (#2435, #30) + e.g. w/ filter 'hello world' (without quotes) both words needs to be in input data. + - Added support for double-quoted "xxx" blocks to e.g. match words sequences. (#2435) + e.g. w/ filter "hello world" the exact sequence needs to be in input data. - Fixed filtering when mixing "include" and "-exclude" keyword so that an "-exclude" match always filters out. (#2435) [@kudaba, @ocornut] - Added `DrawWithHint()` function. (#6206, #6395, #6447) diff --git a/imgui.cpp b/imgui.cpp index f9dc89e53..7e353df8f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3094,9 +3094,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; - FilterOp = '|'; - MinWordSize = 1; - _CountExclude = _CountInclude = 0; + _CountExclude = 0; if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf)); @@ -3118,14 +3116,15 @@ bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) return value_changed; } -// Parse filter and split into items +// Parse filter and split into a format optimal for PassFilter() void ImGuiTextFilter::Build() { _Items.resize(0); - _CountExclude = _CountInclude = 0; - IM_ASSERT(FilterOp == '|' || FilterOp == '&'); + _CountExclude = 0; + const char* buf_e = InputBuf + ImStrlen(InputBuf); const char* word_e; + int seq_incl_start_idx = -1; for (const char* word_b = InputBuf; word_b < buf_e; word_b = word_e + 1) { // Trim blanks @@ -3151,20 +3150,33 @@ void ImGuiTextFilter::Build() } // Min length - if (word_e - word_b < MinWordSize) - continue; + if (word_e - word_b > 0) + { + // Add to list. The '-' is not stored in items but implicitly inferred using (n < CountExclude). + // FIXME-OPT: as items are derived from user input buffer and we expect the insert() to behave sanely. + if (is_excl) + { + _Items.insert(_Items.Data + _CountExclude, ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); + _CountExclude++; + if (seq_incl_start_idx != -1) + seq_incl_start_idx++; + } + else + { + if (seq_incl_start_idx == -1) + seq_incl_start_idx = _Items.Size; + _Items.insert(_Items.Data + _Items.Size, ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); + _Items.Data[seq_incl_start_idx].CountInclude++; + } + } - // Add to list - // The '-' is not stored in items but implicitly inferred using (n < CountExclude). - // FIXME-OPT: about ~push_front(): as N is derived from user inputs we expect this to be fine. - _Items.insert(is_excl ? _Items.Data : _Items.Data + _Items.Size, ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); - if (is_excl) - _CountExclude++; - else - _CountInclude++; + // Next sequence + if (word_e[0] == ',') + seq_incl_start_idx = -1; } } +// FIXME: Could use a specialized ImStristr() + pre-convert our filter to uppercase. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (_Items.Size == 0) @@ -3173,24 +3185,28 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const text = text_end = ""; // Filters are sorted so that '-' ones are always leading. - int n; - for (n = 0; n < _CountExclude; n++) - if (ImStristr(text, text_end, _Items.Data[n].Begin, _Items.Data[n].End) != NULL) + ImGuiTextFilterItem* seq = _Items.Data; + ImGuiTextFilterItem* seq_excl_end = _Items.Data + _CountExclude; + for (; seq < seq_excl_end; seq++) + if (ImStristr(text, text_end, seq->Begin, seq->Begin + seq->Len) != NULL) return false; - const bool is_and_filter = (FilterOp == '&'); - for (; n < _Items.Size; n++) - { - const bool is_match = ImStristr(text, text_end, _Items.Data[n].Begin, _Items.Data[n].End) != NULL; - if (is_match && !is_and_filter) // or incl 1 -> true - return true; // or incl 0 -> continue - if (!is_match && is_and_filter) // and incl 1 -> continue - return false; // and incl 0 -> false - } - // When no inclusion are specified (only exclusions) we implicitly pass - if (_CountInclude == 0) + // Process includes + ImGuiTextFilterItem* seq_incl_end = _Items.Data + _Items.Size; + if (seq == seq_incl_end) // When no inclusion are specified (only exclusions) we implicitly pass return true; - return is_and_filter; + while (seq < seq_incl_end) + { + ImGuiTextFilterItem* seq_next = seq + seq->CountInclude; + IM_ASSERT_PARANOID(seq->CountInclude > 0 && seq_next <= seq_incl_end); + for (; seq < seq_next; seq++) + if (ImStristr(text, text_end, seq->Begin, seq->Begin + seq->Len) == NULL) + break; + if (seq == seq_next) // All matched + return true; + seq = seq_next; // Try next + } + return false; } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 2ad3b91fb..1e0ce7dcc 100644 --- a/imgui.h +++ b/imgui.h @@ -2785,7 +2785,7 @@ struct ImGuiOnceUponAFrame operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; -// Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. +// Helper: Parse and apply text filters e.g. 'aaa bbb' (all), 'aaa,bbb' (any), '-aaa' (exclude), '"Hello, world"' (exact sequence) struct ImGuiTextFilter { IMGUI_API ImGuiTextFilter(const char* default_filter = ""); @@ -2801,20 +2801,18 @@ struct ImGuiTextFilter inline bool Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); return Draw(label); } #endif - // [Internal] Don't use! Will be replaced with ImStrv. + // [Internal] Types struct ImGuiTextFilterItem { const char* Begin; - const char* End; - ImGuiTextFilterItem(const char* b, const char* e) { Begin = b; End = e; } + int Len; + int CountInclude; // >0 when beginning of an AND chain. + ImGuiTextFilterItem(const char* b, const char* e) { IM_ASSERT(e > b); Begin = b; Len = (int)(e - b); CountInclude = 0; } }; // [Internal] Members char InputBuf[256]; // User input buffer - char FilterOp; // == '|' (any) pr '&' (all) - ImU8 MinWordSize; // == 1 - int _CountExclude; // >= 0 - int _CountInclude; // >= 0 + int _CountExclude; // >= 0 count of leading exclude ImVector _Items; // Pre-parsed, trimmed, reordered items }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5ef47f3af..0b16dab3c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3943,15 +3943,24 @@ static void DemoWindowWidgetsTextFilter() static ImGuiTextFilter filter; ImGui::Text("Filter usage:\n" " \"\" display all lines\n" - " \"xxx\" display lines containing \"xxx\"\n" - " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" - " \"-xxx\" hide lines containing \"xxx\""); + " xxx display lines containing \"xxx\"\n" + " xxx yyy display lines containing \"xxx\" and \"yyy\"\n" + " \"xxx yyy\" display lines containing \"xxx yyy\"\n" + " xxx,yyy display lines containing \"xxx\" or \"yyy\"\n" + " -xxx hide lines containing \"xxx\""); ImGui::SetNextItemWidth(-FLT_MIN); filter.DrawWithHint("##Filter", "Filter (incl -excl)"); - const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; - for (int i = 0; i < IM_COUNTOF(lines); i++) - if (filter.PassFilter(lines[i])) - ImGui::BulletText("%s", lines[i]); + if (ImGui::BeginChild("##items", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 15), ImGuiChildFlags_FrameStyle)) + { + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (const char* item : lines) + if (filter.PassFilter(item)) + ImGui::TextUnformatted(item); + for (const char* item : ExampleNames) + if (filter.PassFilter(item)) + ImGui::TextUnformatted(item); + } + ImGui::EndChild(); ImGui::TreePop(); } } From e19fea020f69e97e420f32d80f8f1dc7e829dc2c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2026 15:12:59 +0200 Subject: [PATCH 015/245] ImGuiTextFilter: moved ImGuiTextFilterItem to internals. (#2435) --- imgui.cpp | 4 ++-- imgui.h | 16 ++++------------ imgui_internal.h | 10 ++++++++++ 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7e353df8f..b3cb17a17 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3156,7 +3156,7 @@ void ImGuiTextFilter::Build() // FIXME-OPT: as items are derived from user input buffer and we expect the insert() to behave sanely. if (is_excl) { - _Items.insert(_Items.Data + _CountExclude, ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); + _Items.insert(_Items.Data + _CountExclude, ImGuiTextFilterItem(word_b, word_e)); _CountExclude++; if (seq_incl_start_idx != -1) seq_incl_start_idx++; @@ -3165,7 +3165,7 @@ void ImGuiTextFilter::Build() { if (seq_incl_start_idx == -1) seq_incl_start_idx = _Items.Size; - _Items.insert(_Items.Data + _Items.Size, ImGuiTextFilter::ImGuiTextFilterItem(word_b, word_e)); + _Items.insert(_Items.Data + _Items.Size, ImGuiTextFilterItem(word_b, word_e)); _Items.Data[seq_incl_start_idx].CountInclude++; } } diff --git a/imgui.h b/imgui.h index 1e0ce7dcc..a108888a2 100644 --- a/imgui.h +++ b/imgui.h @@ -2786,6 +2786,7 @@ struct ImGuiOnceUponAFrame }; // Helper: Parse and apply text filters e.g. 'aaa bbb' (all), 'aaa,bbb' (any), '-aaa' (exclude), '"Hello, world"' (exact sequence) +struct ImGuiTextFilterItem; struct ImGuiTextFilter { IMGUI_API ImGuiTextFilter(const char* default_filter = ""); @@ -2801,19 +2802,10 @@ struct ImGuiTextFilter inline bool Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); return Draw(label); } #endif - // [Internal] Types - struct ImGuiTextFilterItem - { - const char* Begin; - int Len; - int CountInclude; // >0 when beginning of an AND chain. - ImGuiTextFilterItem(const char* b, const char* e) { IM_ASSERT(e > b); Begin = b; Len = (int)(e - b); CountInclude = 0; } - }; - - // [Internal] Members + // Members char InputBuf[256]; // User input buffer - int _CountExclude; // >= 0 count of leading exclude - ImVector _Items; // Pre-parsed, trimmed, reordered items + int _CountExclude; // [Internal] >= 0 count of leading exclude + ImVector _Items; // [Internal] Pre-parsed, trimmed, reordered items }; // Helper: Growable text buffer for logging/accumulating text diff --git a/imgui_internal.h b/imgui_internal.h index 8b6ffb796..15d2513aa 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -368,6 +368,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer // - Helper: ImPool<> // - Helper: ImChunkStream<> // - Helper: ImGuiTextIndex +// - Helper: ImGuiTextFilterItem // - Helper: ImGuiStorage //----------------------------------------------------------------------------- @@ -836,6 +837,15 @@ struct ImGuiTextIndex void append(const char* base, int old_size, int new_size); }; +// [Internal] Types +struct ImGuiTextFilterItem +{ + const char* Begin; + int Len; + int CountInclude; // >0 when beginning of an AND chain. + ImGuiTextFilterItem(const char* b, const char* e) { IM_ASSERT(e > b); Begin = b; Len = (int)(e - b); CountInclude = 0; } +}; + // Helper: ImGuiPackedDate (sizeof() == 2) // Store a date in a way that is efficient to read/write in text form. If we stored e.g. number of days since Epoch we'd need costlier back and forth. // This is specifically designed to be able to prune old .ini data. From 6cf8332f93ac2acbba03112171d44396730a74f9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2026 16:52:48 +0200 Subject: [PATCH 016/245] ImGuiTextFilterItem: added MatchIncludesMask support field for e.g. ImGuiTextFilterMultiMatch. --- imgui_internal.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 15d2513aa..77fd38256 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -840,10 +840,11 @@ struct ImGuiTextIndex // [Internal] Types struct ImGuiTextFilterItem { - const char* Begin; - int Len; - int CountInclude; // >0 when beginning of an AND chain. - ImGuiTextFilterItem(const char* b, const char* e) { IM_ASSERT(e > b); Begin = b; Len = (int)(e - b); CountInclude = 0; } + const char* Begin; // Pointer within parent's buffer + int Len; // Length of text (non-zero terminated) + short CountInclude; // Number of consecutive items forming an end chain. >0 when beginning of an AND chain, =0 otherwise. + unsigned short MatchIncludesMask; // Storage for multi-sources versions of PassFilter(). Unused by core library. + ImGuiTextFilterItem(const char* b, const char* e) { IM_ASSERT(e > b); Begin = b; Len = (int)(e - b); CountInclude = 0; MatchIncludesMask = 0; } }; // Helper: ImGuiPackedDate (sizeof() == 2) From 58d7570b8bbbfdcade40799812da9c7162e13498 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2026 18:23:26 +0200 Subject: [PATCH 017/245] ImGuiTextFilterItem: shallow renames. --- imgui.cpp | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b3cb17a17..7bbfa72bd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3124,7 +3124,7 @@ void ImGuiTextFilter::Build() const char* buf_e = InputBuf + ImStrlen(InputBuf); const char* word_e; - int seq_incl_start_idx = -1; + int seq_start_idx = -1; for (const char* word_b = InputBuf; word_b < buf_e; word_b = word_e + 1) { // Trim blanks @@ -3158,21 +3158,21 @@ void ImGuiTextFilter::Build() { _Items.insert(_Items.Data + _CountExclude, ImGuiTextFilterItem(word_b, word_e)); _CountExclude++; - if (seq_incl_start_idx != -1) - seq_incl_start_idx++; + if (seq_start_idx != -1) + seq_start_idx++; } else { - if (seq_incl_start_idx == -1) - seq_incl_start_idx = _Items.Size; + if (seq_start_idx == -1) + seq_start_idx = _Items.Size; _Items.insert(_Items.Data + _Items.Size, ImGuiTextFilterItem(word_b, word_e)); - _Items.Data[seq_incl_start_idx].CountInclude++; + _Items.Data[seq_start_idx].CountInclude++; } } // Next sequence if (word_e[0] == ',') - seq_incl_start_idx = -1; + seq_start_idx = -1; } } @@ -3192,19 +3192,19 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const return false; // Process includes - ImGuiTextFilterItem* seq_incl_end = _Items.Data + _Items.Size; - if (seq == seq_incl_end) // When no inclusion are specified (only exclusions) we implicitly pass + ImGuiTextFilterItem* seq_end = _Items.Data + _Items.Size; + if (seq == seq_end) // When no inclusion are specified (only exclusions) we implicitly pass return true; - while (seq < seq_incl_end) + while (seq < seq_end) { - ImGuiTextFilterItem* seq_next = seq + seq->CountInclude; - IM_ASSERT_PARANOID(seq->CountInclude > 0 && seq_next <= seq_incl_end); - for (; seq < seq_next; seq++) + ImGuiTextFilterItem* seq_incl_end = seq + seq->CountInclude; + IM_ASSERT_PARANOID(seq->CountInclude > 0 && seq_incl_end <= seq_end); + for (; seq < seq_incl_end; seq++) if (ImStristr(text, text_end, seq->Begin, seq->Begin + seq->Len) == NULL) break; - if (seq == seq_next) // All matched + if (seq == seq_incl_end) // All matched return true; - seq = seq_next; // Try next + seq = seq_incl_end; // Try next } return false; } From d12321803d168099245da64fbe57e7f767f744b2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Sep 2026 15:57:40 +0200 Subject: [PATCH 018/245] Popups: reworked GetMousePosOnOpeningCurrentPopup() to be legal to call within the BeginPopup/EndPopup scope of a popup which was just closed. (#9551) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 3 +-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ca1e27e49..07cf3ec9c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,8 @@ Other Changes: - Amended context menu right-click opening code to check that the right-click hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) + - Reworked `GetMousePosOnOpeningCurrentPopup()` to be legal to call within + the BeginPopup/EndPopup scope of a popup which was just closed. (#9551) [@jkunstwald] - ImGuiTextFilter: - Added support for space as an "and" filter, which is the standard. (#2435, #30) e.g. w/ filter 'hello world' (without quotes) both words needs to be in input data. diff --git a/imgui.cpp b/imgui.cpp index 7bbfa72bd..f7d9bfa91 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10269,12 +10269,11 @@ void ImGui::TeleportMousePos(const ImVec2& pos) //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y); } -// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.BeginPopupStack.Size > 0) - return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; + return g.BeginPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; return g.IO.MousePos; } From 7bfc19281459c67863d4615c56152567bb98c773 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Sep 2026 16:48:51 +0200 Subject: [PATCH 019/245] Tables: tweak struct packing. --- docs/CHANGELOG.txt | 4 ++-- imgui_internal.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 07cf3ec9c..ff7c4d265 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,8 +83,8 @@ Other Changes: - Amended context menu right-click opening code to check that the right-click hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) - - Reworked `GetMousePosOnOpeningCurrentPopup()` to be legal to call within - the BeginPopup/EndPopup scope of a popup which was just closed. (#9551) [@jkunstwald] + - Reworked `GetMousePosOnOpeningCurrentPopup()` to be legal to call within the + BeginPopup/EndPopup scope of a popup which was just closed. (#9551) [@jkunstwald] - ImGuiTextFilter: - Added support for space as an "and" filter, which is the standard. (#2435, #30) e.g. w/ filter 'hello world' (without quotes) both words needs to be in input data. diff --git a/imgui_internal.h b/imgui_internal.h index 77fd38256..17925f2f8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3137,9 +3137,9 @@ struct IMGUI_API ImGuiTable ImDrawListSplitter* DrawSplitter; // Shortcut to TempData->DrawSplitter while in table. Isolate draw commands per columns to avoid switching clip rect constantly ImGuiTableInstanceData InstanceDataFirst; ImVector InstanceDataExtra; // FIXME-OPT: Using a small-vector pattern would be good. - ImGuiTableColumnSortSpecs SortSpecsSingle; - ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() + ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. + ImGuiTableColumnSortSpecs SortSpecsSingle; ImGuiTableColumnIdx SortSpecsCount; ImGuiTableColumnIdx ColumnsEnabledCount; // Number of enabled columns (<= ColumnsCount) ImGuiTableColumnIdx ColumnsEnabledFixedCount; // Number of enabled columns using fixed width (<= ColumnsCount) From a6784c378fb59d0cdee51b08b09fbd8ec9d01d95 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Sep 2026 16:54:13 +0200 Subject: [PATCH 020/245] Tables: fixed reconcile path being needlessly taken on first frame of every table. (#9108) --- imgui_internal.h | 1 + imgui_tables.cpp | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 17925f2f8..97158497b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3171,6 +3171,7 @@ struct IMGUI_API ImGuiTable ImS8 NavLayer; // ImGuiNavLayer at the time of BeginTable(). bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). + bool IsNewTable; bool IsInitializing; bool IsReconcileMode; bool IsSortSpecsDirty; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index fb1b998d0..eba5b12e2 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -375,7 +375,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG const int previous_frame_active = table->LastFrameActive; const int instance_no = (previous_frame_active != g.FrameCount) ? 0 : table->InstanceCurrent + 1; const ImGuiTableFlags previous_flags = table->Flags; - const bool is_new_table = (previous_frame_active == -1); table->ID = id; table->Flags = flags; table->LastFrameActive = g.FrameCount; @@ -384,6 +383,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->IsLayoutLocked = false; table->InnerWidth = inner_width; table->NavLayer = (ImS8)outer_window->DC.NavLayerCurrent; + table->IsNewTable = (previous_frame_active == -1); temp_data->UserOuterSize = outer_size; // Instance data (for instance 0, TableID == TableInstanceID) @@ -585,7 +585,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (table->IsInitializing) { // Initialize - if (is_new_table) + if (table->IsNewTable) { table->SettingsOffset = -1; table->IsSettingsRequestLoad = true; @@ -1756,7 +1756,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo ImGuiTableColumn* column = &table->Columns[column_idx]; // If topology change goes into reconcile mode - if (table->IsReconcileMode == false && column->ID != column_id) + if (table->IsReconcileMode == false && column->ID != column_id && !table->IsNewTable) { table->IsReconcileMode = true; table->TempData->ReconcileColumnsRequests.reserve(table->ColumnsCount - column_idx); From cc072ca90e525c0793ff80a152be8eeb70937261 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Sep 2026 17:13:16 +0200 Subject: [PATCH 021/245] Tables: comments for saving fix when using ImGuiTableFlags_Sortable and no user changes were made. (#9519, #9108) Because SortOrder save is gated, it doesn't guarantee every column gets an .ini entry. Amend 1d7b37dc9b. We set ImGuiTableFlags_Reorderable but technically any other field would work, tho ImGuiTableFlags_Reorderable makes more sense. --- docs/CHANGELOG.txt | 3 +++ imgui_tables.cpp | 4 +--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ff7c4d265..a1170fcde 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,9 @@ Other Changes: - Using <> scrolling buttons while the selected Tab is at either end of the section mid-section but not fully visible always makes it fully visible (before eventually selecting a Tab in the leading/trailing section) +- Tables: + - Fixed a bug restoring correct .ini columns order when table use is Sortable + but had no user changes. (regression from 1.92.9). (#9519, #9108) - Selectable: - Fixed `ImGuiSelectableFlags_SelectOnNav` triggering during NavInit. - Fonts: diff --git a/imgui_tables.cpp b/imgui_tables.cpp index eba5b12e2..b3e0458eb 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3970,12 +3970,10 @@ void ImGui::TableSaveSettings(ImGuiTable* table) if (column->DisplayOrder != n) settings->SaveFlags |= ImGuiTableFlags_Reorderable; if (column->SortOrder != -1) - settings->SaveFlags |= ImGuiTableFlags_Sortable; + settings->SaveFlags |= ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable; // Because SortOrder saving itself is gated, make sure every column is saved (#9519) if (column->IsUserEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) settings->SaveFlags |= ImGuiTableFlags_Hideable; } - if (table->Flags & ImGuiTableFlags_Sortable) - settings->SaveFlags |= ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable; settings->SaveFlags &= table->Flags; settings->RefScale = save_ref_scale ? table->RefScale : 0.0f; From 623ba461202d73471d65a1c2b608eecc3959a6d6 Mon Sep 17 00:00:00 2001 From: Daniel Castonguay Date: Tue, 22 Sep 2026 18:12:59 -0400 Subject: [PATCH 022/245] DrawList: fixed dangling ImDrawList::_OwnerName when using animated label. (#9552) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a1170fcde..ceb094151 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -124,6 +124,7 @@ Other Changes: - Added optional `platform_io.DrawCallback_SetSamplerFromTex` standard backend-agnostic draw callback for requesting to use the sampler associated already associated to a texture. Currently only supported by the OpenGL2/3 and SDLRenderer3 backend. (#9378) + - Fixed dangling ImDrawList::_OwnerName when using animated label. (#9552) [@ubi-dcastonguay] - Demo: - Added `Widgets->Mixed Values` section. (#5518, #5677, #6865) - Style Editor: fixed style/colors combo box applying style when opening Combo. diff --git a/imgui.cpp b/imgui.cpp index f7d9bfa91..2bc9e4c34 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7755,6 +7755,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) size_t buf_len = (size_t)window->NameBufLen; window->Name = ImStrdupcpy(window->Name, &buf_len, name); window->NameBufLen = (int)buf_len; + window->DrawList->_OwnerName = window->Name; } // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS From e7289367973e97012a247d6b0a6c4c31b2d4216c Mon Sep 17 00:00:00 2001 From: Brenton Bostick Date: Thu, 24 Sep 2026 07:48:14 -0400 Subject: [PATCH 023/245] Docs: fixed typos/repeated words. (#9555) --- backends/imgui_impl_opengl3_loader.h | 2 +- docs/CHANGELOG.txt | 8 ++++---- imgui.cpp | 4 ++-- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index 2c485841a..34b262dff 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -114,7 +114,7 @@ extern "C" { #define GLAPI extern #endif /* glcorearb.h is for use with OpenGL core profile implementations. -** It should should be placed in the same directory as gl.h and +** It should be placed in the same directory as gl.h and ** included as . ** ** glcorearb.h includes only APIs in the latest OpenGL core profile diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ceb094151..d39b8c7b2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -145,7 +145,7 @@ Other Changes: don't have the equivalent of `SDL_SetTextureScaleMode()` and the callback won't work with them. - Vulkan: added for support for multiple Vulkan contexts with custom loaders. (#6616) [@lstalmir] - WebGPU: fixed passing non-integer sizes to `wgpuRenderPassEncoderSetViewport()` - when when `FramebufferScale` is >1.0f. (#9515, #8628) [@WayU] + when `FramebufferScale` is >1.0f. (#9515, #8628) [@WayU] - WebGPU: update to build with wgpu-native 29.0+. (#9377, #9532, #9530) [@lucascompython, @ivan-enzhaev] - Examples: - MSVC: disabled /JMC in Visual Studio projects (unnecessary overhead). @@ -1755,7 +1755,7 @@ Non-breaking Fonts/Textures related changes: - Fonts: ImFontAtlas::AddFontXXX() can fail more gracefully if error handling is configured to not assert (this will be better exposed via future font flags). - Fonts: added style.FontScaleBase scaling factor (previously called io.FontGlobalScale). -- Fonts: added style.FontScaleDpi scaling factor. This is designed to be be changed on +- Fonts: added style.FontScaleDpi scaling factor. This is designed to be changed on per-monitor/per-viewport basis, which `io.ConfigDpiScaleFonts` does automatically. (which is why it is separate from FontScaleBase). - Fonts: added optional font_size parameter to ImGui::PushFont() function. @@ -2910,7 +2910,7 @@ Other changes: - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] - Examples: SDL3: Remove use of SDL_HINT_IME_NATIVE_UI since new SDL_HINT_IME_IMPLEMENTED_UI - values has a more suitable default for our case case. + values has a more suitable default for our case. - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] @@ -4863,7 +4863,7 @@ Other Changes: - ColorPicker4: Fixed picker being unable to select exact 1.0f color when dragging toward the edges of the SV square (previously picked 0.999989986f). (#3517) [@rokups] - Menus: Fixed vertical alignments of MenuItem() calls within a menu bar (broken in 1.84). (#4538) -- Menus: Improve closing logic when moving diagonally in empty between between parent and child menus to +- Menus: Improve closing logic when moving diagonally in empty space between parent and child menus to accommodate for varying font size and dpi. - Menus: Fixed crash when navigating left inside a child window inside a sub-menu. (#4510). - Menus: Fixed an assertion happening in some situations when closing nested menus (broken in 1.83). (#4640) diff --git a/imgui.cpp b/imgui.cpp index 2bc9e4c34..d25365f16 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -230,7 +230,7 @@ CODE This is to increase compatibility, increase maintainability and facilitate use from other languages. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that. - We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally. + We can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (so don't use ImVector in your code or at our own risk!). - Building: We don't use nor mandate a build system for the main library. @@ -12859,7 +12859,7 @@ bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags // This is a helper to handle the simplest case of associating one named popup to one given widget. // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id. // - To create a popup with a specific identifier, pass it in str_id. -// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. +// - This is useful when using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id. // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // This is essentially the same as: diff --git a/imgui_internal.h b/imgui_internal.h index 97158497b..677a257c6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -538,7 +538,7 @@ inline float ImFloor(float f) { return inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } inline float ImTrunc64(float f) { return (float)(ImS64)(f); } inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } // FIXME: Positive values only. -inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the the bit-hack version (search for "0x1p120f"). +inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the bit-hack version (search for "0x1p120f"). inline int ImModPositive(int a, int b) { return (a + b) % b; } inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } @@ -905,7 +905,7 @@ struct IMGUI_API ImDrawListSharedData const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current font (used for simplified AddText overload) - float FontSize; // Current font size (used for for simplified AddText overload) + float FontSize; // Current font size (used for simplified AddText overload) float FontScale; // Current font scale (== FontSize / Font->FontSize) float CurveTessellationMaxError; // Tessellation tolerance when using PathBezierCurveTo() float CircleTessellationMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1f60853b6..7737a41e6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4795,7 +4795,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(buf != NULL && buf_size >= 0); IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) - IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not not work with left-trimming + IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not work with left-trimming IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Password) == 0); // WordWrap does not work with Password mode. IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Multiline) != 0); // WordWrap does not work in single-line mode. From 5c6a86a9d27d04d4274f7b25be24b38a4579facd Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 25 Sep 2026 14:07:59 +0200 Subject: [PATCH 024/245] imgui_freetype: fixed ExtraSizeScale (used by embedded ProggyForever) leading to non-pixel aligned vertical offset. (#9348, #9233) + Added ImRoundPositive64(), ImRoundSigned64(). --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- imgui_draw.cpp | 1 + imgui_internal.h | 3 ++- misc/freetype/imgui_freetype.cpp | 3 +++ 5 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d39b8c7b2..e751035ac 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,8 @@ Other Changes: - Reworked `AddFontDefault()` to use `io.DisplayFrameBufferScale` as part of the heuristic to select `AddFontDefaultVector()` by default, effectively using ProggyForever instead of ProggyClean on most Apple/Retina setups by default. + - imgui_freetype: Fixed blurryness rendering `AddFontDefaultVector()`. Caused by a + non-pixel aligned offset caused by `ExtraSizeScale`. (#9348, #9233) [@redpartizan, @RDMCz] - ColorEdit: - ColorButton, ColorEdit, ColorPicker: cancel-out alpha caused by BeginDisabled() so disabled color buttons have the same color as non-disabled oness. (#9511) diff --git a/imgui.cpp b/imgui.cpp index d25365f16..57ed579af 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12080,7 +12080,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) } scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]); } - scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f)); + scroll[axis] = ImRoundPositive64(ImMax(scroll[axis], 0.0f)); if (!window->Collapsed && !window->SkipItems) scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0e76fcefc..a4097bf38 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4776,6 +4776,7 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); baked->Descent = ImFloor(unscaled_descent * scale_for_layout); + // FIXME: round to rasterizer density? (#9348) } return true; } diff --git a/imgui_internal.h b/imgui_internal.h index 677a257c6..0ffadedc3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -537,7 +537,8 @@ inline ImVec2 ImTrunc(const ImVec2& v) { return inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } inline float ImTrunc64(float f) { return (float)(ImS64)(f); } -inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } // FIXME: Positive values only. +inline float ImRoundPositive64(float f) { return (float)(ImS64)(f + 0.5f); } // Positive values only. +inline float ImRoundSigned64(float f) { return (float)(ImS64)(f >= 0.0f ? f + 0.5f : f - 0.5f); } inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the bit-hack version (search for "0x1p120f"). inline int ImModPositive(int a, int b) { return (a + b) % b; } inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 79dff8bfb..83259bfd0 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -7,6 +7,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026/09/25: fixed handling of ExtraSizeScale. // 2025/06/11: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927) // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics. @@ -468,6 +469,8 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. //LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * scale; // The spacing in pixels between one row's descent and the next row's ascent. //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font. + baked->Ascent = ImRoundSigned64(baked->Ascent * rasterizer_density) / rasterizer_density; + baked->Descent = ImRoundSigned64(baked->Descent * rasterizer_density) / rasterizer_density; } return true; } From aa0181478b182f7170378a5d8629401b77ee326e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 25 Sep 2026 14:17:14 +0200 Subject: [PATCH 025/245] imgui_freetype: tweak rounding code. (#9348, #9233) --- misc/freetype/imgui_freetype.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 83259bfd0..2e2e78f7d 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -464,8 +464,8 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s // Read metrics FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; const float scale = 1.0f / (rasterizer_density * src->ExtraSizeScale); - baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). - baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). + baked->Ascent = ((float)metrics.ascender / FT_SCALEFACTOR) * scale; // The pixel extents above the baseline in pixels (typically positive). + baked->Descent = ((float)metrics.descender / FT_SCALEFACTOR) * scale; // The extents below the baseline in pixels (typically negative). //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. //LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * scale; // The spacing in pixels between one row's descent and the next row's ascent. //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font. From 09f7a0f062b902dc0b377439421abc58d369b1d9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 28 Sep 2026 15:12:49 +0200 Subject: [PATCH 026/245] Docs: tweak PR template. --- .github/pull_request_template.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8061997cf..998b25427 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,12 +1,12 @@ (Click "Preview" to turn any http URL into a clickable link) -1. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md) +1. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md). By submitting a PR you are agreeing with the [CLA](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md#copyright--contributor-license-agreement). 2. **Make sure you're using a special branch just for this pull request**. (In git, 1 PR = 1 branch. If you update the branch the PR will be updated.) 3. Consider running the [imgui_test_suite](https://github.com/ocornut/imgui_test_engine) or adding new tests to test for expected behaviors. -4. PLEASE DO NOT SUBMIT AI SLOP OR AUTOMATED AI REPORTS. Submissions that are lacking proper human review/judgement before being passed to us are not welcome. Do not let a LLM AI write most of the text for you. +4. PLEASE DO NOT SUBMIT AI-GENERATED PROSE. ONLY SUBMIT CODE THAT YOU REVIEWED AND UNDERSTAND. Submissions that are lacking proper human review/judgement before being passed to us are not welcome. 5. Clear this template before submitting your PR. From db436a15bc04cabaa10d8c7ce5e9dc81c3587f8a Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Sat, 26 Sep 2026 12:34:24 +0200 Subject: [PATCH 027/245] Misc: fixed strict aliasing violation in ImHashData() affecting Clang 23 + SSE 4.2 + -flto. (#9557, #9560) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e751035ac..1eee0b79b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -114,6 +114,9 @@ Other Changes: trivial functions when stepping into. - Tagged various trivial functions using `IM_NODEBUGSTEP`: `ImVec2()`, `ImVec4()` etc. and various operators. + - Fixed strict aliasing violation in `ImHashData()` affecting Clang 23 + SSE 4.2 + -flto. + Could manifest as `ImFontAtlasBakedGetId()` computation omitting font size from + the hashed data. (#9557, #9560) [@sthalik] - IO: restore default clipboard/ime/shell platform handlers on ClearPlatformHandlers(), fixing issues switching backends mid-session to one relying on default. (#9537, #8945, #2769) [@lstalmir] - DrawList: diff --git a/imgui.cpp b/imgui.cpp index 57ed579af..fb86370b9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2493,7 +2493,13 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed) #else while (data + 4 <= data_end) { +#if defined(_DEBUG) || defined(_MSC_VER) crc = _mm_crc32_u32(crc, *(ImU32*)data); +#else + ImU32 v; + memcpy(&v, data, sizeof(ImU32)); // Avoid aliasing violation (#9557) + crc = _mm_crc32_u32(crc, v); +#endif data += 4; } while (data < data_end) From 580c00c316285de8104a8fa0701265557fb78a62 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 28 Sep 2026 17:47:39 +0200 Subject: [PATCH 028/245] InputText: fixed a crash using Home key with WordWrap+ReadOnly. (#9561) Only the change in STB_TEXTEDIT_MOVELINESTART_IMPL() is required. The others are just for nicer semantic. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 10 +++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1eee0b79b..30afc33be 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,8 @@ Other Changes: - Tables: - Fixed a bug restoring correct .ini columns order when table use is Sortable but had no user changes. (regression from 1.92.9). (#9519, #9108) +- InpuText: + - Fixed a crash in some cases when using Home key in a WordWrap+ReadOnly field. (#9561) - Selectable: - Fixed `ImGuiSelectableFlags_SelectOnNav` triggering during NavInit. - Fonts: diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7737a41e6..ceabc13ba 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4232,7 +4232,7 @@ static int STB_TEXTEDIT_MOVELINESTART_IMPL(ImGuiInputTextState* obj, ImStb::STB_ const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks); if (p == p_cursor) // If we are already on a visible beginning-of-line, return real beginning-of-line (would be same as regular handler below) return (int)(p_bol - obj->TextSrc); - if (p_eol == p_cursor && obj->TextA[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left) + if (p_eol == p_cursor && obj->TextSrc[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left) return (int)(p_bol - obj->TextSrc); if (p_eol >= p_cursor) return (int)(p - obj->TextSrc); @@ -5057,7 +5057,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Select the buffer to render. const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state; - bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0) && !is_mixed; + bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextSrc : buf)[0] == 0) && !is_mixed; // Password pushes a temporary font with only a fallback glyph if (is_password && !is_displaying_hint) @@ -5283,7 +5283,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { if (flags & ImGuiInputTextFlags_EscapeClearsAll) { - if (state->TextA.Data[0] != 0) + if (state->TextSrc[0] != 0) { revert_edit = true; } @@ -5376,14 +5376,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (flags & ImGuiInputTextFlags_EscapeClearsAll) { // Clear input - IM_ASSERT(state->TextA.Data[0] != 0); + IM_ASSERT(state->TextSrc[0] != 0); apply_new_text = ""; apply_new_text_length = 0; value_changed = true; char empty_string = 0; stb_textedit_replace(state, state->Stb, &empty_string, 0); } - else if (strcmp(state->TextA.Data, state->TextToRevertTo.Data) != 0) + else if (strcmp(state->TextSrc, state->TextToRevertTo.Data) != 0) { apply_new_text = state->TextToRevertTo.Data; apply_new_text_length = state->TextToRevertTo.Size - 1; From 46ff5a7aab3c091fe8e4e427fea2cabffcf0478d Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 29 Sep 2026 22:04:11 +0200 Subject: [PATCH 029/245] Fonts: shallow refactor of ImFontBaked_BuildLoadGlyph() mostly to reduce an upcoming diff. (#9559) --- imgui_draw.cpp | 49 ++++++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a4097bf38..86a35d731 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4596,35 +4596,34 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep // Call backend char* loader_user_data_p = (char*)baked->FontLoaderDatas; - int src_n = 0; - for (ImFontConfig* src : font->Sources) + char* loader_user_data_p_next = NULL; + for (int src_n = 0; src_n < font->Sources.Size; src_n++, loader_user_data_p = loader_user_data_p_next) { + ImFontConfig* src = font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) + loader_user_data_p_next = loader_user_data_p + loader->FontBakedSrcLoaderDataSize; + + if (src->GlyphExcludeRanges && !ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) + continue; + + if (only_load_advance_x == NULL) { - if (only_load_advance_x == NULL) - { - ImFontGlyph glyph_buf; - if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL)) - { - // FIXME: Add hooks for e.g. #7962 - glyph_buf.Codepoint = src_codepoint; - glyph_buf.SourceIdx = src_n; - return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); - } - } - else - { - // Special mode but only loading glyphs metrics. Will rasterize and pack later. - if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x)) - { - ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); - return NULL; - } - } + ImFontGlyph glyph_buf; + if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL)) + continue; + // FIXME: Add hooks for e.g. #7962 + glyph_buf.Codepoint = src_codepoint; + glyph_buf.SourceIdx = src_n; + return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); + } + else + { + // Special mode but only loading glyphs metrics. Will rasterize and pack later. + if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x)) + continue; + ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); + return NULL; } - loader_user_data_p += loader->FontBakedSrcLoaderDataSize; - src_n++; } // Lazily load fallback glyph From 09d740ba3292a8609481a17e5b20f16df3f34377 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 29 Sep 2026 21:17:16 +0200 Subject: [PATCH 030/245] (Breaking) Fonts: refactor ImFontLoader to allow loading from glyph_index. (#9559, #5647) cc #9540, #8466, #8465 --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 ++- imgui_draw.cpp | 45 ++++++++++++++++---------------- imgui_internal.h | 5 ++-- misc/freetype/imgui_freetype.cpp | 40 ++++++++++++---------------- 5 files changed, 47 insertions(+), 49 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 30afc33be..55e2245db 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,9 @@ Other Changes: ProggyClean on most Apple/Retina setups by default. - imgui_freetype: Fixed blurryness rendering `AddFontDefaultVector()`. Caused by a non-pixel aligned offset caused by `ExtraSizeScale`. (#9348, #9233) [@redpartizan, @RDMCz] + - (Internal) ImFontLoader: reworked `FontSrcContainsGlyph`, `FontBakedLoadGlyph` signatures + to take raw glyph index instead of codepoint. Added `FontSrcGetGlyphIndexFromCodepoint`. + (#9559, #5647, #9540, #8466, #8465) - ColorEdit: - ColorButton, ColorEdit, ColorPicker: cancel-out alpha caused by BeginDisabled() so disabled color buttons have the same color as non-disabled oness. (#9511) diff --git a/imgui.cpp b/imgui.cpp index fb86370b9..62688197d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17710,7 +17710,8 @@ static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigne for (int src_n = 0; src_n < font->Sources.Size; src_n++) { ImFontConfig* src = font->Sources[src_n]; - if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint)) + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + if (loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, (ImWchar)codepoint) == 0) continue; mask |= (1 << src_n); count++; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 86a35d731..1c8e54863 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3123,7 +3123,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) } if (font_cfg->FontLoader != NULL) { - IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL); + IM_ASSERT(font_cfg->FontLoader->FontSrcGetGlyphIndexFromCodepoint != NULL && font_cfg->FontLoader->FontBakedLoadGlyph != NULL); IM_ASSERT(font_cfg->FontLoader->LoaderInit == NULL && font_cfg->FontLoader->LoaderShutdown == NULL); // FIXME-NEWATLAS: Unsupported yet. } // | Target w/ Implicit RefSize | Target w/ Explicit RefSize | @@ -4606,10 +4606,15 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep if (src->GlyphExcludeRanges && !ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) continue; + int glyph_index = loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, codepoint); + if (glyph_index == 0) + continue; + if (only_load_advance_x == NULL) { ImFontGlyph glyph_buf; - if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL)) + glyph_buf.Codepoint = codepoint; + if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, glyph_index, &glyph_buf, NULL)) continue; // FIXME: Add hooks for e.g. #7962 glyph_buf.Codepoint = src_codepoint; @@ -4619,7 +4624,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep else { // Special mode but only loading glyphs metrics. Will rasterize and pack later. - if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x)) + if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, glyph_index, NULL, only_load_advance_x)) continue; ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); return NULL; @@ -4707,10 +4712,8 @@ struct ImGui_ImplStbTrueType_FontSrcData float ScaleFactor; }; -static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) +static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas*, ImFontConfig* src) { - IM_UNUSED(atlas); - ImGui_ImplStbTrueType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplStbTrueType_FontSrcData); IM_ASSERT(src->FontLoaderData == NULL); @@ -4742,29 +4745,27 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* return true; } -static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas*, ImFontConfig* src) { - IM_UNUSED(atlas); ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; IM_DELETE(bd_font_data); src->FontLoaderData = NULL; } -static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +static int ImGui_ImplStbTrueType_FontSrcGetGlyphIndexFromCodepoint(ImFontAtlas*, ImFontConfig* src, ImWchar codepoint) { - IM_UNUSED(atlas); - ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; - IM_ASSERT(bd_font_data != NULL); - - int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); - return glyph_index != 0; + return stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); } -static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*) +static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas*, ImFontConfig* src, int glyph_index) { - IM_UNUSED(atlas); + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; + return glyph_index > 0 && glyph_index < bd_font_data->FontInfo.numGlyphs; +} +static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas*, ImFontConfig* src, ImFontBaked* baked, void*) +{ ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; if (src->MergeMode == false) { @@ -4780,14 +4781,12 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig return true; } -static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) +static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, int glyph_index, ImFontGlyph* out_glyph, float* out_advance_x) { // Search for first font which has the glyph ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; IM_ASSERT(bd_font_data); - int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); - if (glyph_index == 0) - return false; + IM_ASSERT(glyph_index != 0); // Fonts unit to pixels int oversample_h, oversample_v; @@ -4812,7 +4811,6 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC } // Prepare glyph - out_glyph->Codepoint = codepoint; out_glyph->AdvanceX = advance * scale_for_layout; // Pack and retrieve position inside texture atlas @@ -4874,6 +4872,7 @@ const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() loader.Name = "stb_truetype"; loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit; loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy; + loader.FontSrcGetGlyphIndexFromCodepoint = ImGui_ImplStbTrueType_FontSrcGetGlyphIndexFromCodepoint; loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph; loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit; loader.FontBakedDestroy = NULL; @@ -5405,7 +5404,7 @@ bool ImFont::IsGlyphInFont(ImWchar c) for (ImFontConfig* src : Sources) { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (loader->FontSrcContainsGlyph != NULL && loader->FontSrcContainsGlyph(atlas, src, c)) + if (loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, c) != 0) return true; } return false; diff --git a/imgui_internal.h b/imgui_internal.h index 0ffadedc3..b0f8856f8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3932,10 +3932,11 @@ struct ImFontLoader void (*LoaderShutdown)(ImFontAtlas* atlas); bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); - bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); + int (*FontSrcGetGlyphIndexFromCodepoint)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); // Required + bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, int glyph_index); bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); - bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x); + bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, int glyph_index, ImFontGlyph* out_glyph, float* out_advance_x); // Required // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. // FIXME: At this point the two other types of buffers may be managed by core to be consistent? diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 2e2e78f7d..375863fdf 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -221,17 +221,14 @@ void ImGui_ImplFreeType_FontSrcData::CloseFont() } } -static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t codepoint) +static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t glyph_index) { - uint32_t glyph_index = FT_Get_Char_Index(src_data->FtFace, codepoint); - if (glyph_index == 0) - return nullptr; - // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 // - https://github.com/ocornut/imgui/issues/4567 // - https://github.com/ocornut/imgui/issues/4566 // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. + IM_ASSERT(glyph_index != 0); FT_Error error = FT_Load_Glyph(src_data->FtFace, glyph_index, src_data->LoadFlags); if (error) return nullptr; @@ -417,17 +414,15 @@ static bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src return true; } -static void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) +static void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas*, ImFontConfig* src) { - IM_UNUSED(atlas); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; IM_DELETE(bd_font_data); src->FontLoaderData = nullptr; } -static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas*, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { - IM_UNUSED(atlas); float size = baked->Size; const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; if (src->MergeMode && src->SizePixels != 0.0f) @@ -475,9 +470,8 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* s return true; } -static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas*, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { - IM_UNUSED(atlas); IM_UNUSED(baked); IM_UNUSED(src); ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; @@ -486,13 +480,9 @@ static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } -static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) +static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, int glyph_index, ImFontGlyph* out_glyph, float* out_advance_x) { ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; - uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); - if (glyph_index == 0) - return false; - if (bd_font_data->BakedLastActivated != baked) // <-- could use id { // Activate current size @@ -501,7 +491,7 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf bd_font_data->BakedLastActivated = baked; } - const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint); + const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, glyph_index); if (metrics == nullptr) return false; @@ -530,7 +520,6 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf const bool is_visible = (w != 0 && h != 0); // Prepare glyph - out_glyph->Codepoint = codepoint; out_glyph->AdvanceX = advance_x; // Pack and retrieve position inside texture atlas @@ -573,12 +562,16 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf return true; } -static bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) +static int ImGui_ImplFreetype_FontSrcGetGlyphIndexFromCodepoint(ImFontAtlas*, ImFontConfig* src, ImWchar codepoint) { - IM_UNUSED(atlas); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; - int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); - return glyph_index != 0; + return (int)FT_Get_Char_Index(bd_font_data->FtFace, codepoint); +} + +static bool ImGui_ImplFreeType_FontSrcContainsGlyph(ImFontAtlas*, ImFontConfig* src, int glyph_index) +{ + ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + return glyph_index > 0 && glyph_index < bd_font_data->FtFace->num_glyphs; } const ImFontLoader* ImGuiFreeType::GetFontLoader() @@ -589,7 +582,8 @@ const ImFontLoader* ImGuiFreeType::GetFontLoader() loader->LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown; loader->FontSrcInit = ImGui_ImplFreeType_FontSrcInit; loader->FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy; - loader->FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph; + loader->FontSrcGetGlyphIndexFromCodepoint = ImGui_ImplFreetype_FontSrcGetGlyphIndexFromCodepoint; + loader->FontSrcContainsGlyph = ImGui_ImplFreeType_FontSrcContainsGlyph; loader->FontBakedInit = ImGui_ImplFreeType_FontBakedInit; loader->FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy; loader->FontBakedLoadGlyph = ImGui_ImplFreeType_FontBakedLoadGlyph; From dfa3c0c0bb7d694348855b3a67ff95d0319a2d61 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2026 18:09:17 +0200 Subject: [PATCH 031/245] (Breaking) Fonts: rename AddRemapChar() to AddRemapCodepoint(). (#609, #5748, #9559) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui.h | 5 +++-- imgui_draw.cpp | 11 ++++++----- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 55e2245db..6d70915ea 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Breaking Changes: - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. +- Fonts: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). + (#609, #5748, #9559) - Backends: - DirectX12: Removed support for legacy `ImGui_ImplDX12_Init()` signature, which was obsoleted in 1.91.6 (December 2014), because it needed to forcefully disable support diff --git a/imgui.cpp b/imgui.cpp index 62688197d..ef9ca7f29 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -395,6 +395,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2026/09/30 (1.93.0) - ImFont: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). (#609, #5748) - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). diff --git a/imgui.h b/imgui.h index a108888a2..174660964 100644 --- a/imgui.h +++ b/imgui.h @@ -3967,7 +3967,7 @@ struct ImFont ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 17 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 8K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph (== EllipsisChar) needs to be generated by combining multiple '.'. - ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. + ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapCodepoint(), otherwise empty. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() #endif @@ -3993,8 +3993,9 @@ struct ImFont // [Internal] Don't use! IMGUI_API void ClearOutputData(); - IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. + IMGUI_API void AddRemapCodepoint(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); + //inline void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) { AddRemapCodepointToCodepoint(from_codepoint, to_codepoint); } // Renamed in 1.93.0 (Oct 2026) }; // This is provided for consistency (but we don't actually use this) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1c8e54863..e2dd1f701 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4562,6 +4562,12 @@ static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); } +// Remap a codepoint to another codepoint +void ImFont::AddRemapCodepoint(ImWchar from_codepoint, ImWchar to_codepoint) +{ + RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint); +} + static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) { IM_UNUSED(atlas); @@ -5346,11 +5352,6 @@ void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } -void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) -{ - RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint); -} - // Find glyph, load if necessary, return fallback if missing ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c) { From 7263a23f1beab16c72b4a72a036fd822313cfc4e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2026 18:41:31 +0200 Subject: [PATCH 032/245] Fonts: added ImFont::AddRemapCodepointToGlyphIndex(). (#9559, #5647, #609, #5748, #8466) --- imgui.h | 5 ++-- imgui_draw.cpp | 68 ++++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 60 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index 174660964..8c5be4a44 100644 --- a/imgui.h +++ b/imgui.h @@ -3967,7 +3967,7 @@ struct ImFont ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 17 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 8K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph (== EllipsisChar) needs to be generated by combining multiple '.'. - ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapCodepoint(), otherwise empty. + ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapCodepointXXX(). #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() #endif @@ -3994,8 +3994,9 @@ struct ImFont // [Internal] Don't use! IMGUI_API void ClearOutputData(); IMGUI_API void AddRemapCodepoint(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. + IMGUI_API void AddRemapCodepointToGlyphIndex(ImWchar from_codepoint, int font_src_idx, int glyph_idx); IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); - //inline void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) { AddRemapCodepointToCodepoint(from_codepoint, to_codepoint); } // Renamed in 1.93.0 (Oct 2026) + //inline void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) { AddRemapCodepoint(from_codepoint, to_codepoint); } // Renamed in 1.93.0 (Sep 2026) }; // This is provided for consistency (but we don't actually use this) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e2dd1f701..e2085f6e6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4565,14 +4565,43 @@ static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) // Remap a codepoint to another codepoint void ImFont::AddRemapCodepoint(ImWchar from_codepoint, ImWchar to_codepoint) { - RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint); + ImU32 data = (ImU32)to_codepoint; + IM_ASSERT((data & (1u << 31)) == 0); + RemapPairs.SetInt((ImGuiID)from_codepoint, (int)data); } -static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) +static const int IMFONT_REMAPVALUE_GLYPHIDX_SHIFT = 0; +static const int IMFONT_REMAPVALUE_GLYPHIDX_MASK = 0xFFFF; +static const int IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT = 16; +static const int IMFONT_REMAPVALUE_FONTSRCIDX_MASK = 0xFF0000; + +// Remap a codepoint to a raw glyph index inside the font. Allows accessing glyphs which are not mapped to codepoints. (#9559) +// font_src_idx = index in font->Sources[], or -1 for last added source. +// glyph_idx = index in TTF or OTF file. +void ImFont::AddRemapCodepointToGlyphIndex(ImWchar from_codepoint, int font_src_idx, int glyph_idx) +{ + if (font_src_idx == -1) + font_src_idx = Sources.Size - 1; + IM_ASSERT(font_src_idx >= 0 && font_src_idx < Sources.Size && ((font_src_idx << IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT) & ~IMFONT_REMAPVALUE_FONTSRCIDX_MASK) == 0); + IM_ASSERT(glyph_idx >= 0 && ((glyph_idx << IMFONT_REMAPVALUE_GLYPHIDX_SHIFT) & ~IMFONT_REMAPVALUE_GLYPHIDX_MASK) == 0); + ImU32 data = ((ImU32)glyph_idx << IMFONT_REMAPVALUE_GLYPHIDX_SHIFT) | (font_src_idx << IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT) | (1u << 31); + RemapPairs.SetInt((ImGuiID)from_codepoint, (int)data); +} + +static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar codepoint, ImWchar* out_codepoint, int* out_font_src_idx, int* out_glyph_idx) { IM_UNUSED(atlas); - if (font->RemapPairs.Data.Size != 0) - *c = (ImWchar)font->RemapPairs.GetInt((ImGuiID)*c, (int)*c); + if (font->RemapPairs.Data.Size == 0) + return; + ImU32 data = (ImU32)font->RemapPairs.GetInt((ImGuiID)codepoint, (int)codepoint); + if (data & (1u << 31)) + { + *out_codepoint = (ImWchar)-1; + *out_font_src_idx = (data & IMFONT_REMAPVALUE_FONTSRCIDX_MASK) >> IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT; + *out_glyph_idx = (data & IMFONT_REMAPVALUE_GLYPHIDX_MASK) >> IMFONT_REMAPVALUE_GLYPHIDX_SHIFT; + return; + } + *out_codepoint = (ImWchar)data; } static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint, float* only_load_advance_x) @@ -4589,7 +4618,8 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep // User remapping hooks ImWchar src_codepoint = codepoint; - ImFontAtlas_FontHookRemapCodepoint(atlas, font, &codepoint); + int src_font_idx = -1, src_glyph_idx = -1; + ImFontAtlas_FontHookRemapCodepoint(atlas, font, codepoint, &src_codepoint, &src_font_idx, &src_glyph_idx); //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); @@ -4609,10 +4639,19 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; loader_user_data_p_next = loader_user_data_p + loader->FontBakedSrcLoaderDataSize; - if (src->GlyphExcludeRanges && !ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) - continue; - - int glyph_index = loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, codepoint); + int glyph_index; + if (src_codepoint != (ImWchar)-1) + { + if (src->GlyphExcludeRanges && !ImFontAtlasBuildAcceptCodepointForSource(src, src_codepoint)) + continue; + glyph_index = loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, src_codepoint); + } + else + { + if (src_n != src_font_idx) + continue; + glyph_index = src_glyph_idx; + } if (glyph_index == 0) continue; @@ -4623,7 +4662,6 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, glyph_index, &glyph_buf, NULL)) continue; // FIXME: Add hooks for e.g. #7962 - glyph_buf.Codepoint = src_codepoint; glyph_buf.SourceIdx = src_n; return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); } @@ -5401,7 +5439,15 @@ bool ImFontBaked::IsGlyphLoaded(ImWchar c) bool ImFont::IsGlyphInFont(ImWchar c) { ImFontAtlas* atlas = OwnerAtlas; - ImFontAtlas_FontHookRemapCodepoint(atlas, this, &c); + ImWchar src_codepoint = c; + int src_font_idx = -1, src_glyph_idx = -1; + ImFontAtlas_FontHookRemapCodepoint(atlas, this, c, &src_codepoint, &src_font_idx, &src_glyph_idx); + if (src_font_idx != -1) + { + ImFontConfig* src = Sources[src_font_idx]; + const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; + return loader->FontSrcContainsGlyph ? loader->FontSrcContainsGlyph(atlas, src, src_glyph_idx) : false; + } for (ImFontConfig* src : Sources) { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; From a9fd325ca5462ac260107fc172660682cd976c1e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2026 18:51:32 +0200 Subject: [PATCH 033/245] Docs: add Changelog entries. Amend 7263a23. --- docs/CHANGELOG.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6d70915ea..803702a63 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,8 @@ Other Changes: - Reworked `AddFontDefault()` to use `io.DisplayFrameBufferScale` as part of the heuristic to select `AddFontDefaultVector()` by default, effectively using ProggyForever instead of ProggyClean on most Apple/Retina setups by default. + - Added ImFont::AddRemapCodepointToGlyphIndex() allowing to access glyphs that are not + mapped to codepoints. (#9559, #5647, #609, #5748, #8466) - imgui_freetype: Fixed blurryness rendering `AddFontDefaultVector()`. Caused by a non-pixel aligned offset caused by `ExtraSizeScale`. (#9348, #9233) [@redpartizan, @RDMCz] - (Internal) ImFontLoader: reworked `FontSrcContainsGlyph`, `FontBakedLoadGlyph` signatures From 3f00c0d0f414d45af2a0979b925ebf2e8f09936b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2026 19:13:56 +0200 Subject: [PATCH 034/245] Examples: GLFW+Metal: fixed mistakenly calling ImGui_ImplGlfw_InitForOpenGL(), which broke multi-viewport support. (#9564) --- docs/CHANGELOG.txt | 2 ++ examples/example_glfw_metal/main.mm | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 803702a63..78fefb11f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -164,6 +164,8 @@ Other Changes: - Examples: - MSVC: disabled /JMC in Visual Studio projects (unnecessary overhead). - GLFW/SDL2/SDL3+WebGPU: fixed running with wgpu-native missing `wgpuInstanceWaitAny()`. (#9377) + - GLFW+Metal: fixed mistakenly calling `ImGui_ImplGlfw_InitForOpenGL()`, which + broke multi-viewport support. (#9564) [@ypujante] - SDL2+Metal: create Metal context without using a `SDL_Renderer`. - QNX+OpenGL3, QNX+Vulkan: added QNX Screen examples. (#9492) [@mgorchak-blackberry] - OSX+OpenGL3: added example_apple_opengl3/ (OSX/Cocoa + OpenGL 3.2 Core profile). diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index 0ded0a3bd..a3671e4e6 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -58,7 +58,7 @@ int main(int, char**) id commandQueue = [device newCommandQueue]; // Setup Platform/Renderer backends - ImGui_ImplGlfw_InitForOpenGL(window, true); + ImGui_ImplGlfw_InitForOther(window, true); ImGui_ImplMetal_Init(device); // Load Fonts From fe33b77f6450bef548fe98db977be238f0459a10 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Oct 2026 12:59:30 +0200 Subject: [PATCH 035/245] Backends: OpenGL3: Avoid querying glGetIntegerv(GL_CLIP_ORIGIN) again when using DrawCallback_ResetRenderState. (#2186, #3998, #3146, #3143, #8640) --- backends/imgui_impl_opengl3.cpp | 27 +++++++++++++-------------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 73dc349d8..7c07eb008 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -24,6 +24,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-10-01: OpenGL: Avoid querying glGetIntegerv(GL_CLIP_ORIGIN) again when using DrawCallback_ResetRenderState. (#2186, #3998, #3146, #3143, #8640) // 2026-09-17: OpenGL: Added support for platform_io.DrawCallback_SetSamplerFromTex. (#9378) // 2026-09-07: OpenGL: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-15: OpenGL: Backup and restore GL_UNPACK_ROW_LENGTH and GL_UNPACK_ALIGNMENT in UpdateTexture() to avoid corrupting caller GL state. (#8802, #9473) @@ -259,6 +260,7 @@ struct ImGui_ImplOpenGL3_Data bool HasPolygonMode; bool HasBindSampler; bool HasClipOrigin; + bool ClipOriginLowerLeft; bool UseBufferSubData; #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER GLuint TexSamplers[2]; // Used if HasBindSimpler. (0=linear, 1=nearest) @@ -361,17 +363,6 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, ImGui_Impl glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif - // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) -#if defined(GL_CLIP_ORIGIN) - bool clip_origin_lower_left = true; - if (bd->HasClipOrigin) - { - GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); - if (current_clip_origin == GL_UPPER_LEFT) - clip_origin_lower_left = false; - } -#endif - // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height)); @@ -379,9 +370,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, ImGui_Impl float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; -#if defined(GL_CLIP_ORIGIN) - if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left -#endif + if (!bd->ClipOriginLowerLeft) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, @@ -524,6 +513,16 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_primitive_restart = (!bd->GlProfileIsES3 && bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; #endif + // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) + bd->ClipOriginLowerLeft = true; +#if defined(GL_CLIP_ORIGIN) + if (bd->HasClipOrigin) + { + GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); + bd->ClipOriginLowerLeft = (current_clip_origin != GL_UPPER_LEFT); + } +#endif + // Setup desired GL state // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 78fefb11f..8fbc0b8ed 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -148,6 +148,8 @@ Other Changes: callback to request using the sampler associated already associated to a texture. (#9378) - OpenGL2, OpenGL3: fixed `DrawCallback_ResetRenderState` handler not reseting all states in the glTexParameter() path. (#9378) + - OpenGL3: avoid querying `glGetIntegerv(GL_CLIP_ORIGIN)` again when using `DrawCallback_ResetRenderState`, + at it appear to stall some drivers. (#2186, #3998, #3146, #3143, #8640) - SDL2: fixed querying framebuffer scale/density when using Metal without going through a SDL_Renderer. (#5592) [@lailoken] - SDLRenderer3: restore any temporarily modified texture scale modes at the of `RenderDrawData()`. (#9378) From a3f3e4944a2aa6053e8876fe55a4ebad404d08d6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Oct 2026 17:36:59 +0200 Subject: [PATCH 036/245] (Breaking) Backends: OpenGL3: added ImGui_ImplOpenGL3_SetClipOrigin. Default to GL_LOWER_LEFT. (#2186, #3998, #3146, #3143, #8640) --- backends/imgui_impl_opengl3.cpp | 31 ++++++++++++++++++++-------- backends/imgui_impl_opengl3.h | 3 +++ backends/imgui_impl_opengl3_loader.h | 1 + docs/CHANGELOG.txt | 10 +++++++-- 4 files changed, 34 insertions(+), 11 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 7c07eb008..568067c5f 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -24,7 +24,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-10-01: OpenGL: Avoid querying glGetIntegerv(GL_CLIP_ORIGIN) again when using DrawCallback_ResetRenderState. (#2186, #3998, #3146, #3143, #8640) +// 2026-10-01: OpenGL: Added ImGui_ImplOpenGL3_SetClipOrigin() to specify clip origins (GL_LOWER_LEFT/GL_UPPER_LEFT, or use 0 to autodetect). (#2186, #3998, #3146, #3143, #8640) +// (Breaking): we now default to GL_LOWER_LEFT instead of 0=autodetect. Because 1) detection is not reliable and 2) is slow. +// 2026-10-01: OpenGL: Avoid querying glGetIntegerv(GL_CLIP_ORIGIN) multiple times when using DrawCallback_ResetRenderState. (#2186, #3998, #3146, #3143, #8640) // 2026-09-17: OpenGL: Added support for platform_io.DrawCallback_SetSamplerFromTex. (#9378) // 2026-09-07: OpenGL: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-15: OpenGL: Backup and restore GL_UNPACK_ROW_LENGTH and GL_UNPACK_ALIGNMENT in UpdateTexture() to avoid corrupting caller GL state. (#8802, #9473) @@ -260,7 +262,8 @@ struct ImGui_ImplOpenGL3_Data bool HasPolygonMode; bool HasBindSampler; bool HasClipOrigin; - bool ClipOriginLowerLeft; + GLenum ClipOriginRequest; // Default = GL_LOWER_LEFT. Change using ImGui_ImplOpenGL3_SetClipOrigin(). + GLenum ClipOriginCurrent; bool UseBufferSubData; #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER GLuint TexSamplers[2]; // Used if HasBindSimpler. (0=linear, 1=nearest) @@ -370,7 +373,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, ImGui_Impl float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; - if (!bd->ClipOriginLowerLeft) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left + if (bd->ClipOriginCurrent == GL_UPPER_LEFT) { float tmp = T; T = B; B = tmp; } // Swap top and bottom const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, @@ -452,6 +455,14 @@ static void ImGui_ImplOpenGL3_DrawCallback_SetSamplerFromTex(const ImDrawList*, render_state->UseTexParameterFilter = false; } +// Default is GL_LOWER_LEFT since 2026/10/01. Used to be auto. +void ImGui_ImplOpenGL3_SetClipOrigin(unsigned int clip_origin) +{ + IM_ASSERT(clip_origin == 0 || clip_origin == GL_UPPER_LEFT || clip_origin == GL_LOWER_LEFT); + ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); + bd->ClipOriginRequest = clip_origin; +} + // OpenGL3 Render function. // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. // This is in order to be able to run within an OpenGL engine that doesn't do so. @@ -514,14 +525,15 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) #endif // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) - bd->ClipOriginLowerLeft = true; -#if defined(GL_CLIP_ORIGIN) - if (bd->HasClipOrigin) + bd->ClipOriginCurrent = bd->ClipOriginRequest; + if (bd->ClipOriginCurrent == 0) { - GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); - bd->ClipOriginLowerLeft = (current_clip_origin != GL_UPPER_LEFT); - } + bd->ClipOriginCurrent = GL_LOWER_LEFT; +#if defined(GL_CLIP_ORIGIN) + if (bd->HasClipOrigin) + glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&bd->ClipOriginCurrent); #endif + } // Setup desired GL state // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) @@ -1149,6 +1161,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) bd->HasClipOrigin = true; } #endif + bd->ClipOriginCurrent = bd->ClipOriginRequest = GL_LOWER_LEFT; return true; } diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h index e1d999bd3..17a49cd51 100644 --- a/backends/imgui_impl_opengl3.h +++ b/backends/imgui_impl_opengl3.h @@ -44,6 +44,9 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex); +// (Advanced) Specify clip origin, same value as glClipControl() or 0 for auto-detection. +IMGUI_IMPL_API void ImGui_ImplOpenGL3_SetClipOrigin(unsigned int gl_clip_origin); + // Configuration flags to add in your imconfig file: //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten) //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android) diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index 34b262dff..47f9fb364 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -303,6 +303,7 @@ typedef khronos_uint16_t GLushort; #define GL_LINK_STATUS 0x8B82 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_CURRENT_PROGRAM 0x8B8D +#define GL_LOWER_LEFT 0x8CA1 #define GL_UPPER_LEFT 0x8CA2 typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8fbc0b8ed..e0d0d9264 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,9 @@ Breaking Changes: - DirectX12: Removed support for legacy `ImGui_ImplDX12_Init()` signature, which was obsoleted in 1.91.6 (December 2014), because it needed to forcefully disable support for `ImGuiBackendFlags_RendererHasTextures`. Use the new signature! (#9487) + - OpenGL3: Does not attempt to read `GL_CLIP_ORIGIN` by default as the detection is + sub-optimal and not reliable on some setup. Use `ImGui_ImplOpenGL3_SetClipOrigin(0)` + to enable auto-detection, or e.g. `ImGui_ImplOpenGL3_SetClipOrigin(GL_UPPER_LEFT)`. Other Changes: @@ -148,8 +151,11 @@ Other Changes: callback to request using the sampler associated already associated to a texture. (#9378) - OpenGL2, OpenGL3: fixed `DrawCallback_ResetRenderState` handler not reseting all states in the glTexParameter() path. (#9378) - - OpenGL3: avoid querying `glGetIntegerv(GL_CLIP_ORIGIN)` again when using `DrawCallback_ResetRenderState`, - at it appear to stall some drivers. (#2186, #3998, #3146, #3143, #8640) + - OpenGL3: added `ImGui_ImplOpenGL3_SetClipOrigin()` to specify origin between + `GL_LOWER_LEFT` (new default), `GL_UPPER_LEFT` and `0` (autodetect, old default). + - OpenGL3: avoid querying `glGetIntegerv(GL_CLIP_ORIGIN)` multiple times when using + when using default and using `DrawCallback_ResetRenderState`, at it appear to stall + some drivers. (#2186, #3998, #3146, #3143, #8640) - SDL2: fixed querying framebuffer scale/density when using Metal without going through a SDL_Renderer. (#5592) [@lailoken] - SDLRenderer3: restore any temporarily modified texture scale modes at the of `RenderDrawData()`. (#9378) From ed73ef4e84c9488256c5710de6ff1ebc2c9a8496 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Oct 2026 19:20:39 +0200 Subject: [PATCH 037/245] Backends: OpenGL3: fixed build for WebGL, ES2/ES3. (#2186, #3998, #3146, #3143, #8640) Amend fe33b77 --- backends/imgui_impl_opengl3.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 568067c5f..d9cf487c5 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -192,6 +192,10 @@ #define IMGUI_IMPL_OPENGL_LOADER_IMGL3W #include "imgui_impl_opengl3_loader.h" #endif +#ifndef GL_LOWER_LEFT +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#endif // Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension #ifndef IMGUI_IMPL_OPENGL_ES2 @@ -529,7 +533,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (bd->ClipOriginCurrent == 0) { bd->ClipOriginCurrent = GL_LOWER_LEFT; -#if defined(GL_CLIP_ORIGIN) +#ifdef GL_CLIP_ORIGIN if (bd->HasClipOrigin) glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&bd->ClipOriginCurrent); #endif From 68bd43b2b455168571f99794132df136cc45329e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Oct 2026 18:00:45 +0200 Subject: [PATCH 038/245] Tables: fixed a bug tracking topology changes (insert new columns in the middle) when the table is not Reorderable. (#9570, #9108, #9572) --- docs/CHANGELOG.txt | 3 +++ imgui_tables.cpp | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e0d0d9264..e341b0296 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,9 @@ Other Changes: - Tables: - Fixed a bug restoring correct .ini columns order when table use is Sortable but had no user changes. (regression from 1.92.9). (#9519, #9108) + - Fixed a bug tracking topology changes (insert new columns in the middle) + when the table is not _Reorderable: new columns would be ordered incorrectly. + (#9570, #9108, #9572) [@lailoken] - InpuText: - Fixed a crash in some cases when using Home key in a WordWrap+ReadOnly field. (#9561) - Selectable: diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b3e0458eb..5ba6cb28f 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -4107,6 +4107,12 @@ static int IMGUI_CDECL TableFixDisplayOrderComparer(const void* lhs, const void* // Fix invalid display order data: compact values (0,1,3 -> 0,1,2); preserve relative order (0,3,1 -> 0,2,1); deduplicate (0,4,1,1 -> 0,3,1,2) void ImGui::TableFixDisplayOrder(ImGuiTable* table) { + if ((table->Flags & ImGuiTableFlags_Reorderable) == 0) + { + for (int n = 0; n < table->ColumnsCount; n++) + table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n; + return; + } ImGuiContext& g = *GImGui; g.TempBuffer.reserve((int)(sizeof(ImGuiTableFixDisplayOrderColumnData) * table->ColumnsCount)); // FIXME: Maybe wrap those two lines as a helper. ImGuiTableFixDisplayOrderColumnData* fdo_columns = (ImGuiTableFixDisplayOrderColumnData*)(void*)g.TempBuffer.Data; From 4989b4c75491f2908aa3072ed3041245e6f98c09 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Oct 2026 19:41:20 +0200 Subject: [PATCH 039/245] Fonts: added IMGUI_DISABLE_STB_TRUETYPE. (#9573) --- docs/CHANGELOG.txt | 2 ++ imconfig.h | 4 +++- imgui.cpp | 1 + imgui_internal.h | 2 +- 4 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e341b0296..203922ab1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -94,6 +94,8 @@ Other Changes: - (Internal) ImFontLoader: reworked `FontSrcContainsGlyph`, `FontBakedLoadGlyph` signatures to take raw glyph index instead of codepoint. Added `FontSrcGetGlyphIndexFromCodepoint`. (#9559, #5647, #9540, #8466, #8465) + - Added `IMGUI_DISABLE_STB_TRUETYPE` to completely omit the stb_truetype loader + code + stb_truetype.h code. (#9573) - ColorEdit: - ColorButton, ColorEdit, ColorPicker: cancel-out alpha caused by BeginDisabled() so disabled color buttons have the same color as non-disabled oness. (#9511) diff --git a/imconfig.h b/imconfig.h index a25fa89af..d9c05692f 100644 --- a/imconfig.h +++ b/imconfig.h @@ -72,7 +72,8 @@ //---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) //#define IMGUI_USE_WCHAR32 -//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version +//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version. +// This is for if you already embed a copy of those library in your code and don't want duplicate code in your binary. // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" @@ -102,6 +103,7 @@ //---- Use stb_truetype to build and rasterize the font atlas (default) // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. //#define IMGUI_ENABLE_STB_TRUETYPE +//#define IMGUI_DISABLE_STB_TRUETYPE //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. // This will be inlined as part of ImVec2 and ImVec4 class declarations. diff --git a/imgui.cpp b/imgui.cpp index ef9ca7f29..e1b1b7dce 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16741,6 +16741,7 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL")) { const ImFontLoader* loader_current = atlas->FontLoader; + IM_UNUSED(loader_current); BeginDisabled(!atlas->RendererHasTextures); #ifdef IMGUI_ENABLE_STB_TRUETYPE const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype(); diff --git a/imgui_internal.h b/imgui_internal.h index b0f8856f8..538005fc9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -126,7 +126,7 @@ Index of this file: // Enable stb_truetype by default unless FreeType is enabled. // You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together. -#ifndef IMGUI_ENABLE_FREETYPE +#if !defined(IMGUI_ENABLE_FREETYPE) && !defined(IMGUI_ENABLE_STB_TRUETYPE) && !defined(IMGUI_DISABLE_STB_TRUETYPE) #define IMGUI_ENABLE_STB_TRUETYPE #endif From 71fc553bc48ae75f52b9911834cc83b094fae740 Mon Sep 17 00:00:00 2001 From: tqjxlm Date: Tue, 6 Oct 2026 14:09:10 +0100 Subject: [PATCH 040/245] Backends: Vulkan: support rendering inside passes with multiple color attachments. (#9574) We render to the first color attachment and leave the other ones untouched (color write mask 0). With dynamic rendering, create one blend attachment state per PipelineRenderingCreateInfo::colorAttachmentCount. Requires the independentBlend device feature. --- backends/imgui_impl_vulkan.cpp | 14 +++++++++++--- backends/imgui_impl_vulkan.h | 1 + docs/CHANGELOG.txt | 4 ++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 80b9d58ab..7017a6fd1 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-10-06: Added support for dynamic rendering with multiple color attachments (PipelineRenderingCreateInfo.colorAttachmentCount > 1): we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-09-03: Added for support for multiple Vulkan contexts with custom loaders. (#6616) // 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. (#9378) @@ -1062,7 +1063,14 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; ms_info.rasterizationSamples = (info->MSAASamples != 0) ? info->MSAASamples : VK_SAMPLE_COUNT_1_BIT; - VkPipelineColorBlendAttachmentState color_attachment[1] = {}; + // Blend into the first color attachment. With dynamic rendering, other color attachments of the rendering are left untouched (requires independentBlend feature). + int color_attachment_count = 1; +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + if (bd->VulkanInitInfo.UseDynamicRendering && info->PipelineRenderingCreateInfo.colorAttachmentCount > 1) + color_attachment_count = (int)info->PipelineRenderingCreateInfo.colorAttachmentCount; +#endif + ImVector color_attachment; + color_attachment.resize(color_attachment_count, VkPipelineColorBlendAttachmentState()); // colorWriteMask = 0 color_attachment[0].blendEnable = VK_TRUE; color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; @@ -1077,8 +1085,8 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc VkPipelineColorBlendStateCreateInfo blend_info = {}; blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - blend_info.attachmentCount = 1; - blend_info.pAttachments = color_attachment; + blend_info.attachmentCount = (uint32_t)color_attachment.Size; + blend_info.pAttachments = color_attachment.Data; ImVector dynamic_states = info->ExtraDynamicStates; dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 0f2da5e2d..44c76c9a0 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -101,6 +101,7 @@ struct ImGui_ImplVulkan_PipelineInfo // - As an convenience, by setting DescriptorPoolSize > 0 the backend will create one for you. // - About dynamic rendering: // - When using dynamic rendering, set UseDynamicRendering=true + fill PipelineInfoMain.PipelineRenderingCreateInfo structure. +// - PipelineRenderingCreateInfo may describe multiple color attachments: we render to the first one and leave the others untouched. This requires the 'independentBlend' device feature. struct ImGui_ImplVulkan_InitInfo { uint32_t ApiVersion; // Fill with API version of Instance, e.g. VK_API_VERSION_1_3 or your value of VkApplicationInfo::apiVersion. May be lower than header version (VK_HEADER_VERSION_COMPLETE) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 203922ab1..9f595ba55 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -171,6 +171,10 @@ Other Changes: Note: this callback is only supported by selected rendering backends: most other graphics API don't have the equivalent of `SDL_SetTextureScaleMode()` and the callback won't work with them. - Vulkan: added for support for multiple Vulkan contexts with custom loaders. (#6616) [@lstalmir] + - Vulkan: added support for rendering inside a render pass with multiple color attachments + (e.g. when merged with other passes): we render to the first color attachment and leave the + other ones untouched. (with dynamic rendering, `PipelineRenderingCreateInfo` may describe multiple + color attachments. This requires the `independentBlend` device feature). (#9574) [@tqjxlm] - WebGPU: fixed passing non-integer sizes to `wgpuRenderPassEncoderSetViewport()` when `FramebufferScale` is >1.0f. (#9515, #8628) [@WayU] - WebGPU: update to build with wgpu-native 29.0+. (#9377, #9532, #9530) [@lucascompython, @ivan-enzhaev] From f502f9c980ce8c71ac0a8e326637a7bc71b06c03 Mon Sep 17 00:00:00 2001 From: tqjxlm Date: Tue, 6 Oct 2026 14:09:10 +0100 Subject: [PATCH 041/245] Backends: Metal, Metal4: support rendering inside passes with multiple color attachments. (#9574) Key the pipeline cache on all color attachment pixel formats of the render pass descriptor passed to backend's NewFrame(). --- backends/imgui_impl_metal.mm | 32 ++++++++++++++++++++++++++------ backends/imgui_impl_metal4.mm | 32 ++++++++++++++++++++++++++------ docs/CHANGELOG.txt | 6 ++++-- 3 files changed, 56 insertions(+), 14 deletions(-) diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 55b33de14..43019b54f 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -16,6 +16,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-04-28: Added support for standard draw callbacks (in platform_io): DrawCallback_SetSamplerLinear and DrawCallback_SetSamplerNearest. (#9378, #9381) // 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState (others are not yet supported). (#9378) @@ -58,14 +59,16 @@ - (instancetype)initWithBuffer:(id)buffer; @end +#define IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS 8 // Metal's limit (see Metal Feature Set Tables). Not configurable. + // An object that encapsulates the data necessary to uniquely identify a // render pipeline state. These are used as cache keys. @interface FramebufferDescriptor : NSObject @property (nonatomic, assign) unsigned long sampleCount; -@property (nonatomic, assign) MTLPixelFormat colorPixelFormat; @property (nonatomic, assign) MTLPixelFormat depthPixelFormat; @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat; - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor; +- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index; @end @interface MetalTexture : NSObject @@ -477,23 +480,33 @@ void ImGui_ImplMetal_Shutdown() #pragma mark - FramebufferDescriptor implementation @implementation FramebufferDescriptor +{ + MTLPixelFormat _colorPixelFormats[IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS]; +} + - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor { if ((self = [super init])) { _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount; - _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat; + for (NSUInteger n = 0; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) + _colorPixelFormats[n] = renderPassDescriptor.colorAttachments[n].texture.pixelFormat; _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat; _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat; } return self; } +- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index +{ + return _colorPixelFormats[index]; +} + - (nonnull id)copyWithZone:(nullable NSZone*)zone { FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; copy.sampleCount = self.sampleCount; - copy.colorPixelFormat = self.colorPixelFormat; + memcpy(copy->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)); copy.depthPixelFormat = self.depthPixelFormat; copy.stencilPixelFormat = self.stencilPixelFormat; return copy; @@ -502,10 +515,12 @@ void ImGui_ImplMetal_Shutdown() - (NSUInteger)hash { NSUInteger sc = _sampleCount & 0x3; - NSUInteger cf = _colorPixelFormat & 0x3FF; + NSUInteger cf = _colorPixelFormats[0] & 0x3FF; NSUInteger df = _depthPixelFormat & 0x3FF; NSUInteger sf = _stencilPixelFormat & 0x3FF; NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc; + for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) + hash = hash * 31 + _colorPixelFormats[n]; return hash; } @@ -515,7 +530,7 @@ void ImGui_ImplMetal_Shutdown() if (![other isKindOfClass:[FramebufferDescriptor class]]) return NO; return other.sampleCount == self.sampleCount && - other.colorPixelFormat == self.colorPixelFormat && + memcmp(other->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)) == 0 && other.depthPixelFormat == self.depthPixelFormat && other.stencilPixelFormat == self.stencilPixelFormat; } @@ -661,7 +676,7 @@ void ImGui_ImplMetal_Shutdown() pipelineDescriptor.fragmentFunction = fragmentFunction; pipelineDescriptor.vertexDescriptor = vertexDescriptor; pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount; - pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat; + pipelineDescriptor.colorAttachments[0].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:0]; pipelineDescriptor.colorAttachments[0].blendingEnabled = YES; pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha; @@ -669,6 +684,11 @@ void ImGui_ImplMetal_Shutdown() pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne; pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha; + for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) // Don't write to other color attachments, if any. + { + pipelineDescriptor.colorAttachments[n].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:n]; + pipelineDescriptor.colorAttachments[n].writeMask = MTLColorWriteMaskNone; + } pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat; pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat; diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index 73f8c5905..2f9a53bdb 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -19,6 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-07: Metal 4: Added metal-cpp support. (#9461) // 2026-07-02: Metal 4: Added new Metal 4 backend implementation. (#9458) @@ -46,14 +47,16 @@ struct ImGui_Metal4_ConstantData - (instancetype)initWithBuffer:(id)buffer; @end +#define IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS 8 // Metal's limit (see Metal Feature Set Tables). Not configurable. + // An object that encapsulates the data necessary to uniquely identify a // render pipeline state. These are used as cache keys. @interface FramebufferDescriptor : NSObject @property (nonatomic, assign) unsigned long sampleCount; -@property (nonatomic, assign) MTLPixelFormat colorPixelFormat; @property (nonatomic, assign) MTLPixelFormat depthPixelFormat; @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat; - (instancetype)initWithRenderPassDescriptor:(MTL4RenderPassDescriptor*)renderPassDescriptor; +- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index; @end @interface MetalTexture : NSObject @@ -514,23 +517,33 @@ void ImGui_ImplMetal4_Shutdown() #pragma mark - FramebufferDescriptor implementation @implementation FramebufferDescriptor +{ + MTLPixelFormat _colorPixelFormats[IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS]; +} + - (instancetype)initWithRenderPassDescriptor:(MTL4RenderPassDescriptor*)renderPassDescriptor { if ((self = [super init])) { _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount; - _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat; + for (NSUInteger n = 0; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) + _colorPixelFormats[n] = renderPassDescriptor.colorAttachments[n].texture.pixelFormat; _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat; _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat; } return self; } +- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index +{ + return _colorPixelFormats[index]; +} + - (nonnull id)copyWithZone:(nullable NSZone*)zone { FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; copy.sampleCount = self.sampleCount; - copy.colorPixelFormat = self.colorPixelFormat; + memcpy(copy->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)); copy.depthPixelFormat = self.depthPixelFormat; copy.stencilPixelFormat = self.stencilPixelFormat; return copy; @@ -539,10 +552,12 @@ void ImGui_ImplMetal4_Shutdown() - (NSUInteger)hash { NSUInteger sc = _sampleCount & 0x3; - NSUInteger cf = _colorPixelFormat & 0x3FF; + NSUInteger cf = _colorPixelFormats[0] & 0x3FF; NSUInteger df = _depthPixelFormat & 0x3FF; NSUInteger sf = _stencilPixelFormat & 0x3FF; NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc; + for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) + hash = hash * 31 + _colorPixelFormats[n]; return hash; } @@ -552,7 +567,7 @@ void ImGui_ImplMetal4_Shutdown() if (![other isKindOfClass:[FramebufferDescriptor class]]) return NO; return other.sampleCount == self.sampleCount && - other.colorPixelFormat == self.colorPixelFormat && + memcmp(other->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)) == 0 && other.depthPixelFormat == self.depthPixelFormat && other.stencilPixelFormat == self.stencilPixelFormat; } @@ -719,7 +734,7 @@ fragment half4 fragment_main(VertexOut in [[stage_in]], pipelineDescriptor.fragmentFunction = fragmentFunction; pipelineDescriptor.vertexDescriptor = vertexDescriptor; pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount; - pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat; + pipelineDescriptor.colorAttachments[0].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:0]; pipelineDescriptor.colorAttachments[0].blendingEnabled = YES; pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha; @@ -727,6 +742,11 @@ fragment half4 fragment_main(VertexOut in [[stage_in]], pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne; pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha; + for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) // Don't write to other color attachments, if any. + { + pipelineDescriptor.colorAttachments[n].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:n]; + pipelineDescriptor.colorAttachments[n].writeMask = MTLColorWriteMaskNone; + } pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat; pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9f595ba55..12c9de64c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -152,6 +152,9 @@ Other Changes: - Style Editor: fixed style/colors combo box applying style when opening Combo. - Backends: - QNX: added QNX Screen backend. (#9492) [@mgorchak-blackberry] + - Metal, Metal4: added support for rendering inside a render pass with multiple color + attachments (e.g. when merged with other passes): we render to the first color attachment + and leave the other ones untouched. (#9574) [@tqjxlm] - OpenGL2, OpenGL3: added support for `platform_io.DrawCallback_SetSamplerFromTex` draw callback to request using the sampler associated already associated to a texture. (#9378) - OpenGL2, OpenGL3: fixed `DrawCallback_ResetRenderState` handler not reseting all states @@ -173,8 +176,7 @@ Other Changes: - Vulkan: added for support for multiple Vulkan contexts with custom loaders. (#6616) [@lstalmir] - Vulkan: added support for rendering inside a render pass with multiple color attachments (e.g. when merged with other passes): we render to the first color attachment and leave the - other ones untouched. (with dynamic rendering, `PipelineRenderingCreateInfo` may describe multiple - color attachments. This requires the `independentBlend` device feature). (#9574) [@tqjxlm] + other ones untouched. (#9574) [@tqjxlm] - WebGPU: fixed passing non-integer sizes to `wgpuRenderPassEncoderSetViewport()` when `FramebufferScale` is >1.0f. (#9515, #8628) [@WayU] - WebGPU: update to build with wgpu-native 29.0+. (#9377, #9532, #9530) [@lucascompython, @ivan-enzhaev] From 6335dfb19c4bda4bee269d33403db4e19ecc17fc Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 28 Apr 2026 00:04:59 +0200 Subject: [PATCH 042/245] (Breaking) DrawList: removed half pixel offset from ImDrawList::AddLine(). (#9504) --- imgui.cpp | 6 ++++ imgui_draw.cpp | 90 ++++++++++++++++++++++++++++++++++++++++-------- imgui_internal.h | 17 +++++++++ 3 files changed, 99 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e1b1b7dce..e2954904c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1374,6 +1374,9 @@ static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multi // [SECTION] FORWARD DECLARATIONS //------------------------------------------------------------------------- +extern bool g_LEGACY_STROKES; +bool g_LEGACY_STROKES = false; + static void SetCurrentWindow(ImGuiWindow* window); static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); @@ -5921,6 +5924,9 @@ void ImGui::NewFrame() g.DebugBeginReturnValueCullDepth = -1; #endif + g_LEGACY_STROKES = g.IO.KeyShift; + ImGui::Checkbox("g_LEGACY_STROKES", &g_LEGACY_STROKES); + CallContextHooks(&g, ImGuiContextHookType_NewFramePost); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e2085f6e6..05772300d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1484,11 +1484,20 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } } +extern bool g_LEGACY_STROKES; + void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; + if (g_LEGACY_STROKES) + { + const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; + AddPolyline(points, 2, col, thickness); + return; + } + + const ImVec2 points[2] = { p1, p2 }; AddPolyline(points, 2, col, thickness); } @@ -1496,16 +1505,46 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th { if ((col & IM_COL32_A_MASK) == 0) return; - const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness); + + if (g_LEGACY_STROKES) + { + const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. + AddPolyline(points, 2, col, thickness); + return; + } + + if (ImIsTruncated4(min_x, max_x, y, thickness)) + { + PrimReserve(6, 4); + PrimRect(ImVec2(min_x, y), ImVec2(max_x, y + thickness), col); + } + else + { + AddRectFilled(ImVec2(min_x, y), ImVec2(max_x, y + thickness), col); + } } void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - const ImVec2 points[2] = { ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness); + + if (g_LEGACY_STROKES) + { + const ImVec2 points[2] = { ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f) }; // Same as AddLine() above. + AddPolyline(points, 2, col, thickness); + return; + } + + if (ImIsTruncated4(x, min_y, max_y, thickness)) + { + PrimReserve(6, 4); + PrimRect(ImTrunc(ImVec2(x, min_y)), ImTrunc(ImVec2(x + thickness, max_y)), col); + } + else + { + AddRectFilled(ImVec2(x, min_y), ImVec2(x + thickness, max_y), col); + } } // p_min = upper-left, p_max = lower-right @@ -1525,10 +1564,19 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if ((col & IM_COL32_A_MASK) == 0) return; - if (Flags & ImDrawListFlags_AntiAliasedLines) - PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); - else - PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. + + if (g_LEGACY_STROKES) + { + if (Flags & ImDrawListFlags_AntiAliasedLines) + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); + else + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. + PathStroke(col, thickness, ImDrawFlags_Closed); + return; + } + + const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); + PathRect(p_min + offset, p_max - offset, rounding - thickness * 0.5f, flags); PathStroke(col, thickness, ImDrawFlags_Closed); } @@ -1615,10 +1663,14 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) return; + if (g_LEGACY_STROKES) + radius -= 0.5f; + else + radius -= thickness * 0.5f; if (num_segments <= 0) { // Use arc with automatic segment count - _PathArcToFastEx(center, radius - 0.5f, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); + _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); _Path.Size--; } else @@ -1628,7 +1680,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); } PathStroke(col, thickness, ImDrawFlags_Closed); @@ -1664,9 +1716,14 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; + if (g_LEGACY_STROKES) + radius -= 0.5f; + else + radius -= thickness * 0.5f; + // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); PathStroke(col, thickness, ImDrawFlags_Closed); } @@ -1688,12 +1745,17 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co if ((col & IM_COL32_A_MASK) == 0) return; + ImVec2 r; + if (g_LEGACY_STROKES) + r = radius; + else + r = ImVec2(radius.x - thickness * 0.5f, radius.y - thickness * 0.5f); if (num_segments <= 0) - num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. + num_segments = _CalcCircleAutoSegmentCount(ImMax(r.x, r.y)); // A bit pessimistic, maybe there's a better computation to do here. // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; - PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1); + PathEllipticalArcTo(center, r, rot, 0.0f, a_max, num_segments - 1); PathStroke(col, thickness, ImDrawFlags_Closed); } diff --git a/imgui_internal.h b/imgui_internal.h index 538005fc9..31ee350ca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -548,6 +548,23 @@ inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } inline float ImExponentialMovingAverage(float avg, float sample, int n){ avg -= avg / (float)n; avg += sample / (float)n; return avg; } + +inline bool ImIsTruncated(float x) { return (float)(int)x == x; } +#ifdef IMGUI_ENABLE_SSE +// Returns true if all parameters are whole numbers. +inline bool ImIsTruncated4(float x, float y, float z, float w) +{ + __m128 v = _mm_set_ps(x, y, z, w); + __m128i i = _mm_cvttps_epi32(v); + return _mm_movemask_ps(_mm_cmpeq_ps(v, _mm_cvtepi32_ps(i))) == 0xF; +} +#else +inline bool ImIsTruncated4(float x, float y, float z, float w) +{ + return (float)(int)x == x && (float)(int)y == y && (float)(int)z == z && (float)(int)w == w; +} +#endif + IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Geometry From f73d8f40299a124ecc5222e477b0236180a475d3 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 28 Apr 2026 18:14:34 +0200 Subject: [PATCH 043/245] DrawList: added StrokePos flags: ImDrawFlags_StrokeInside, ImDrawFlags_StrokeOutside, ImDrawFlags_StrokeCenter, ImDrawFlags_StrokeLegacy. (#9504) --- imgui.h | 19 ++++++++----- imgui_draw.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 76 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index 8c5be4a44..9fab91ad1 100644 --- a/imgui.h +++ b/imgui.h @@ -30,7 +30,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.93.0 WIP" -#define IMGUI_VERSION_NUM 19297 +#define IMGUI_VERSION_NUM 19298 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -3321,6 +3321,13 @@ enum ImDrawFlags_ ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. //ImDrawFlags_Closed = 1, // Prior to 1.92.8 (May 2026), ImDrawFlags_Closed was guaranteed to be == 1<<0 == 1 for legacy compatibility reason. Hardcoded use of 1 or true should be replaced. + // Stroke position relative to the shape outline + ImDrawFlags_StrokeInside = 0 << 16, // Draw stroke inside of the shape outline (Default) + ImDrawFlags_StrokeCenter = 1 << 16, // Draw stroke at the center of the shape outline + ImDrawFlags_StrokeOutside = 2 << 16, // Draw stroke outside of the shape outline + ImDrawFlags_StrokeLegacy = 3 << 16, // Use legacy position + ImDrawFlags_StrokeMask_ = 0x03 << 16, + ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, }; @@ -3389,8 +3396,8 @@ struct ImDrawList // In future versions we will use textures to provide cheaper and higher-quality circles. // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); + IMGUI_API void AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, float thickness = 1.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); @@ -3398,11 +3405,11 @@ struct ImDrawList IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); - IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); + IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); - IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 05772300d..416b1cb45 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1501,7 +1501,7 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th AddPolyline(points, 2, col, thickness); } -void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness) +void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -1513,6 +1513,11 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th return; } + ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + if (stroke_pos == ImDrawFlags_StrokeCenter) + y -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + y -= thickness; if (ImIsTruncated4(min_x, max_x, y, thickness)) { PrimReserve(6, 4); @@ -1524,7 +1529,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th } } -void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness) +void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -1536,6 +1541,11 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th return; } + ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + if (stroke_pos == ImDrawFlags_StrokeCenter) + x += thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + x -= thickness; if (ImIsTruncated4(x, min_y, max_y, thickness)) { PrimReserve(6, 4); @@ -1576,7 +1586,20 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl } const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); - PathRect(p_min + offset, p_max - offset, rounding - thickness * 0.5f, flags); + const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + if (stroke_pos == ImDrawFlags_StrokeInside) + PathRect(p_min + offset, p_max - offset, rounding - thickness * 0.5f, flags); + else if (stroke_pos == ImDrawFlags_StrokeCenter) + PathRect(p_min, p_max, rounding, flags); + else if (stroke_pos == ImDrawFlags_StrokeOutside) + PathRect(p_min - offset, p_max + offset, rounding + thickness * 0.5f, flags); + else if (stroke_pos == ImDrawFlags_StrokeLegacy) + { + if (Flags & ImDrawListFlags_AntiAliasedLines) + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); + else + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. + } PathStroke(col, thickness, ImDrawFlags_Closed); } @@ -1658,15 +1681,26 @@ void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImV PathFillConvex(col); } -void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) +void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) return; if (g_LEGACY_STROKES) + { radius -= 0.5f; + } else - radius -= thickness * 0.5f; + { + const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + if (stroke_pos == ImDrawFlags_StrokeInside) + radius -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + radius += thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeLegacy) + radius -= 0.5f; + } + if (num_segments <= 0) { // Use arc with automatic segment count @@ -1711,15 +1745,25 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, } // Guaranteed to honor 'num_segments' -void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) +void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; if (g_LEGACY_STROKES) + { radius -= 0.5f; + } else - radius -= thickness * 0.5f; + { + const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + if (stroke_pos == ImDrawFlags_StrokeInside) + radius -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + radius += thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeLegacy) + radius -= 0.5f; + } // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; @@ -1740,16 +1784,26 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in } // Ellipse -void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments, float thickness) +void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; ImVec2 r; if (g_LEGACY_STROKES) + { r = radius; + } else - r = ImVec2(radius.x - thickness * 0.5f, radius.y - thickness * 0.5f); + { + r = radius; + ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + if (stroke_pos == ImDrawFlags_StrokeInside) + r -= ImVec2(thickness * 0.5f, thickness * 0.5f); + else if (stroke_pos == ImDrawFlags_StrokeOutside) + r += ImVec2(thickness * 0.5f, thickness * 0.5f); + } + if (num_segments <= 0) num_segments = _CalcCircleAutoSegmentCount(ImMax(r.x, r.y)); // A bit pessimistic, maybe there's a better computation to do here. From 43d829885e7bb918460fe0e3f4046092c3f335d5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 4 May 2026 18:38:39 +0200 Subject: [PATCH 044/245] DrawList: added ImDrawFlags_StrokeLegacy support to AddLine(). --- imgui.h | 2 +- imgui_draw.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 9fab91ad1..d3e4ed665 100644 --- a/imgui.h +++ b/imgui.h @@ -3395,7 +3395,7 @@ struct ImDrawList // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. // In future versions we will use textures to provide cheaper and higher-quality circles. // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. - IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, float thickness = 1.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 416b1cb45..8f27e0506 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1486,11 +1486,11 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr extern bool g_LEGACY_STROKES; -void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness) +void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; - if (g_LEGACY_STROKES) + if (g_LEGACY_STROKES || (flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; AddPolyline(points, 2, col, thickness); From 37f16412d59a0cb9d283e0ae1c93f2ef6d8799b5 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 28 Apr 2026 18:28:22 +0200 Subject: [PATCH 045/245] Fixed layout/pixel-perfect issues in various widgets (w/ g_LEGACY_STROKES toggle). (#9504) --- imgui.cpp | 16 ++++++++++++ imgui_tables.cpp | 22 +++++++++++++--- imgui_widgets.cpp | 65 +++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 89 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e2954904c..549973af2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7310,8 +7310,16 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) } if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) { + if (g_LEGACY_STROKES) + { float y = window->Pos.y + window->TitleBarHeight - 1; window->DrawList->AddLineH(window->Pos.x + border_size * 0.5f, window->Pos.x + window->Size.x - border_size * 0.5f, y, border_col, g.Style.FrameBorderSize); + } + else + { + float y = window->Pos.y + window->TitleBarHeight - g.Style.FrameBorderSize; + window->DrawList->AddLineH(window->Pos.x + border_size, window->Pos.x + window->Size.x - border_size, y, border_col, g.Style.FrameBorderSize); + } } } @@ -7379,7 +7387,12 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) + { + if (g_LEGACY_STROKES) window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5f, menu_bar_rect.Max.x - window_border_size * 0.5f, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + else + window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size, menu_bar_rect.Max.x - window_border_size, menu_bar_rect.Max.y - style.FrameBorderSize, GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + } } // Scrollbars @@ -18326,7 +18339,10 @@ void ImGui::DebugDrawLineExtents(ImU32 col) float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y); float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y); window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y1, col, 1.0f); + if (g_LEGACY_STROKES) window->DrawList->AddLineV(curr_x - 0.5f, line_y1, line_y2, col, 1.0f); + else + window->DrawList->AddLineV(curr_x, line_y1, line_y2, col, 1.0f); window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y2, col, 1.0f); } diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5ba6cb28f..469311bcf 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2947,6 +2947,8 @@ static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_ return table->BorderColorLight; } +extern bool g_LEGACY_STROKES; + // FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow) void ImGui::TableDrawBorders(ImGuiTable* table) { @@ -2961,7 +2963,11 @@ void ImGui::TableDrawBorders(ImGuiTable* table) // Draw inner border and resizing feedback ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); const float border_size = TABLE_BORDER_SIZE; - const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? 1.0f : 0.0f); + float draw_y1; + if (g_LEGACY_STROKES) + draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? 1.0f : 0.0f); + else + draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f); const float draw_y2_body = table->InnerRect.Max.y; const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; if (table->Flags & ImGuiTableFlags_BordersInnerV) @@ -3018,7 +3024,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) else if (table->Flags & ImGuiTableFlags_BordersOuterV) { inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); - inner_drawlist->AddLineV(outer_border.Max.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); + inner_drawlist->AddLineV(outer_border.Max.x - border_size, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); } else if (table->Flags & ImGuiTableFlags_BordersOuterH) { @@ -3029,9 +3035,15 @@ void ImGui::TableDrawBorders(ImGuiTable* table) if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) { // Draw bottom-most row border between it is above outer border. + const float h_inset = (table->Flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; const float border_y = table->RowPosY2; if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) + { + if (g_LEGACY_STROKES) inner_drawlist->AddLineH(table->BorderX1, table->BorderX2, border_y, table->BorderColorLight, border_size); + else + inner_drawlist->AddLineH(table->BorderX1 + h_inset, table->BorderX2 - h_inset, border_y, table->BorderColorLight, border_size); + } } inner_drawlist->PopClipRect(); @@ -3624,7 +3636,11 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label if (pass == 1) { // Draw border - draw_list->AddLine(bg_shape[0] - ImVec2(TABLE_BORDER_SIZE * 0.5f, 0.0f), bg_shape[3] - ImVec2(TABLE_BORDER_SIZE * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), TABLE_BORDER_SIZE); + const float border_size = TABLE_BORDER_SIZE; + if (g_LEGACY_STROKES) + draw_list->AddLine(bg_shape[0] - ImVec2(border_size * 0.5f, 0.0f), bg_shape[3] - ImVec2(border_size * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), border_size); + else + draw_list->AddLine(bg_shape[0] + ImVec2(border_size * 0.5f, 0.0f), bg_shape[3] + ImVec2(border_size * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), border_size); } } PopClipRect(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ceabc13ba..8413344a8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -903,6 +903,8 @@ bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None); } +extern bool g_LEGACY_STROKES; + // Button to close a window bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) { @@ -932,7 +934,7 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact); const ImU32 cross_col = GetColorU32(ImGuiCol_Text); - const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); + const ImVec2 cross_center = g_LEGACY_STROKES ? (bb.GetCenter() - ImVec2(0.5f, 0.5f)) : bb.GetCenter(); const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; const float cross_thickness = 1.0f * (float)(int)g.Style._MainScale; // FIXME-DPI window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness); @@ -1757,7 +1759,11 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end const float sep1_x1 = pos.x; const float sep2_x2 = bb.Max.x; - const float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.999f); + float seps_y; + if (g_LEGACY_STROKES) + seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.999f); + else + seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + (-separator_thickness * 0.5f + 1.0f) + 0.999f); // Align hline vertically, and snap to pixels. const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f); const ImVec2 label_pos(pos.x + padding.x + ImMax(0.0f, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y); // FIXME-ALIGN @@ -5759,7 +5765,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ state->CursorAnim += io.DeltaTime; bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); - ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); + ImRect cursor_screen_rect; + if (g_LEGACY_STROKES) + cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); + else + cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 1.0f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.0f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) draw_window->DrawList->AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, GetColorU32(ImGuiCol_InputTextCursor), style.InputTextCursorSize); @@ -7309,16 +7319,27 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) return; ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; - float x1 = ImTrunc(parent_data->DrawLinesX1); + float x1; + if (g_LEGACY_STROKES) + x1 = ImTrunc(parent_data->DrawLinesX1); + else + x1 = ImTrunc(parent_data->DrawLinesX1 - g.Style.TreeLinesSize * 0.5f) + g.Style.TreeLinesSize * 0.5f; // Draw line centered at X1, but snap to pixels boundary. float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); - float y = ImTrunc(target_pos.y); + float y; + if (g_LEGACY_STROKES) + y = ImTrunc(target_pos.y); + else + y = ImTrunc(target_pos.y) + g.Style.TreeLinesSize * 0.5f; float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f; parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding); if (x1 >= x2) return; if (rounding > 0.0f) { - x1 += 0.5f + rounding; + if (g_LEGACY_STROKES) + x1 += 0.5f + rounding; + else + x1 += rounding; window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3); if (x1 < x2) window->DrawList->PathLineTo(ImVec2(x2, y)); @@ -7326,7 +7347,11 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) } else { - window->DrawList->AddLineH(x1, x2, y, GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + // We use AddLine() instead of AddLineH() as we provide coordinates for line center, + // in order to make the code use same coordinates for both rounded and non-rounded version. + if (!g_LEGACY_STROKES) + x1 += g.Style.TreeLinesSize * 0.5f; // Avoid overdraw + window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } } @@ -7349,10 +7374,15 @@ void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) y2 = ImMin(y2, window->ClipRect.Max.y); if (y2 <= y1) return; - float x = ImTrunc(data->DrawLinesX1); + float x; + if (g_LEGACY_STROKES) + x = ImTrunc(data->DrawLinesX1); + else + x = ImTrunc(data->DrawLinesX1 - g.Style.TreeLinesSize * 0.5f) + g.Style.TreeLinesSize * 0.5f; // Draw line centered at X1, but snap to pixels boundary. if (data->DrawLinesTableColumn != -1) TablePushColumnChannel(data->DrawLinesTableColumn); - window->DrawList->AddLineV(x, y1, y2, GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + // We use AddLine() instead of AddLineV() as we provide coordinates for line center, + window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); if (data->DrawLinesTableColumn != -1) TablePopColumnChannel(); } @@ -10944,8 +10974,18 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) { // Might be moved to TabItemBackground() ? - ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); - ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImVec2 tl; + ImVec2 tr; + if (g_LEGACY_STROKES) + { + tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); + tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); + } + else + { + tl = bb.GetTL() + ImVec2(0, style.TabBarOverlineSize * 0.5f); + tr = bb.GetTR() + ImVec2(0, style.TabBarOverlineSize * 0.5f); + } ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline); if (style.TabRounding > 0.0f) { @@ -10956,7 +10996,10 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } else { + if (g_LEGACY_STROKES) display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize); + else + display_draw_list->AddLine(tl, tr, overline_col, style.TabBarOverlineSize); } } RenderNavCursor(bb, id); From ae06573c9a2f84632347f034099e4c5d96845620 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 27 Apr 2026 23:39:17 +0200 Subject: [PATCH 046/245] DrawList: Textured Round Corners: first version. (#1962) --- imgui.h | 9 ++- imgui_draw.cpp | 155 ++++++++++++++++++++++++++++++++++++++++++++++- imgui_internal.h | 4 +- 3 files changed, 163 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index d3e4ed665..89371a239 100644 --- a/imgui.h +++ b/imgui.h @@ -3207,6 +3207,10 @@ struct ImGuiSelectionExternalStorage #define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) #endif +#ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX +#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) +#endif + // ImDrawIdx: vertex index. [Compile-time configurable type] // - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). // - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. @@ -3373,6 +3377,7 @@ struct ImDrawList ImVector _CallbacksDataBuf; // [Internal] float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content. float _InvFringeScale; // [internal] 1.0 / _FringeScale // FIXME: Consider renaming to _PixelDensity. + bool _FringeScaleIsInteger; // [Internal] true if _FringeScale is a whole number, used to select fast path for rendering const char* _OwnerName; // Pointer to owner window's name for debugging // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData(). @@ -3517,6 +3522,7 @@ struct ImDrawList IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); + IMGUI_API void _AddMirrored9Slice(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); }; // All draw data to render a Dear ImGui frame @@ -3877,7 +3883,8 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + ImVec4 TexUvCornerFills[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX]; // UVs for baked anti-aliased corners int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8f27e0506..dee1a1ab3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -725,6 +725,7 @@ void ImDrawList::_SetPixelDensity(float pixel_density) IM_ASSERT(pixel_density > 0.0f); _FringeScale = 1.0f / pixel_density; _InvFringeScale = pixel_density; + _FringeScaleIsInteger = ImIsTruncated(_FringeScale); } // Reserve space for a number of vertices and indices. @@ -1603,14 +1604,84 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathStroke(col, thickness, ImDrawFlags_Closed); } +void ImDrawList::_AddMirrored9Slice(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags) +{ + // 9-slice with corner mirroring + const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); + const ImVec2 uv_tr(tex_uvs.z, tex_uvs.y); + const ImVec2 uv_br(tex_uvs.z, tex_uvs.w); + const ImVec2 uv_bl(tex_uvs.x, tex_uvs.w); + + PrimReserve(9 * 2 * 3, 4 * 4); + + const float r_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? r : 0.0f; + const float r_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? r : 0.0f; + const float r_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? r : 0.0f; + const float r_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? r : 0.0f; + + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + + PrimWriteVtx(ImVec2(p_min.x, p_min.y), uv_tl, col); + PrimWriteVtx(ImVec2(p_min.x + r_tl, p_min.y), uv_tr, col); + PrimWriteVtx(ImVec2(p_max.x - r_tr, p_min.y), uv_tr, col); + PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv_tl, col); + + PrimWriteVtx(ImVec2(p_min.x, p_min.y + r_tl), uv_bl, col); + PrimWriteVtx(ImVec2(p_min.x + r_tl, p_min.y + r_tl), uv_br, col); + PrimWriteVtx(ImVec2(p_max.x - r_tr, p_min.y + r_tr), uv_br, col); + PrimWriteVtx(ImVec2(p_max.x, p_min.y + r_tr), uv_bl, col); + + PrimWriteVtx(ImVec2(p_min.x, p_max.y - r_bl), uv_bl, col); + PrimWriteVtx(ImVec2(p_min.x + r_bl, p_max.y - r_bl), uv_br, col); + PrimWriteVtx(ImVec2(p_max.x - r_br, p_max.y - r_br), uv_br, col); + PrimWriteVtx(ImVec2(p_max.x, p_max.y - r_br), uv_bl, col); + + PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv_tl, col); + PrimWriteVtx(ImVec2(p_min.x + r_bl, p_max.y), uv_tr, col); + PrimWriteVtx(ImVec2(p_max.x - r_br, p_max.y ), uv_tr, col); + PrimWriteVtx(ImVec2(p_max.x, p_max.y), uv_tl, col); + + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + PrimWriteIdx(idx+4); PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); + PrimWriteIdx(idx+4); PrimWriteIdx(idx+1); PrimWriteIdx(idx+5); + idx++; + } + idx++; + } +} + void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; - if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + + if (ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated(rounding)) { - PrimReserve(6, 4); - PrimRect(p_min, p_max, col); + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; + + rounding = ImMin(rounding, ImFabs(p_max.x - p_min.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(p_max.y - p_min.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + + const int s_rounding = (int)rounding; + if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + PrimReserve(6, 4); + PrimRect(p_min, p_max, col); + } + else if (s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + { + ImVec4 tex_uvs = _Data->TexUvCornerFills[s_rounding - 1]; + _AddMirrored9Slice(p_min, p_max, col, ImMax(2.0f, (float)s_rounding), tex_uvs, flags); + } + else + { + PathRect(p_min, p_max, (float)s_rounding, flags); + PathFillConvex(col); + } } else { @@ -3754,6 +3825,82 @@ static void ImFontAtlasBuildUpdateTexDataBasic(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); } +static ImU8 SampleCorner(float x, float y, float cx, float cy, float r) +{ + const float dx = ImMin(x, cx) - cx; + const float dy = ImMin(y, cy) - cy; + const float d = ImSqrt(dx*dx + dy*dy); + const float aa_width = 1.0f; + return (ImU8)(ImClamp(1.0f - (d - r + aa_width * 0.5f) / aa_width, 0.0f, 1.0f) * 255.0f); +} + +static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) +{ + // Pack and store identifier so we can refresh UV coordinates on texture resize. + ImTextureData* tex = atlas->TexData; + ImFontAtlasBuilder* builder = atlas->Builder; + + ImFontAtlasRect r; + bool add_and_draw = atlas->GetCustomRect(builder->PackIdCornersTexData, &r) == false; + if (add_and_draw) + { + ImVec2i pack_size(0, 0); + for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) + { + pack_size.x += ImMax(2, i+1) + 2; + pack_size.y = ImMax(pack_size.y, (i+1) + 2); + } + builder->PackIdCornersTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdCornersTexData != ImFontAtlasRectId_Invalid); + } + + int x = r.x; + int y = r.y; + for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) // +1 because of the zero-width row + { + const int s = ImMax(2, n+1); // We need at least 2px so that stretching has solid color. + const int w = s + 2; + const int h = s + 2; + + // Corner circle + const float cx = 1.0f + (float)(n+1); + const float cy = 1.0f + (float)(n+1); + const float rad = (float)(n+1); + IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds before we start writing pixels + + // Write each slice + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) + { + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(x, y); + const int pitch = tex->Width; + for (int ly = 0; ly < h; ly++) + { + for (int lx = 0; lx < h; lx++) + write_ptr[lx] = SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, rad); + write_ptr += pitch; + } + } + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(x, y); + const int pitch = tex->Width; + for (int ly = 0; ly < h; ly++) + { + for (int lx = 0; lx < h; lx++) + write_ptr[lx] = IM_COL32(255, 255, 255, SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, rad)); + write_ptr += pitch; + } + } + + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; + atlas->TexUvCornerFills[n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + + x += w; + } +} + static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) { if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) @@ -4189,6 +4336,7 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; shared_data->TexUvLines = atlas->TexUvLines; + shared_data->TexUvCornerFills = atlas->TexUvCornerFills; } } @@ -4207,6 +4355,7 @@ static void ImFontAtlasBuildUpdateTexData(ImFontAtlas* atlas) { ImFontAtlasBuildUpdateTexDataBasic(atlas); ImFontAtlasBuildUpdateTexDataLines(atlas); + ImFontAtlasBuildUpdateTexDataCorners(atlas); } // Create a new texture, discard previous one diff --git a/imgui_internal.h b/imgui_internal.h index 31ee350ca..e6a9d0321 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -921,6 +921,7 @@ struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) + const ImVec4* TexUvCornerFills; // UV of rounded corner (== FontAtlas->TexUvCornerFills) ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current font (used for simplified AddText overload) float FontSize; // Current font size (used for simplified AddText overload) @@ -4055,8 +4056,9 @@ struct ImFontAtlasBuilder // Custom rectangle identifiers ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; + ImFontAtlasRectId PackIdCornersTexData; - ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } + ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdCornersTexData = -1; } }; IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); From 26652204093514cd1ff11e30914fb8d1a56b5a94 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 23 Apr 2026 12:10:26 +0300 Subject: [PATCH 047/245] DrawList: Textured Round Corners: implemented faster render path for stroked rectangles. (#1962) - added check to render simpler geometry when (stroked) rectangle has integer coords - render non.rounded with 4 non-AA rectangles - added textures for corners of 1-3 thickness and 1-16 rounding - use textured corners when possible, or fallback to generic one --- imgui.h | 7 +- imgui_draw.cpp | 270 +++++++++++++++++++++++++++++++++++++++++++++-- imgui_internal.h | 1 + 3 files changed, 269 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index 89371a239..87ddae804 100644 --- a/imgui.h +++ b/imgui.h @@ -3210,6 +3210,9 @@ struct ImGuiSelectionExternalStorage #ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX #define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) #endif +#ifndef IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX +#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (3) +#endif // ImDrawIdx: vertex index. [Compile-time configurable type] // - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). @@ -3522,7 +3525,8 @@ struct ImDrawList IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); - IMGUI_API void _AddMirrored9Slice(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); + IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); + IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); }; // All draw data to render a Dear ImGui frame @@ -3885,6 +3889,7 @@ struct ImFontAtlas ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines ImVec4 TexUvCornerFills[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX]; // UVs for baked anti-aliased corners + ImVec4 TexUvCornerStrokes[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dee1a1ab3..52f408843 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1558,6 +1558,125 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th } } + +void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags) +{ + const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); + const ImVec2 uv_tr(tex_uvs.z, tex_uvs.y); + const ImVec2 uv_br(tex_uvs.z, tex_uvs.w); + const ImVec2 uv_bl(tex_uvs.x, tex_uvs.w); + + const int idx_allocated = 8 * 2 * 3; + const int vtx_allocated = 8 * 4; + PrimReserve(idx_allocated, vtx_allocated); + ImDrawVert* start_vtx_ptr = _VtxWritePtr; + ImDrawIdx* start_idx_ptr = _IdxWritePtr; + + if (flags & ImDrawFlags_RoundCornersTopLeft) + { + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + PrimWriteVtx(ImVec2(p_min.x, p_min.y), uv_tl, col); + PrimWriteVtx(ImVec2(p_min.x + r, p_min.y), uv_tr, col); + PrimWriteVtx(ImVec2(p_min.x + r, p_min.y + r), uv_br, col); + PrimWriteVtx(ImVec2(p_min.x, p_min.y + r), uv_bl, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + + if (flags & ImDrawFlags_RoundCornersTopRight) + { + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + PrimWriteVtx(ImVec2(p_max.x - r, p_min.y), uv_tr, col); + PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv_tl, col); + PrimWriteVtx(ImVec2(p_max.x, p_min.y + r), uv_bl, col); + PrimWriteVtx(ImVec2(p_max.x - r, p_min.y + r), uv_br, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + + if (flags & ImDrawFlags_RoundCornersBottomRight) + { + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + PrimWriteVtx(ImVec2(p_max.x - r, p_max.y - r), uv_br, col); + PrimWriteVtx(ImVec2(p_max.x, p_max.y - r), uv_bl, col); + PrimWriteVtx(ImVec2(p_max.x, p_max.y), uv_tl, col); + PrimWriteVtx(ImVec2(p_max.x - r, p_max.y), uv_tr, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + + if (flags & ImDrawFlags_RoundCornersBottomLeft) + { + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + PrimWriteVtx(ImVec2(p_min.x, p_max.y - r), uv_bl, col); + PrimWriteVtx(ImVec2(p_min.x + r, p_max.y - r), uv_br, col); + PrimWriteVtx(ImVec2(p_min.x + r, p_max.y), uv_tr, col); + PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv_tl, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + + const float r_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? r : 0; + const float r_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? r : 0; + const float r_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? r : 0; + const float r_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? r : 0; + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; + + { + // Top + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + const float left = p_min.x + r_tl; + const float right = p_max.x - r_tr; + PrimWriteVtx(ImVec2(left, p_min.y), opaque_uv, col); + PrimWriteVtx(ImVec2(right, p_min.y), opaque_uv, col); + PrimWriteVtx(ImVec2(right, p_min.y + t), opaque_uv, col); + PrimWriteVtx(ImVec2(left, p_min.y + t), opaque_uv, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + { + // Left + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + const float top = p_min.y + ImMax(r_tl, t); + const float bottom = p_max.y - ImMax(r_bl, t); + PrimWriteVtx(ImVec2(p_min.x, top), opaque_uv, col); + PrimWriteVtx(ImVec2(p_min.x + t, top), opaque_uv, col); + PrimWriteVtx(ImVec2(p_min.x + t, bottom), opaque_uv, col); + PrimWriteVtx(ImVec2(p_min.x, bottom), opaque_uv, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + { + // Right + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + const float top = p_min.y + ImMax(r_tr, t); + const float bottom = p_max.y - ImMax(r_br, t); + PrimWriteVtx(ImVec2(p_max.x - t, top), opaque_uv, col); + PrimWriteVtx(ImVec2(p_max.x, top), opaque_uv, col); + PrimWriteVtx(ImVec2(p_max.x, bottom), opaque_uv, col); + PrimWriteVtx(ImVec2(p_max.x - t, bottom), opaque_uv, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + { + // Bottom + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + const float left = p_min.x + r_bl; + const float right = p_max.x - r_br; + PrimWriteVtx(ImVec2(left, p_max.y - t), opaque_uv, col); + PrimWriteVtx(ImVec2(right, p_max.y - t), opaque_uv, col); + PrimWriteVtx(ImVec2(right, p_max.y), opaque_uv, col); + PrimWriteVtx(ImVec2(left, p_max.y), opaque_uv, col); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); + PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + } + + const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); + const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); + if (idx_used < idx_allocated || vtx_used < vtx_allocated) + PrimUnreserve(idx_allocated - idx_used, vtx_allocated - vtx_used); +} + // p_min = upper-left, p_max = lower-right // Note we don't render 1 pixels sized rectangles properly. void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) @@ -1586,8 +1705,49 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } + ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside) && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated(rounding) && ImIsTruncated(thickness)) + { + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; + + rounding = ImMin(rounding, ImFabs(p_max.x - p_min.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(p_max.y - p_min.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + + int s_rounding = (int)rounding; + int s_thickness = (int)thickness; + + ImVec2 s_min = p_min; + ImVec2 s_max = p_max; + if (stroke_pos == ImDrawFlags_StrokeOutside) + { + s_min -= ImVec2(thickness, thickness); + s_max += ImVec2(thickness, thickness); + s_rounding += s_thickness; + } + + if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + const float t = (float)s_thickness; + PrimReserve(6*4, 4*4); + PrimRect(ImVec2(p_min.x, p_min.y), ImVec2(p_max.x, p_min.y + t), col); + PrimRect(ImVec2(p_min.x, p_min.y + t), ImVec2(p_min.x + t, p_max.y - t), col); + PrimRect(ImVec2(p_max.x - t, p_min.y + t), ImVec2(p_max.x, p_max.y - t), col); + PrimRect(ImVec2(p_min.x, p_max.y - t), ImVec2(p_max.x, p_max.y), col); + return; + } + if (s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + { + const int size = ImMax(s_rounding, s_thickness); + const int idx = (s_thickness - 1) * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + s_rounding - 1; + IM_ASSERT(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); + const ImVec4 tex_uvs = _Data->TexUvCornerStrokes[idx]; + _AddRectBaked(s_min, s_max, col, (float)size, (float)thickness, tex_uvs, flags); + return; + } + } + const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); - const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); if (stroke_pos == ImDrawFlags_StrokeInside) PathRect(p_min + offset, p_max - offset, rounding - thickness * 0.5f, flags); else if (stroke_pos == ImDrawFlags_StrokeCenter) @@ -1604,7 +1764,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathStroke(col, thickness, ImDrawFlags_Closed); } -void ImDrawList::_AddMirrored9Slice(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags) +void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags) { // 9-slice with corner mirroring const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); @@ -1675,7 +1835,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c else if (s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { ImVec4 tex_uvs = _Data->TexUvCornerFills[s_rounding - 1]; - _AddMirrored9Slice(p_min, p_max, col, ImMax(2.0f, (float)s_rounding), tex_uvs, flags); + _AddRectFilledBaked(p_min, p_max, col, ImMax(2.0f, (float)s_rounding), tex_uvs, flags); } else { @@ -3834,6 +3994,17 @@ static ImU8 SampleCorner(float x, float y, float cx, float cy, float r) return (ImU8)(ImClamp(1.0f - (d - r + aa_width * 0.5f) / aa_width, 0.0f, 1.0f) * 255.0f); } +static ImU8 SampleCornerStroke(float x, float y, float cx, float cy, float outer_r, float inner_r) +{ + const float dx = ImMin(x, cx) - cx; + const float dy = ImMin(y, cy) - cy; + const float d = ImSqrt(dx*dx + dy*dy); + const float aa_width = 1.0f; + const float outer = 1.0f - (d - outer_r + aa_width * 0.5f) / aa_width; + const float inner = (d - inner_r + aa_width * 0.5f) / aa_width; + return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.f); +} + static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) { // Pack and store identifier so we can refresh UV coordinates on texture resize. @@ -3845,10 +4016,30 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) if (add_and_draw) { ImVec2i pack_size(0, 0); + // Filled corners + int row_width = 0; + int row_height = 0; for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) { - pack_size.x += ImMax(2, i+1) + 2; - pack_size.y = ImMax(pack_size.y, (i+1) + 2); + const int size = ImMax(2, i+1) + 2; + row_width += size; + row_height = ImMax(row_height, size); + } + pack_size.x = ImMax(pack_size.x, row_width); + pack_size.y += row_height; + // Rounded corners + for (int t = 0; t < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; t++) + { + row_width = 0; + row_height = 0; + for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) + { + const int size = ImMax(2, ImMax(i+1, t+1)) + 2; + row_width += size; + row_height = ImMax(row_height, size); + } + pack_size.x = ImMax(pack_size.x, row_width); + pack_size.y += row_height; } builder->PackIdCornersTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); IM_ASSERT(builder->PackIdCornersTexData != ImFontAtlasRectId_Invalid); @@ -3856,16 +4047,20 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) int x = r.x; int y = r.y; - for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) // +1 because of the zero-width row + int row_height = 0; + + // Filled + for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) { - const int s = ImMax(2, n+1); // We need at least 2px so that stretching has solid color. + const int rounding = n+1; + const int s = ImMax(2, rounding); // We need at least 2px so that stretching has solid color. const int w = s + 2; const int h = s + 2; // Corner circle const float cx = 1.0f + (float)(n+1); const float cy = 1.0f + (float)(n+1); - const float rad = (float)(n+1); + const float rad = (float)rounding; IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds before we start writing pixels // Write each slice @@ -3898,6 +4093,64 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) atlas->TexUvCornerFills[n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); x += w; + row_height = ImMax(row_height, h); + } + y += row_height; + + // Stroked + for (int t = 0; t < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; t++) + { + x = r.x; + row_height = 0; + for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) + { + const int rounding = n+1; + const int thickness = t+1; + const int s = ImMax(rounding, thickness); + const int w = s + 2; + const int h = s + 2; + + // Corner circle + const float cx = 1.0f + (float)(n + 1); + const float cy = 1.0f + (float)(n + 1); + const float outer_rad = (float)rounding; + const float inner_rad = (float)(rounding - thickness); + + IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds before we start writing pixels + + // Write each slice + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) + { + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(x, y); + const int pitch = tex->Width; + for (int ly = 0; ly < h; ly++) + { + for (int lx = 0; lx < h; lx++) + write_ptr[lx] = SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, outer_rad, inner_rad); + write_ptr += pitch; + } + } + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(x, y); + const int pitch = tex->Width; + for (int ly = 0; ly < h; ly++) + { + for (int lx = 0; lx < h; lx++) + write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, outer_rad, inner_rad)); + write_ptr += pitch; + } + } + + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; + atlas->TexUvCornerStrokes[t*IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + + x += w; + row_height = ImMax(row_height, h); + } + y += row_height; } } @@ -4337,6 +4590,7 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; shared_data->TexUvLines = atlas->TexUvLines; shared_data->TexUvCornerFills = atlas->TexUvCornerFills; + shared_data->TexUvCornerStrokes = atlas->TexUvCornerStrokes; } } diff --git a/imgui_internal.h b/imgui_internal.h index e6a9d0321..d351411cc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -922,6 +922,7 @@ struct IMGUI_API ImDrawListSharedData ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) const ImVec4* TexUvCornerFills; // UV of rounded corner (== FontAtlas->TexUvCornerFills) + const ImVec4* TexUvCornerStrokes; ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current font (used for simplified AddText overload) float FontSize; // Current font size (used for simplified AddText overload) From 237a498c2d6972b1be5e1a36b2f3a7a1cd6fdeac Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 28 Apr 2026 09:32:09 +0300 Subject: [PATCH 048/245] DrawList: Textured Round Corners: Added flags to disable textured rounded corners (#1962) - added ImFontAtlasFlags_NoBakedRoundCorners which controls if rounded corners should be baked to texture - added ImDrawListFlags_RoundCornersUseTex which controls if we should try to use textured roudned corners - fixed how _FringeScaleIsInteger is calculated (we want to detect integer pixel scale) - fixed how _FringeScale is used with textured rounded corners --- imgui.cpp | 2 ++ imgui.h | 4 +++- imgui_draw.cpp | 46 +++++++++++++++++++++++++++++----------------- 3 files changed, 34 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 549973af2..b6cef8d0c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5624,6 +5624,8 @@ static void SetupDrawListSharedData() g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines)) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; + if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_RoundCornersUseTex; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) diff --git a/imgui.h b/imgui.h index 87ddae804..88bbbf9b9 100644 --- a/imgui.h +++ b/imgui.h @@ -3348,6 +3348,7 @@ enum ImDrawListFlags_ ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. ImDrawListFlags_TextNoPixelSnap = 1 << 4, // Disable automatically snapping AddText() calls to pixel boundaries. + ImDrawListFlags_RoundCornersUseTex = 1 << 5, // Enable using textures instead of strokes to draw rounded corners/circles where possible. }; // Draw command list @@ -3380,7 +3381,7 @@ struct ImDrawList ImVector _CallbacksDataBuf; // [Internal] float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content. float _InvFringeScale; // [internal] 1.0 / _FringeScale // FIXME: Consider renaming to _PixelDensity. - bool _FringeScaleIsInteger; // [Internal] true if _FringeScale is a whole number, used to select fast path for rendering + bool _FringeScaleIsInteger; // [Internal] true if 1/_FringeScale is a whole number, used to select fast path for rendering const char* _OwnerName; // Pointer to owner window's name for debugging // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData(). @@ -3744,6 +3745,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). + ImFontAtlasFlags_NoBakedRoundCorners= 1 << 3, // Don't build round corners into the atlas. }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 52f408843..e194075ef 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -725,7 +725,7 @@ void ImDrawList::_SetPixelDensity(float pixel_density) IM_ASSERT(pixel_density > 0.0f); _FringeScale = 1.0f / pixel_density; _InvFringeScale = pixel_density; - _FringeScaleIsInteger = ImIsTruncated(_FringeScale); + _FringeScaleIsInteger = ImIsTruncated(_InvFringeScale); } // Reserve space for a number of vertices and indices. @@ -1519,7 +1519,8 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th y -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeOutside) y -= thickness; - if (ImIsTruncated4(min_x, max_x, y, thickness)) + + if (_FringeScaleIsInteger && ImIsTruncated4(min_x, max_x, y, thickness)) { PrimReserve(6, 4); PrimRect(ImVec2(min_x, y), ImVec2(max_x, y + thickness), col); @@ -1547,10 +1548,11 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th x += thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeOutside) x -= thickness; - if (ImIsTruncated4(x, min_y, max_y, thickness)) + + if (_FringeScaleIsInteger && ImIsTruncated4(x, min_y, max_y, thickness)) { PrimReserve(6, 4); - PrimRect(ImTrunc(ImVec2(x, min_y)), ImTrunc(ImVec2(x + thickness, max_y)), col); + PrimRect(ImVec2(x, min_y), ImVec2(x + thickness, max_y), col); } else { @@ -1705,8 +1707,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } + const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); - if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside) && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated(rounding) && ImIsTruncated(thickness)) + if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside) && is_truncated) { if ((flags & ImDrawFlags_RoundCornersMask_) == 0) flags |= ImDrawFlags_RoundCornersAll; @@ -1714,8 +1717,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl rounding = ImMin(rounding, ImFabs(p_max.x - p_min.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); rounding = ImMin(rounding, ImFabs(p_max.y - p_min.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - int s_rounding = (int)rounding; - int s_thickness = (int)thickness; + int s_rounding = (int)(rounding / _FringeScale); + int s_thickness = (int)(thickness / _FringeScale); ImVec2 s_min = p_min; ImVec2 s_max = p_max; @@ -1728,7 +1731,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { - const float t = (float)s_thickness; + const float t = (float)s_thickness * _FringeScale; PrimReserve(6*4, 4*4); PrimRect(ImVec2(p_min.x, p_min.y), ImVec2(p_max.x, p_min.y + t), col); PrimRect(ImVec2(p_min.x, p_min.y + t), ImVec2(p_min.x + t, p_max.y - t), col); @@ -1736,13 +1739,14 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PrimRect(ImVec2(p_min.x, p_max.y - t), ImVec2(p_max.x, p_max.y), col); return; } - if (s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { - const int size = ImMax(s_rounding, s_thickness); + IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); + const int size = ImMax(s_rounding, s_thickness); // This is matching the baking calculations. const int idx = (s_thickness - 1) * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + s_rounding - 1; - IM_ASSERT(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); + IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); const ImVec4 tex_uvs = _Data->TexUvCornerStrokes[idx]; - _AddRectBaked(s_min, s_max, col, (float)size, (float)thickness, tex_uvs, flags); + _AddRectBaked(s_min, s_max, col, (float)size * _FringeScale, (float)thickness, tex_uvs, flags); return; } } @@ -1826,16 +1830,21 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c rounding = ImMin(rounding, ImFabs(p_max.x - p_min.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); rounding = ImMin(rounding, ImFabs(p_max.y - p_min.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - const int s_rounding = (int)rounding; + + const int s_rounding = (int)(rounding / _FringeScale); if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { PrimReserve(6, 4); PrimRect(p_min, p_max, col); } - else if (s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + else if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { - ImVec4 tex_uvs = _Data->TexUvCornerFills[s_rounding - 1]; - _AddRectFilledBaked(p_min, p_max, col, ImMax(2.0f, (float)s_rounding), tex_uvs, flags); + IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); + const int size = ImMax(2, s_rounding); // This is matching the baking calculations. + const int idx = s_rounding - 1; + IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); + ImVec4 tex_uvs = _Data->TexUvCornerFills[idx]; + _AddRectFilledBaked(p_min, p_max, col, (float)size * _FringeScale, tex_uvs, flags); } else { @@ -4002,11 +4011,14 @@ static ImU8 SampleCornerStroke(float x, float y, float cx, float cy, float outer const float aa_width = 1.0f; const float outer = 1.0f - (d - outer_r + aa_width * 0.5f) / aa_width; const float inner = (d - inner_r + aa_width * 0.5f) / aa_width; - return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.f); + return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.0f); } static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) { + if (atlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners) + return; + // Pack and store identifier so we can refresh UV coordinates on texture resize. ImTextureData* tex = atlas->TexData; ImFontAtlasBuilder* builder = atlas->Builder; From b9707d72abb0ba9c263dd46da61a4a5df726aea5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 5 May 2026 17:40:15 +0200 Subject: [PATCH 049/245] DrawList: Textured Round Corners: use macros + rename locals. (#1962) Squashed: Rename macros to IM_APPEND_VTX(), IM_APPEND_TRI() --- imgui_draw.cpp | 168 +++++++++++++++++++++++++++---------------------- 1 file changed, 93 insertions(+), 75 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e194075ef..b4e1c5e65 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -819,6 +819,25 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c #define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) #define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0 +// We avoid using the 'do { } while (false)` idiom in those macros as they typically have overhead in debug builds. +#define IM_APPEND_VTX(PX, PY, UV, COL) \ + { \ + _VtxWritePtr->pos.x = PX; \ + _VtxWritePtr->pos.y = PY; \ + _VtxWritePtr->uv = UV; \ + _VtxWritePtr->col = COL; \ + _VtxWritePtr++; \ + _VtxCurrentIdx++; \ + } (void)0 + +#define IM_APPEND_TRI(a, b, c) \ + { \ + _IdxWritePtr[0] = (ImDrawIdx)(a); \ + _IdxWritePtr[1] = (ImDrawIdx)(b); \ + _IdxWritePtr[2] = (ImDrawIdx)(c); \ + _IdxWritePtr += 3; \ + } (void)0 + // TODO: Thickness anti-aliased lines cap are missing their AA fringe. // We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) @@ -1560,7 +1579,6 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th } } - void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags) { const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); @@ -1577,45 +1595,45 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if (flags & ImDrawFlags_RoundCornersTopLeft) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - PrimWriteVtx(ImVec2(p_min.x, p_min.y), uv_tl, col); - PrimWriteVtx(ImVec2(p_min.x + r, p_min.y), uv_tr, col); - PrimWriteVtx(ImVec2(p_min.x + r, p_min.y + r), uv_br, col); - PrimWriteVtx(ImVec2(p_min.x, p_min.y + r), uv_bl, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + IM_APPEND_VTX(p_min.x, p_min.y, uv_tl, col); + IM_APPEND_VTX(p_min.x + r, p_min.y, uv_tr, col); + IM_APPEND_VTX(p_min.x + r, p_min.y + r, uv_br, col); + IM_APPEND_VTX(p_min.x, p_min.y + r, uv_bl, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } if (flags & ImDrawFlags_RoundCornersTopRight) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - PrimWriteVtx(ImVec2(p_max.x - r, p_min.y), uv_tr, col); - PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv_tl, col); - PrimWriteVtx(ImVec2(p_max.x, p_min.y + r), uv_bl, col); - PrimWriteVtx(ImVec2(p_max.x - r, p_min.y + r), uv_br, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + IM_APPEND_VTX(p_max.x - r, p_min.y, uv_tr, col); + IM_APPEND_VTX(p_max.x, p_min.y, uv_tl, col); + IM_APPEND_VTX(p_max.x, p_min.y + r, uv_bl, col); + IM_APPEND_VTX(p_max.x - r, p_min.y + r, uv_br, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } if (flags & ImDrawFlags_RoundCornersBottomRight) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - PrimWriteVtx(ImVec2(p_max.x - r, p_max.y - r), uv_br, col); - PrimWriteVtx(ImVec2(p_max.x, p_max.y - r), uv_bl, col); - PrimWriteVtx(ImVec2(p_max.x, p_max.y), uv_tl, col); - PrimWriteVtx(ImVec2(p_max.x - r, p_max.y), uv_tr, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + IM_APPEND_VTX(p_max.x - r, p_max.y - r, uv_br, col); + IM_APPEND_VTX(p_max.x, p_max.y - r, uv_bl, col); + IM_APPEND_VTX(p_max.x, p_max.y, uv_tl, col); + IM_APPEND_VTX(p_max.x - r, p_max.y, uv_tr, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } if (flags & ImDrawFlags_RoundCornersBottomLeft) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - PrimWriteVtx(ImVec2(p_min.x, p_max.y - r), uv_bl, col); - PrimWriteVtx(ImVec2(p_min.x + r, p_max.y - r), uv_br, col); - PrimWriteVtx(ImVec2(p_min.x + r, p_max.y), uv_tr, col); - PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv_tl, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + IM_APPEND_VTX(p_min.x, p_max.y - r, uv_bl, col); + IM_APPEND_VTX(p_min.x + r, p_max.y - r, uv_br, col); + IM_APPEND_VTX(p_min.x + r, p_max.y, uv_tr, col); + IM_APPEND_VTX(p_min.x, p_max.y, uv_tl, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } const float r_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? r : 0; @@ -1627,50 +1645,50 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c { // Top ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float left = p_min.x + r_tl; - const float right = p_max.x - r_tr; - PrimWriteVtx(ImVec2(left, p_min.y), opaque_uv, col); - PrimWriteVtx(ImVec2(right, p_min.y), opaque_uv, col); - PrimWriteVtx(ImVec2(right, p_min.y + t), opaque_uv, col); - PrimWriteVtx(ImVec2(left, p_min.y + t), opaque_uv, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + const float x0 = p_min.x + r_tl; + const float x1 = p_max.x - r_tr; + IM_APPEND_VTX(x0, p_min.y, opaque_uv, col); + IM_APPEND_VTX(x1, p_min.y, opaque_uv, col); + IM_APPEND_VTX(x1, p_min.y + t, opaque_uv, col); + IM_APPEND_VTX(x0, p_min.y + t, opaque_uv, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } { // Left ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float top = p_min.y + ImMax(r_tl, t); - const float bottom = p_max.y - ImMax(r_bl, t); - PrimWriteVtx(ImVec2(p_min.x, top), opaque_uv, col); - PrimWriteVtx(ImVec2(p_min.x + t, top), opaque_uv, col); - PrimWriteVtx(ImVec2(p_min.x + t, bottom), opaque_uv, col); - PrimWriteVtx(ImVec2(p_min.x, bottom), opaque_uv, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + const float y0 = p_min.y + ImMax(r_tl, t); + const float y1 = p_max.y - ImMax(r_bl, t); + IM_APPEND_VTX(p_min.x, y0, opaque_uv, col); + IM_APPEND_VTX(p_min.x + t, y0, opaque_uv, col); + IM_APPEND_VTX(p_min.x + t, y1, opaque_uv, col); + IM_APPEND_VTX(p_min.x, y1, opaque_uv, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } { // Right ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float top = p_min.y + ImMax(r_tr, t); - const float bottom = p_max.y - ImMax(r_br, t); - PrimWriteVtx(ImVec2(p_max.x - t, top), opaque_uv, col); - PrimWriteVtx(ImVec2(p_max.x, top), opaque_uv, col); - PrimWriteVtx(ImVec2(p_max.x, bottom), opaque_uv, col); - PrimWriteVtx(ImVec2(p_max.x - t, bottom), opaque_uv, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + const float y0 = p_min.y + ImMax(r_tr, t); + const float y1 = p_max.y - ImMax(r_br, t); + IM_APPEND_VTX(p_max.x - t, y0, opaque_uv, col); + IM_APPEND_VTX(p_max.x, y0, opaque_uv, col); + IM_APPEND_VTX(p_max.x, y1, opaque_uv, col); + IM_APPEND_VTX(p_max.x - t, y1, opaque_uv, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } { // Bottom ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float left = p_min.x + r_bl; - const float right = p_max.x - r_br; - PrimWriteVtx(ImVec2(left, p_max.y - t), opaque_uv, col); - PrimWriteVtx(ImVec2(right, p_max.y - t), opaque_uv, col); - PrimWriteVtx(ImVec2(right, p_max.y), opaque_uv, col); - PrimWriteVtx(ImVec2(left, p_max.y), opaque_uv, col); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); PrimWriteIdx(idx+2); - PrimWriteIdx(idx+0); PrimWriteIdx(idx+2); PrimWriteIdx(idx+3); + const float x0 = p_min.x + r_bl; + const float x1 = p_max.x - r_br; + IM_APPEND_VTX(x0, p_max.y - t, opaque_uv, col); + IM_APPEND_VTX(x1, p_max.y - t, opaque_uv, col); + IM_APPEND_VTX(x1, p_max.y, opaque_uv, col); + IM_APPEND_VTX(x0, p_max.y, opaque_uv, col); + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); @@ -1785,32 +1803,32 @@ void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, I ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - PrimWriteVtx(ImVec2(p_min.x, p_min.y), uv_tl, col); - PrimWriteVtx(ImVec2(p_min.x + r_tl, p_min.y), uv_tr, col); - PrimWriteVtx(ImVec2(p_max.x - r_tr, p_min.y), uv_tr, col); - PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv_tl, col); + IM_APPEND_VTX(p_min.x, p_min.y, uv_tl, col); + IM_APPEND_VTX(p_min.x + r_tl, p_min.y, uv_tr, col); + IM_APPEND_VTX(p_max.x - r_tr, p_min.y, uv_tr, col); + IM_APPEND_VTX(p_max.x, p_min.y, uv_tl, col); - PrimWriteVtx(ImVec2(p_min.x, p_min.y + r_tl), uv_bl, col); - PrimWriteVtx(ImVec2(p_min.x + r_tl, p_min.y + r_tl), uv_br, col); - PrimWriteVtx(ImVec2(p_max.x - r_tr, p_min.y + r_tr), uv_br, col); - PrimWriteVtx(ImVec2(p_max.x, p_min.y + r_tr), uv_bl, col); + IM_APPEND_VTX(p_min.x, p_min.y + r_tl, uv_bl, col); + IM_APPEND_VTX(p_min.x + r_tl, p_min.y + r_tl, uv_br, col); + IM_APPEND_VTX(p_max.x - r_tr, p_min.y + r_tr, uv_br, col); + IM_APPEND_VTX(p_max.x, p_min.y + r_tr, uv_bl, col); - PrimWriteVtx(ImVec2(p_min.x, p_max.y - r_bl), uv_bl, col); - PrimWriteVtx(ImVec2(p_min.x + r_bl, p_max.y - r_bl), uv_br, col); - PrimWriteVtx(ImVec2(p_max.x - r_br, p_max.y - r_br), uv_br, col); - PrimWriteVtx(ImVec2(p_max.x, p_max.y - r_br), uv_bl, col); + IM_APPEND_VTX(p_min.x, p_max.y - r_bl, uv_bl, col); + IM_APPEND_VTX(p_min.x + r_bl, p_max.y - r_bl, uv_br, col); + IM_APPEND_VTX(p_max.x - r_br, p_max.y - r_br, uv_br, col); + IM_APPEND_VTX(p_max.x, p_max.y - r_br, uv_bl, col); - PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv_tl, col); - PrimWriteVtx(ImVec2(p_min.x + r_bl, p_max.y), uv_tr, col); - PrimWriteVtx(ImVec2(p_max.x - r_br, p_max.y ), uv_tr, col); - PrimWriteVtx(ImVec2(p_max.x, p_max.y), uv_tl, col); + IM_APPEND_VTX(p_min.x, p_max.y, uv_tl, col); + IM_APPEND_VTX(p_min.x + r_bl, p_max.y, uv_tr, col); + IM_APPEND_VTX(p_max.x - r_br, p_max.y, uv_tr, col); + IM_APPEND_VTX(p_max.x, p_max.y, uv_tl, col); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { - PrimWriteIdx(idx+4); PrimWriteIdx(idx+0); PrimWriteIdx(idx+1); - PrimWriteIdx(idx+4); PrimWriteIdx(idx+1); PrimWriteIdx(idx+5); + IM_APPEND_TRI(idx + 4, idx + 0, idx + 1); + IM_APPEND_TRI(idx + 4, idx + 1, idx + 5); idx++; } idx++; From 80096045d9cf0e0f23298d9e4441e3322b93911c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 5 May 2026 20:18:03 +0200 Subject: [PATCH 050/245] DrawList: AddRect: avoid altering rounding on StrokeOutside when initial value if 0 + comments --- imgui_draw.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b4e1c5e65..0ec80274c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1738,17 +1738,22 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl int s_rounding = (int)(rounding / _FringeScale); int s_thickness = (int)(thickness / _FringeScale); + // AddRectBaked() renders the stroke inside the rectangle, so we need to adjust the outside case + // This branch does not handle the center, since odd thickness strokes are not pixel aligned, even if the rectangle is. ImVec2 s_min = p_min; ImVec2 s_max = p_max; if (stroke_pos == ImDrawFlags_StrokeOutside) { s_min -= ImVec2(thickness, thickness); s_max += ImVec2(thickness, thickness); - s_rounding += s_thickness; + if (s_rounding != 0.0f) + s_rounding += s_thickness; } + // FIXME-WIP: Why isn't rounding offset in the _StrokeInside case? if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { + // FIXME-WIP: This could use half the number of vertices. const float t = (float)s_thickness * _FringeScale; PrimReserve(6*4, 4*4); PrimRect(ImVec2(p_min.x, p_min.y), ImVec2(p_max.x, p_min.y + t), col); From 9199934a7f6a3253f70e93ced52cc0b7803a2f6d Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 8 May 2026 13:07:25 +0300 Subject: [PATCH 051/245] DrawList: added ImDrawFlags_StrokeCenterPixelAligned - added ImDrawFlags_StrokeCenterPixelAligned which center aligns stroke so that outside of the stroke is pixel aligned - fixed AddRect() non-rounded pixel aligned case to use correnct min/max - fixed AddRect() default case to not adjust rounding for non-rounded rects - fixed lineV() centered offset - renamed ImDrawFlags_StrokeCenterPixelAligned to ImDrawFlags_StrokeCenterAligned. - reduced debug build indirections. --- imgui.h | 7 +++--- imgui_draw.cpp | 66 +++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 58 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index 88bbbf9b9..7e48ce43b 100644 --- a/imgui.h +++ b/imgui.h @@ -3331,9 +3331,10 @@ enum ImDrawFlags_ // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 0 << 16, // Draw stroke inside of the shape outline (Default) ImDrawFlags_StrokeCenter = 1 << 16, // Draw stroke at the center of the shape outline - ImDrawFlags_StrokeOutside = 2 << 16, // Draw stroke outside of the shape outline - ImDrawFlags_StrokeLegacy = 3 << 16, // Use legacy position - ImDrawFlags_StrokeMask_ = 0x03 << 16, + ImDrawFlags_StrokeCenterPixelAligned = 2 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. + ImDrawFlags_StrokeOutside = 3 << 16, // Draw stroke outside of the shape outline + ImDrawFlags_StrokeLegacy = 4 << 16, // Use legacy position + ImDrawFlags_StrokeMask_ = 0x07 << 16, ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0ec80274c..613010929 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1536,6 +1536,8 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); if (stroke_pos == ImDrawFlags_StrokeCenter) y -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + y -= IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; else if (stroke_pos == ImDrawFlags_StrokeOutside) y -= thickness; @@ -1564,7 +1566,9 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); if (stroke_pos == ImDrawFlags_StrokeCenter) - x += thickness * 0.5f; + x -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + x -= IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; else if (stroke_pos == ImDrawFlags_StrokeOutside) x -= thickness; @@ -1725,9 +1729,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); + const bool is_truncated = _FringeScaleIsInteger&& ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); - if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside) && is_truncated) + if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) { if ((flags & ImDrawFlags_RoundCornersMask_) == 0) flags |= ImDrawFlags_RoundCornersAll; @@ -1740,15 +1744,29 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl // AddRectBaked() renders the stroke inside the rectangle, so we need to adjust the outside case // This branch does not handle the center, since odd thickness strokes are not pixel aligned, even if the rectangle is. + // Pixel aligned center works, since the stroke is aligned to pixels. ImVec2 s_min = p_min; ImVec2 s_max = p_max; if (stroke_pos == ImDrawFlags_StrokeOutside) { - s_min -= ImVec2(thickness, thickness); - s_max += ImVec2(thickness, thickness); - if (s_rounding != 0.0f) + s_min.x -= thickness; + s_min.y -= thickness; + s_max.x += thickness; + s_max.y += thickness; + if (s_rounding != 0) s_rounding += s_thickness; } + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + { + const float offset = (s_thickness / 2) * _FringeScale; // Using integer div, since we want IM_TRUNC(thickness/2). + s_min.x -= offset; + s_min.y -= offset; + s_max.x += offset; + s_max.y += offset; + if (s_rounding != 0) + s_rounding += s_thickness / 2; + } + // FIXME-WIP: Why isn't rounding offset in the _StrokeInside case? if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) @@ -1756,10 +1774,10 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl // FIXME-WIP: This could use half the number of vertices. const float t = (float)s_thickness * _FringeScale; PrimReserve(6*4, 4*4); - PrimRect(ImVec2(p_min.x, p_min.y), ImVec2(p_max.x, p_min.y + t), col); - PrimRect(ImVec2(p_min.x, p_min.y + t), ImVec2(p_min.x + t, p_max.y - t), col); - PrimRect(ImVec2(p_max.x - t, p_min.y + t), ImVec2(p_max.x, p_max.y - t), col); - PrimRect(ImVec2(p_min.x, p_max.y - t), ImVec2(p_max.x, p_max.y), col); + PrimRect(ImVec2(s_min.x, s_min.y), ImVec2(s_max.x, s_min.y + t), col); + PrimRect(ImVec2(s_min.x, s_min.y + t), ImVec2(s_min.x + t, s_max.y - t), col); + PrimRect(ImVec2(s_max.x - t, s_min.y + t), ImVec2(s_max.x, s_max.y - t), col); + PrimRect(ImVec2(s_min.x, s_max.y - t), ImVec2(s_max.x, s_max.y), col); return; } if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) @@ -1776,11 +1794,26 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); if (stroke_pos == ImDrawFlags_StrokeInside) - PathRect(p_min + offset, p_max - offset, rounding - thickness * 0.5f, flags); + { + rounding -= (rounding != 0.f) ? thickness * 0.5f : 0.f; + PathRect(p_min + offset, p_max - offset, rounding, flags); + } else if (stroke_pos == ImDrawFlags_StrokeCenter) + { PathRect(p_min, p_max, rounding, flags); + } + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + { + // PathRect() centers the stroke, just calculate the fractional offset. + const float fract = (thickness * 0.5f) - IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + rounding += (rounding != 0.f) ? fract : 0.f; + PathRect(ImVec2(p_min.x + fract, p_min.y + fract), ImVec2(p_max.x - fract, p_max.y - fract), rounding, flags); + } else if (stroke_pos == ImDrawFlags_StrokeOutside) - PathRect(p_min - offset, p_max + offset, rounding + thickness * 0.5f, flags); + { + rounding += (rounding != 0.f) ? thickness * 0.5f : 0.f; + PathRect(p_min - offset, p_max + offset, rounding, flags); + } else if (stroke_pos == ImDrawFlags_StrokeLegacy) { if (Flags & ImDrawListFlags_AntiAliasedLines) @@ -1958,6 +1991,8 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); if (stroke_pos == ImDrawFlags_StrokeInside) radius -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + radius += IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale - thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeOutside) radius += thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeLegacy) @@ -2022,6 +2057,8 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); if (stroke_pos == ImDrawFlags_StrokeInside) radius -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + radius -= thickness * 0.5f - IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; else if (stroke_pos == ImDrawFlags_StrokeOutside) radius += thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeLegacy) @@ -2063,6 +2100,11 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); if (stroke_pos == ImDrawFlags_StrokeInside) r -= ImVec2(thickness * 0.5f, thickness * 0.5f); + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + { + const float fract = thickness * 0.5f - IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + r -= ImVec2(fract, fract); + } else if (stroke_pos == ImDrawFlags_StrokeOutside) r += ImVec2(thickness * 0.5f, thickness * 0.5f); } From 789f0d7140dd1b5eb3546582e96fbe107b34f683 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 8 May 2026 13:44:14 +0300 Subject: [PATCH 052/245] DrawList: optimize non-AA non-rounded case of AddRect() --- imgui_draw.cpp | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 613010929..687b5d5f9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1767,17 +1767,34 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl s_rounding += s_thickness / 2; } - // FIXME-WIP: Why isn't rounding offset in the _StrokeInside case? - if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { - // FIXME-WIP: This could use half the number of vertices. + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; const float t = (float)s_thickness * _FringeScale; - PrimReserve(6*4, 4*4); - PrimRect(ImVec2(s_min.x, s_min.y), ImVec2(s_max.x, s_min.y + t), col); - PrimRect(ImVec2(s_min.x, s_min.y + t), ImVec2(s_min.x + t, s_max.y - t), col); - PrimRect(ImVec2(s_max.x - t, s_min.y + t), ImVec2(s_max.x, s_max.y - t), col); - PrimRect(ImVec2(s_min.x, s_max.y - t), ImVec2(s_max.x, s_max.y), col); + + PrimReserve(8*3, 8); + const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(s_min.x, s_min.y, opaque_uv, col); + IM_APPEND_VTX(s_min.x + t, s_min.y + t, opaque_uv, col); + IM_APPEND_VTX(s_max.x, s_min.y, opaque_uv, col); + IM_APPEND_VTX(s_max.x - t, s_min.y + t, opaque_uv, col); + IM_APPEND_VTX(s_max.x, s_max.y, opaque_uv, col); + IM_APPEND_VTX(s_max.x - t, s_max.y - t, opaque_uv, col); + IM_APPEND_VTX(s_min.x, s_max.y, opaque_uv, col); + IM_APPEND_VTX(s_min.x + t, s_max.y - t, opaque_uv, col); + + IM_APPEND_TRI(idx + 0, idx + 3, idx + 1); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); + + IM_APPEND_TRI(idx + 2, idx + 5, idx + 3); + IM_APPEND_TRI(idx + 2, idx + 4, idx + 5); + + IM_APPEND_TRI(idx + 4, idx + 7, idx + 5); + IM_APPEND_TRI(idx + 4, idx + 6, idx + 7); + + IM_APPEND_TRI(idx + 6, idx + 1, idx + 7); + IM_APPEND_TRI(idx + 6, idx + 0, idx + 1); + return; } if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) From d6fee823b4166dc61bad32393c992438425df462 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 4 May 2026 15:55:46 +0200 Subject: [PATCH 053/245] Demo: Custom Rendering: expose Stroke Position. Demo: Custom Rendering: amend tests (to include legacy AddLine() for vertical/horizontal lines to compare. --- imgui_demo.cpp | 46 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0b16dab3c..422da3c0c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10406,6 +10406,15 @@ static void ShowExampleAppCustomRendering(bool* p_open) curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); ImGui::ColorEdit4("Color", &colf.x); + static ImDrawFlags flags = 0; + ImGui::AlignTextToFramePadding(); + ImGui::Text("Stroke:"); + ImGui::SameLine(); ImGui::RadioButton("Inside", &flags, ImDrawFlags_StrokeInside); + ImGui::SameLine(); ImGui::RadioButton("Center", &flags, ImDrawFlags_StrokeCenter); + ImGui::SameLine(); ImGui::RadioButton("CenterPixelAligned", &flags, ImDrawFlags_StrokeCenterPixelAligned); + ImGui::SameLine(); ImGui::RadioButton("Outside", &flags, ImDrawFlags_StrokeOutside); + ImGui::SameLine(); ImGui::RadioButton("Legacy", &flags, ImDrawFlags_StrokeLegacy); + const ImVec2 p = ImGui::GetCursorScreenPos(); const ImU32 col = ImColor(colf); const float spacing = 10.0f; @@ -10422,23 +10431,27 @@ static void ShowExampleAppCustomRendering(bool* p_open) { // First line uses a thickness of 1.0f, second line uses the configurable thickness float th = (n == 0) ? 1.0f : thickness; - draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle - draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th); x += sz + spacing; // Ellipse - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, th); x += sz + spacing; // Square - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x += sz + spacing; // Square with all rounded corners - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle + draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th, flags); x += sz + spacing; // N-gon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th, flags); x += sz + spacing; // Circle + draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th, flags); x += sz + spacing; // Ellipse + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, th, flags); x += sz + spacing; // Square + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, flags); x += sz + spacing; // Square with all rounded corners + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, flags | corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th/*, flags*/);x += sz + spacing; // Triangle //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle - PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, th, ImDrawFlags_Closed); x += sz + spacing; // Concave Shape + PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); x += sz + spacing; // Concave Shape //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); - draw_list->AddLineH(x, x + sz, y, col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) - draw_list->AddLineV(x, y, y + sz, col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line + draw_list->AddLineH(x, x + sz, y, col, th, flags); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLineV(x, y, y + sz, col, th, flags); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) + + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th, flags); x += sz + spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th, flags); x += spacing; + + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th, flags); x += sz + spacing; // Diagonal line // Path draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f, 3.141592f * -0.5f); - draw_list->PathStroke(col, th); + draw_list->PathStroke(col, th, flags); x += sz + spacing; // Quadratic Bezier Curve (3 control points) @@ -10463,8 +10476,13 @@ static void ShowExampleAppCustomRendering(bool* p_open) //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing; // Vertical line (faster than AddLine, but only handle integer thickness) + x += sz + spacing; + x += spacing; + draw_list->AddRectFilled(ImVec2(x + 0, y), ImVec2(x + 0 + 1, y + 1), col); // Pixels (faster than AddLine) + draw_list->AddRectFilled(ImVec2(x + 2, y), ImVec2(x + 2 + 2, y + 2), col); + draw_list->AddRectFilled(ImVec2(x + 5, y), ImVec2(x + 5 + 3, y + 3), col); + x += spacing + sz; // Path draw_list->PathArcTo(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, 3.141592f * -0.5f, 3.141592f); From 2361f61526ac22e6bb5e372d08d2a72eaf78d9cc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 May 2026 18:42:23 +0200 Subject: [PATCH 054/245] DrawList: fixed is_truncated checks in AddRect() and AddRectFilled(). --- imgui_draw.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 687b5d5f9..5f9d2f017 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1729,7 +1729,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - const bool is_truncated = _FringeScaleIsInteger&& ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); + const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) { @@ -1812,7 +1812,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); if (stroke_pos == ImDrawFlags_StrokeInside) { - rounding -= (rounding != 0.f) ? thickness * 0.5f : 0.f; + rounding -= (rounding != 0.0f) ? thickness * 0.5f : 0.0f; PathRect(p_min + offset, p_max - offset, rounding, flags); } else if (stroke_pos == ImDrawFlags_StrokeCenter) @@ -1823,12 +1823,12 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl { // PathRect() centers the stroke, just calculate the fractional offset. const float fract = (thickness * 0.5f) - IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; - rounding += (rounding != 0.f) ? fract : 0.f; + rounding += (rounding != 0.0f) ? fract : 0.0f; PathRect(ImVec2(p_min.x + fract, p_min.y + fract), ImVec2(p_max.x - fract, p_max.y - fract), rounding, flags); } else if (stroke_pos == ImDrawFlags_StrokeOutside) { - rounding += (rounding != 0.f) ? thickness * 0.5f : 0.f; + rounding += (rounding != 0.0f) ? thickness * 0.5f : 0.0f; PathRect(p_min - offset, p_max + offset, rounding, flags); } else if (stroke_pos == ImDrawFlags_StrokeLegacy) @@ -1895,7 +1895,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if ((col & IM_COL32_A_MASK) == 0) return; - if (ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_min.y) && ImIsTruncated(rounding)) + if (ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated(rounding)) { if ((flags & ImDrawFlags_RoundCornersMask_) == 0) flags |= ImDrawFlags_RoundCornersAll; From 5a5a16da4d00d97df7063b3dfab882d61cc4ea52 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 19 May 2026 17:40:16 +0200 Subject: [PATCH 055/245] DrawList: added _GetStrokePos() helper indirection, made flags=0 select default at runtime. --- imgui.h | 11 ++++++----- imgui_demo.cpp | 3 ++- imgui_draw.cpp | 25 ++++++++++++++++++------- imgui_internal.h | 1 + 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index 7e48ce43b..f947ee886 100644 --- a/imgui.h +++ b/imgui.h @@ -3329,11 +3329,11 @@ enum ImDrawFlags_ //ImDrawFlags_Closed = 1, // Prior to 1.92.8 (May 2026), ImDrawFlags_Closed was guaranteed to be == 1<<0 == 1 for legacy compatibility reason. Hardcoded use of 1 or true should be replaced. // Stroke position relative to the shape outline - ImDrawFlags_StrokeInside = 0 << 16, // Draw stroke inside of the shape outline (Default) - ImDrawFlags_StrokeCenter = 1 << 16, // Draw stroke at the center of the shape outline - ImDrawFlags_StrokeCenterPixelAligned = 2 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. - ImDrawFlags_StrokeOutside = 3 << 16, // Draw stroke outside of the shape outline - ImDrawFlags_StrokeLegacy = 4 << 16, // Use legacy position + ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (Default) + ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline + ImDrawFlags_StrokeCenterPixelAligned = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. + ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline + ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy position ImDrawFlags_StrokeMask_ = 0x07 << 16, ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, @@ -3524,6 +3524,7 @@ struct ImDrawList IMGUI_API void _OnChangedTexture(); IMGUI_API void _OnChangedVtxOffset(); IMGUI_API void _SetTexture(ImTextureRef tex_ref); + IMGUI_API ImDrawFlags _GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos); IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 422da3c0c..615201f01 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10406,9 +10406,10 @@ static void ShowExampleAppCustomRendering(bool* p_open) curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); ImGui::ColorEdit4("Color", &colf.x); - static ImDrawFlags flags = 0; + static ImDrawFlags flags = ImDrawFlags_None; ImGui::AlignTextToFramePadding(); ImGui::Text("Stroke:"); + ImGui::SameLine(); ImGui::RadioButton("Default", &flags, ImDrawFlags_None); ImGui::SameLine(); ImGui::RadioButton("Inside", &flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); ImGui::RadioButton("Center", &flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); ImGui::RadioButton("CenterPixelAligned", &flags, ImDrawFlags_StrokeCenterPixelAligned); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5f9d2f017..2bbdb8785 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1506,11 +1506,22 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr extern bool g_LEGACY_STROKES; +// We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. +// The earlier should use verbatim legacy code but will be removed before release once we confirm that both matches. +ImDrawFlags ImDrawList::_GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos) +{ + if (flags & ImDrawFlags_StrokeMask_) + return (flags & ImDrawFlags_StrokeMask_); + return _Data->OverrideStrokePos ? _Data->OverrideStrokePos : default_stroke_pos; +} + void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; - if (g_LEGACY_STROKES || (flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy) + + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); // WIP: only Legacy is used. + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; AddPolyline(points, 2, col, thickness); @@ -1533,7 +1544,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th return; } - ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeCenter) y -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -1564,7 +1575,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th return; } - ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeCenter) x -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -1730,7 +1741,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl } const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); - ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) { if ((flags & ImDrawFlags_RoundCornersMask_) == 0) @@ -2005,7 +2016,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu } else { - const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeInside) radius -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -2071,7 +2082,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ } else { - const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeInside) radius -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -2114,7 +2125,7 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co else { r = radius; - ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeInside) r -= ImVec2(thickness * 0.5f, thickness * 0.5f); else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) diff --git a/imgui_internal.h b/imgui_internal.h index d351411cc..9db27ab74 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -927,6 +927,7 @@ struct IMGUI_API ImDrawListSharedData ImFont* Font; // Current font (used for simplified AddText overload) float FontSize; // Current font size (used for simplified AddText overload) float FontScale; // Current font scale (== FontSize / Font->FontSize) + ImDrawFlags OverrideStrokePos; // Override default StrokePos when not specified by an individual primitive. == 0 or ImDrawFlags_StrokeLegacy only. float CurveTessellationMaxError; // Tessellation tolerance when using PathBezierCurveTo() float CircleTessellationMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) From 442834a428a9df0ff3ce9f7d93e8684327e7e2cd Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 19 May 2026 23:13:33 +0300 Subject: [PATCH 056/245] DrawList: changed CenterPixelAligned growth to be smoother, added stroke pos to AddLine() - changed vertical AddLine() to be consistent with AddLineV() - changed CenterPixelAligned growth to be smoother - added (temporary) specialized stroke pos support for AddLine() --- imgui_demo.cpp | 2 +- imgui_draw.cpp | 49 ++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 615201f01..a2caa877a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10446,7 +10446,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddLineV(x, y, y + sz, col, th, flags); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th, flags); x += sz + spacing; - draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th, flags); x += spacing; + draw_list->AddLine(ImVec2(x, y + sz), ImVec2(x, y), col, th, flags); x += spacing; draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th, flags); x += sz + spacing; // Diagonal line diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2bbdb8785..415f584bb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1504,6 +1504,19 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } } +static float CalculateCenterPixelAlignedOffset(float thickness, float _FringeScale) +{ + // Old jumpy one. + // return IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + + // Calculate outside offset for stroke position CenterPixelAligned + // so that one side the of the line is always at pixel boundary. + // On integer thickness both sides of the line are on pixel boundary. + const float screen_thickness = thickness / _FringeScale; + const int s_thickness = IM_TRUNC(screen_thickness); + return ((s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; +} + extern bool g_LEGACY_STROKES; // We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. @@ -1528,8 +1541,26 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th return; } - const ImVec2 points[2] = { p1, p2 }; - AddPolyline(points, 2, col, thickness); + ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImVec2 off(0, 0); + if (stroke_pos != ImDrawFlags_StrokeCenter) + { + // FIXME: this should be removed when the generic PathStroke() stroke pos is merged. + float nx = -(p1.y - p2.y); + float ny = p1.x - p2.x; + IM_NORMALIZE2F_OVER_ZERO(nx, ny); + float offset = 0.0f; + if (stroke_pos == ImDrawFlags_StrokeInside) + offset = -thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + offset = -(thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale)); + else if (stroke_pos == ImDrawFlags_StrokeOutside) + offset = thickness * 0.5f; + off.x = nx * offset; + off.y = ny * offset; + } + const ImVec2 points[2] = { p1 + off, p2 + off }; + AddPolyline(points, 2, col, thickness, flags); } void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness, ImDrawFlags flags) @@ -1548,7 +1579,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if (stroke_pos == ImDrawFlags_StrokeCenter) y -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - y -= IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + y -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) y -= thickness; @@ -1570,7 +1601,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if (g_LEGACY_STROKES) { - const ImVec2 points[2] = { ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f) }; // Same as AddLine() above. + const ImVec2 points[2] = { ImVec2(x + 0.5f, max_y + 0.5f), ImVec2(x + 0.5f, min_y + 0.5f) }; // Same as AddLine() above. AddPolyline(points, 2, col, thickness); return; } @@ -1579,7 +1610,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if (stroke_pos == ImDrawFlags_StrokeCenter) x -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - x -= IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + x -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) x -= thickness; @@ -1833,7 +1864,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) { // PathRect() centers the stroke, just calculate the fractional offset. - const float fract = (thickness * 0.5f) - IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + const float fract = (thickness * 0.5f) - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); rounding += (rounding != 0.0f) ? fract : 0.0f; PathRect(ImVec2(p_min.x + fract, p_min.y + fract), ImVec2(p_max.x - fract, p_max.y - fract), rounding, flags); } @@ -2020,7 +2051,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu if (stroke_pos == ImDrawFlags_StrokeInside) radius -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - radius += IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale - thickness * 0.5f; + radius -= thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) radius += thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeLegacy) @@ -2086,7 +2117,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ if (stroke_pos == ImDrawFlags_StrokeInside) radius -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - radius -= thickness * 0.5f - IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + radius -= thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) radius += thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeLegacy) @@ -2130,7 +2161,7 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co r -= ImVec2(thickness * 0.5f, thickness * 0.5f); else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) { - const float fract = thickness * 0.5f - IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + const float fract = thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); r -= ImVec2(fract, fract); } else if (stroke_pos == ImDrawFlags_StrokeOutside) From 60a934afd903493de8669e241bf56347c7e8ecd9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 20 May 2026 14:22:36 +0200 Subject: [PATCH 057/245] DrawList: fixed build/warnings + added pretty theorical support for _StrokeLegacy in AddLineV/AddLineH (Squash) Various zealous warning fixes. --- imgui_draw.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 415f584bb..b0abc0585 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1513,8 +1513,8 @@ static float CalculateCenterPixelAlignedOffset(float thickness, float _FringeSca // so that one side the of the line is always at pixel boundary. // On integer thickness both sides of the line are on pixel boundary. const float screen_thickness = thickness / _FringeScale; - const int s_thickness = IM_TRUNC(screen_thickness); - return ((s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; + const int s_thickness = (int)screen_thickness; + return ((float)(s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; } extern bool g_LEGACY_STROKES; @@ -1541,7 +1541,6 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th return; } - ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); ImVec2 off(0, 0); if (stroke_pos != ImDrawFlags_StrokeCenter) { @@ -1568,14 +1567,14 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if ((col & IM_COL32_A_MASK) == 0) return; - if (g_LEGACY_STROKES) + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. AddPolyline(points, 2, col, thickness); return; } - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeCenter) y -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -1599,14 +1598,14 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if ((col & IM_COL32_A_MASK) == 0) return; - if (g_LEGACY_STROKES) + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(x + 0.5f, max_y + 0.5f), ImVec2(x + 0.5f, min_y + 0.5f) }; // Same as AddLine() above. AddPolyline(points, 2, col, thickness); return; } - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeCenter) x -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -1800,7 +1799,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl } else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) { - const float offset = (s_thickness / 2) * _FringeScale; // Using integer div, since we want IM_TRUNC(thickness/2). + const float offset = (float)(s_thickness / 2) * _FringeScale; // Using integer div, since we want IM_TRUNC(thickness/2). s_min.x -= offset; s_min.y -= offset; s_max.x += offset; @@ -1975,6 +1974,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c } // p_min = upper-left, p_max = lower-right +// Note: this does not support anti-aliasing when provided non-integer vertices. void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) { if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) From c98d220e6ff70c818dcf45da63e21073349c5784 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 21 Apr 2026 10:46:18 +0300 Subject: [PATCH 058/245] DrawList: added improved polyline rendering. (#2183, #7972) - added 2 variants of polyline rendering - one handles integer-sized thickness using one strip of triangles along the line - second handles any thickness using 2 strips of triangles long the line --- imgui.h | 3 + imgui_demo.cpp | 2 +- imgui_draw.cpp | 724 ++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 726 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index f947ee886..c52455b3e 100644 --- a/imgui.h +++ b/imgui.h @@ -3430,6 +3430,7 @@ struct ImDrawList // - Only simple polygons are supported by filling functions (no self-intersections, no holes). // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); + IMGUI_API void AddPolylineLegacy(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); @@ -3530,6 +3531,8 @@ struct ImDrawList IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); + IMGUI_API void _AddPolylineThin(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs); + IMGUI_API void _AddPolylineThick(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a2caa877a..23d340dc4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10396,7 +10396,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) static int curve_segments_override_v = 8; static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 100.0f, "%.0f"); - ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f"); + ImGui::DragFloat("Thickness", &thickness, 0.05f, 0.0f, 32.0f, "%.02f"); ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b0abc0585..37c5ae4b9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -838,9 +838,729 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c _IdxWritePtr += 3; \ } (void)0 -// TODO: Thickness anti-aliased lines cap are missing their AA fringe. -// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. +#define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) +#define IM_POLYLINE_MITER_LIMIT (4.0f) + +static void CalcSegmentNormals(const ImVec2* points, const int points_count, ImVec2* normals, float* sqr_lengths, bool closed) +{ + // Calculate normals for each line segment + for (int i = 0; i < points_count - 1; i++) + { + float dx = points[i+1].x - points[i].x; + float dy = points[i+1].y - points[i].y; + const float d2 = dx*dx + dy*dy; + const float inv_len = (d2 > 0.0f) ? 1.f / sqrtf(d2) : 0.f; //ImRsqrt(d2) : 0.f; + normals[i].x = -dy * inv_len; + normals[i].y = dx * inv_len; + sqr_lengths[i] = d2; + } + if (closed) + { + const float dx = points[0].x - points[points_count - 1].x; + const float dy = points[0].y - points[points_count - 1].y; + const float d2 = dx*dx + dy*dy; + const float inv_len = (d2 > 0.0f) ? 1.f / sqrtf(d2) : 0.f; //ImRsqrt(d2) : 0.f; + normals[points_count - 1].x = -dy * inv_len; + normals[points_count - 1].y = dx * inv_len; + sqr_lengths[points_count - 1] = d2; + } + else + { + normals[points_count - 1] = normals[points_count - 2]; + sqr_lengths[points_count - 1] = 0.f; + } +} + +void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs) +{ + const bool closed = (flags & ImDrawFlags_Closed) != 0; + + _Data->TempBuffer.reserve_discard(points_count * 2); + ImVec2* normals = _Data->TempBuffer.Data; + float* sqr_lengths = (float*)(normals + points_count); + CalcSegmentNormals(points, points_count, normals, sqr_lengths, closed); + + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + + thickness += _FringeScale; + const float half_thickness = thickness * 0.5f; + const float miter_distance_limit = half_thickness * IM_POLYLINE_MITER_LIMIT; + const float miter_distance_limit_sqr = miter_distance_limit * miter_distance_limit; + const float half_aa = _FringeScale * 0.5f; + + // TODO: Each point will generate 2-7 vertices. The worst case happens really rarely. This can be issue with large polylines and 16it indices. + // One option could be to calculate the miter values and overl & bevel flags before, then alloc, and finally commit. + int idx_count = 0; + int vtx_count = 0; + if (closed) + { + vtx_count = /*body*/points_count * 7 + /*closing*/3; + idx_count = (/*body*/points_count * 5 + /*closing*/4) * 3; + } + else + { + // Body + caps + vtx_count = /*body*/(points_count - 2) * 7 + /*caps*/(6 * 2); + idx_count = (/*body*/(points_count - 2) * 5 + /*last seg*/4 + /*caps*/(4 * 2)) * 3; + } + + PrimReserve(idx_count, vtx_count); + + ImDrawVert* start_vtx_ptr = _VtxWritePtr; + ImDrawIdx* start_idx_ptr = _IdxWritePtr; + + int base_idx = (int)_VtxCurrentIdx; + + ImVec2 p1; + ImVec2 n1; + float len_sqr1; + + const float half_texel = (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x; + const ImVec2 uv0(tex_uvs.x + half_texel, tex_uvs.y); + const ImVec2 uv1(tex_uvs.z - half_texel, tex_uvs.y); + const ImVec2 uv2((uv0.x+uv1.x)*0.5f, tex_uvs.y); + + int point_idx = 0; + int point_end = points_count; + if (!closed) + { + // Start cap + point_idx++; + point_end--; + p1 = points[0]; + n1 = normals[0]; + len_sqr1 = sqr_lengths[0]; + + const ImVec2 dir(n1.y, -n1.x); + const ImVec2 pa = p1 - dir * half_aa; + const ImVec2 pb = p1 + dir * half_aa; + + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa.x - n1.x * half_thickness , pa.y - n1.y * half_thickness , uv0, col_trans); + IM_APPEND_VTX(pa.x + n1.x * half_thickness , pa.y + n1.y * half_thickness , uv1, col_trans); + + int next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pb.x - n1.x * half_thickness , pb.y - n1.y * half_thickness , uv0, col); + IM_APPEND_VTX(pb.x + n1.x * half_thickness , pb.y + n1.y * half_thickness , uv1, col); + + // AA cap + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + base_idx = next_base_idx; + } + else + { + // Wrap around segment + p1 = points[points_count-1]; + n1 = normals[points_count-1]; + len_sqr1 = sqr_lengths[points_count-1]; + + // This will be filled later, allocate space. + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(0, 0, uv0, col); + IM_APPEND_VTX(0, 0, uv1, col); + } + + while (point_idx < point_end) + { + ImVec2 n0 = n1; + float len_sqr0 = len_sqr1; + p1 = points[point_idx]; + n1 = normals[point_idx]; + len_sqr1 = sqr_lengths[point_idx]; + + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float miter_scale_factor = (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? half_thickness / (1.0f + cos_theta) : FLT_MAX; // avoid division by zero + const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; + const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; + const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; + + const bool overlap = (len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT); + const bool bevel = miter_distance_sqr > miter_distance_limit_sqr; + + if (bevel) + { + // Clipped bevel + const float sin_theta = n0.y * n1.x - n0.x * n1.y; + float bevel_normal_x = n0.x + n1.x; + float bevel_normal_y = n0.y + n1.y; + IM_NORMALIZE2F_OVER_ZERO(bevel_normal_x, bevel_normal_y); + + const float signed_miter_offset = sin_theta < 0.0f ? half_thickness : -half_thickness; + const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); + const float pt_x = p1.x - bevel_normal_x * signed_miter_offset; + const float pt_y = p1.y - bevel_normal_y * signed_miter_offset; + const float sd_x = bevel_normal_y * side_offset; + const float sd_y = -bevel_normal_x * side_offset; + + if (overlap) + { + // Dislocated bevel. + if (sin_theta < 0.f) + { + IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 + IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); // 4 + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv0, col); // 5 + IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 6 + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 7 + IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 8 + + // Connect prev to next + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + // Bevel tris + IM_APPEND_TRI(base_idx + 6, base_idx + 2, base_idx + 4); + IM_APPEND_TRI(base_idx + 6, base_idx + 4, base_idx + 5); + IM_APPEND_TRI(base_idx + 6, base_idx + 5, base_idx + 7); + base_idx = next_base_idx; + } + else + { + IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 + IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv1, col); // 4 + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv1, col); // 5 + IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 6 + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 7 + IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 8 + + // Connect prev to next + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + // Bevel + IM_APPEND_TRI(base_idx + 6, base_idx + 7, base_idx + 5); + IM_APPEND_TRI(base_idx + 6, base_idx + 5, base_idx + 4); + IM_APPEND_TRI(base_idx + 6, base_idx + 4, base_idx + 3); + base_idx = next_base_idx; + } + } + else + { + // Bevel + if (sin_theta < 0.f) + { +/* IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv0, col); + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); + + // Bevel tri + IM_APPEND_TRI(base_idx+2, base_idx+3, base_idx+4); + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+4); + IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); + base_idx = next_base_idx;*/ + + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); // 2 + IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv0, col); // 4 + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); // 5 + + // Connect prev to next + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 5); + IM_APPEND_TRI(base_idx + 0, base_idx + 5, base_idx + 1); + // Bevel + IM_APPEND_TRI(base_idx + 3, base_idx + 5, base_idx + 2); + IM_APPEND_TRI(base_idx + 3, base_idx + 2, base_idx + 4); + IM_APPEND_TRI(base_idx + 3, base_idx + 4, base_idx + 5); + base_idx = next_base_idx; + } + else + { + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv1, col); // 2 + IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); // 4 + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv1, col); // 5 + + // Connect prev to next + IM_APPEND_TRI(base_idx + 0, base_idx + 4, base_idx + 2); + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 1); + // Bevel + IM_APPEND_TRI(base_idx + 3, base_idx + 2, base_idx + 4); + IM_APPEND_TRI(base_idx + 3, base_idx + 4, base_idx + 5); + IM_APPEND_TRI(base_idx + 3, base_idx + 5, base_idx + 2); + base_idx = next_base_idx; + +/* IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv1, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv1, col); + + // Bevel tri + IM_APPEND_TRI(base_idx + 3, base_idx + 4, base_idx + 2); + // Connect prev to next + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 2); + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 1); + base_idx = next_base_idx;*/ + } + } + } + else + { + if (overlap) + { + // Dislocated Miter + const float sin_theta = n0.y * n1.x - n0.x * n1.y; + if (sin_theta < 0.f) + { + + IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 + IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 + IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); // 4 + IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 5 + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 6 + IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 7 + + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); + // Miter + IM_APPEND_TRI(base_idx+5, base_idx+2, base_idx+4); + IM_APPEND_TRI(base_idx+5, base_idx+4, base_idx+6); + + base_idx = next_base_idx; + } + else + { + IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 + IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); // 4 + IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 5 + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 6 + IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 7 + + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); + // Miter + IM_APPEND_TRI(base_idx+5, base_idx+4, base_idx+3); + IM_APPEND_TRI(base_idx+5, base_idx+7, base_idx+4); + + base_idx = next_base_idx; + } + } + else + { + // Miter + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); // 2 + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); // 3 + + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); + + base_idx = next_base_idx; + } + } + + point_idx++; + } + + // End cap + if (!closed) + { + p1 = points[points_count-1]; + n1 = normals[points_count-1]; + + // End cap + const ImVec2 dir(n1.y, -n1.x); + const ImVec2 pa = p1 - dir * half_aa; + const ImVec2 pb = p1 + dir * half_aa; + + int next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa.x - n1.x * half_thickness, pa.y - n1.y * half_thickness, uv0, col); + IM_APPEND_VTX(pa.x + n1.x * half_thickness, pa.y + n1.y * half_thickness, uv1, col); + + IM_APPEND_VTX(pb.x - n1.x * half_thickness, pb.y - n1.y * half_thickness, uv0, col_trans); + IM_APPEND_VTX(pb.x + n1.x * half_thickness, pb.y + n1.y * half_thickness, uv1, col_trans); + + // Connect + IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); + base_idx = next_base_idx; + + // AA cap + IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); + } + else + { + // Connect the path. + start_vtx_ptr[0] = VtxBuffer.Data[base_idx+0]; + start_vtx_ptr[1] = VtxBuffer.Data[base_idx+1]; + } + + // Restore unused memory + const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); + const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); + IM_ASSERT(vtx_used <= vtx_count && idx_used <= idx_count); + PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); +} + +void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) +{ + const bool closed = (flags & ImDrawFlags_Closed) != 0; + + _Data->TempBuffer.reserve_discard(points_count * 2); + ImVec2* normals = _Data->TempBuffer.Data; + float* sqr_lengths = (float*)(normals + points_count); + CalcSegmentNormals(points, points_count, normals, sqr_lengths, closed); + + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + + // TODO: we can expand this by having one very long texture strip for the lines, + // or if place black 2x2 pixel next to the while pixel, and use texture clamping (that thickness would expand out of the texture). + const float max_width = (IM_DRAWLIST_TEX_LINES_WIDTH_MAX-1) * _FringeScale * 2.f; + thickness = ImMin(thickness, max_width); + + thickness += _FringeScale; // Place half of AA fringe each side of the line. + const float half_thickness = thickness * 0.5f; + const float miter_distance_limit = half_thickness * IM_POLYLINE_MITER_LIMIT; + const float miter_distance_limit_sqr = miter_distance_limit * miter_distance_limit; + const float half_aa = _FringeScale * 0.5f; + + int idx_count = 0; + int vtx_count = 0; + if (closed) + { + vtx_count = /*body*/points_count * 5 + /*closing*/3; + idx_count = (/*body*/points_count * 5 + /*closing*/4) * 3; + } + else + { + // Body + caps + vtx_count = /*body*/(points_count - 2) * 5 + /*caps*/(6 * 2); + idx_count = (/*body*/(points_count - 2) * 5 + /*last seg*/4 + /*caps*/(4 * 2)) * 3; + } + + PrimReserve(idx_count, vtx_count); + + ImDrawVert* start_vtx_ptr = _VtxWritePtr; + ImDrawIdx* start_idx_ptr = _IdxWritePtr; + + int base_idx = (int)_VtxCurrentIdx; + + ImVec2 p1; + ImVec2 n1; + float len_sqr1; + + const ImVec4 tex_uvs = _Data->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX]; + const ImVec2 uv_out(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); + const ImVec2 uv_in(tex_uvs.x + ((half_thickness + 0.5f) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); + + int point_idx = 0; + int point_end = points_count; + if (!closed) + { + point_idx++; + point_end--; + p1 = points[0]; + n1 = normals[0]; + len_sqr1 = sqr_lengths[0]; + + // Start cap + const ImVec2 dir(n1.y, -n1.x); + const ImVec2 pa = p1 - dir * half_aa; + const ImVec2 pb = p1 + dir * half_aa; + + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa.x - n1.x * half_thickness , pa.y - n1.y * half_thickness , uv_out, col_trans); + IM_APPEND_VTX(pa.x, pa.y, uv_in, col_trans); + IM_APPEND_VTX(pa.x + n1.x * half_thickness , pa.y + n1.y * half_thickness , uv_out, col_trans); + + int next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pb.x - n1.x * half_thickness , pb.y - n1.y * half_thickness , uv_out, col); + IM_APPEND_VTX(pb.x, pb.y, uv_in, col); + IM_APPEND_VTX(pb.x + n1.x * half_thickness , pb.y + n1.y * half_thickness , uv_out, col); + + // AA cap + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); + IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); + base_idx = next_base_idx; + } + else + { + p1 = points[points_count-1]; + n1 = normals[points_count-1]; + len_sqr1 = sqr_lengths[points_count-1]; + + // This will be filled later, allocate space. + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(0, 0, uv_out, col); + IM_APPEND_VTX(0, 0, uv_in, col); + IM_APPEND_VTX(0, 0, uv_out, col); + } + + while (point_idx < point_end) + { + ImVec2 n0 = n1; + float len_sqr0 = len_sqr1; + p1 = points[point_idx]; + n1 = normals[point_idx]; + len_sqr1 = sqr_lengths[point_idx]; + + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float miter_scale_factor = (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? half_thickness / (1.0f + cos_theta) : FLT_MAX; // avoid division by zero + const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; + const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; + const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; + + const bool overlap = (len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT); + const bool bevel = miter_distance_sqr > miter_distance_limit_sqr; + + if (bevel) + { + // Clipped bevel + const float sin_theta = n0.y * n1.x - n0.x * n1.y; + float bevel_normal_x = n0.x + n1.x; + float bevel_normal_y = n0.y + n1.y; + IM_NORMALIZE2F_OVER_ZERO(bevel_normal_x, bevel_normal_y); + + const float signed_miter_offset = sin_theta < 0.0f ? half_thickness : -half_thickness; + const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); + const float pt_x = p1.x - bevel_normal_x * signed_miter_offset; + const float pt_y = p1.y - bevel_normal_y * signed_miter_offset; + const float sd_x = bevel_normal_y * side_offset; + const float sd_y = -bevel_normal_x * side_offset; + + if (overlap) + { + // Dislocated bevel. + if (sin_theta < 0.f) + { + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); + IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv_out, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); + IM_APPEND_VTX(p1.x, p1.y, uv_in, col); + IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv_out, col); + + // Bevel tri + IM_APPEND_TRI(base_idx+3, base_idx+5, base_idx+6); + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+6); + IM_APPEND_TRI(base_idx+0, base_idx+6, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+4); + IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+2); + base_idx = next_base_idx; + } + else + { + IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv_out, col); + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv_out, col); + IM_APPEND_VTX(p1.x, p1.y, uv_in, col); + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); + + // Bevel tri + IM_APPEND_TRI(base_idx+6, base_idx+7, base_idx+4); + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+6); + IM_APPEND_TRI(base_idx+0, base_idx+6, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+4); + IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+2); + base_idx = next_base_idx; + } + } + else + { + // Bevel + if (sin_theta < 0.f) + { + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); + IM_APPEND_VTX(p1.x, p1.y, uv_in, col); + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv_out, col); + + // Bevel tri + IM_APPEND_TRI(base_idx+3, base_idx+4, base_idx+5); + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+5); + IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+6); + IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+2); + base_idx = next_base_idx; + } + else + { + IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv_out, col); + IM_APPEND_VTX(p1.x, p1.y, uv_in, col); + IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); + + // Bevel tri + IM_APPEND_TRI(base_idx+5, base_idx+6, base_idx+3); + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+5); + IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+3); + IM_APPEND_TRI(base_idx+1, base_idx+3, base_idx+2); + base_idx = next_base_idx; + } + } + } + else + { + if (overlap) + { + // Dislocated miter + const float sin_theta = n0.y * n1.x - n0.x * n1.y; + if (sin_theta < 0.f) + { + IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv_out, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv_out, col); + IM_APPEND_VTX(p1.x, p1.y, uv_in, col); + IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv_out, col); + + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+5); + IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+3); + IM_APPEND_TRI(base_idx+1, base_idx+3, base_idx+2); + + base_idx = next_base_idx; + } + else + { + IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv_out, col); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv_out, col); + IM_APPEND_VTX(p1.x, p1.y, uv_in, col); + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv_out, col); + + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+5); + IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+6); + IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+2); + + base_idx = next_base_idx; + } + } + else + { + // Miter + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv_out, col); + IM_APPEND_VTX(p1.x, p1.y, uv_in, col); + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv_out, col); + + // Connect prev to next + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); + IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); + + base_idx = next_base_idx; + } + } + + point_idx++; + } + + // End cap + if (!closed) + { + p1 = points[points_count-1]; + n1 = normals[points_count-1]; + + // End cap + const ImVec2 dir(n1.y, -n1.x); + const ImVec2 pa = p1 - dir * half_aa; + const ImVec2 pb = p1 + dir * half_aa; + + int next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa.x - n1.x * half_thickness, pa.y - n1.y * half_thickness, uv_out, col); + IM_APPEND_VTX(pa.x, pa.y, uv_in, col); + IM_APPEND_VTX(pa.x + n1.x * half_thickness, pa.y + n1.y * half_thickness, uv_out, col); + + IM_APPEND_VTX(pb.x - n1.x * half_thickness, pb.y - n1.y * half_thickness, uv_out, col_trans); + IM_APPEND_VTX(pb.x, pb.y, uv_in, col_trans); + IM_APPEND_VTX(pb.x + n1.x * half_thickness, pb.y + n1.y * half_thickness, uv_out, col_trans); + + // Connect + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); + IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); + base_idx = next_base_idx; + + // AA cap + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); + IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); + IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); + IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); + } + else + { + // Connect the path. + start_vtx_ptr[0] = VtxBuffer.Data[base_idx+0]; + start_vtx_ptr[1] = VtxBuffer.Data[base_idx+1]; + start_vtx_ptr[2] = VtxBuffer.Data[base_idx+2]; + } + + // Restore unused memory + const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); + const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); + IM_ASSERT(vtx_used <= vtx_count && idx_used <= idx_count); + PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); +} + void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) +{ + if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) + return; + + float screen_thickness = thickness / _FringeScale; + if (screen_thickness < 1.f/255.f) + return; + if (screen_thickness < 1.f) + { + const float alpha = thickness; + col = ImGui::GetColorU32(col, alpha); + screen_thickness = 1.f; + thickness = _FringeScale; + } + + // TODO: square vs miter cap + // TODO: support splitting very long lines to multiple draw calls. + + // We can use cheaper rendering if the thickness is integer size. + const int int_thickness = (int)screen_thickness; + const bool can_use_thin = ImAbs(screen_thickness - (float)int_thickness) < 0.01f && (int_thickness >= 1 && int_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX); + + if (can_use_thin) + { + const ImVec4 tex_uvs = _Data->TexUvLines[int_thickness]; + _AddPolylineThin(points, points_count, col, (float)int_thickness * _FringeScale, flags, tex_uvs); + } + else + { + _AddPolylineThick(points, points_count, col, thickness, flags); + } +} + +void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) return; From a5b8a920c323b5e1e2df40a0224d2e2aeca2103f Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 21 Apr 2026 15:28:20 +0300 Subject: [PATCH 059/245] DrawList: added better handling for rendering degenerate geometry. (#2183, #7972) - Add ImDrawFlags_MiterOnly which is used to indicate that a path contains simple geometry and can be rendered using mitered corners - Added handling of degenerated shapes for stroked rectangle, circle, ngon, and ellipse - Render shapes filled when outline covers the whole shape - Clamp very small circles and ngons, and use alpha fade below one pixel - Added correct offset for ellipse --- imgui.h | 5 +- imgui_demo.cpp | 2 +- imgui_draw.cpp | 263 ++++++++++++++++++++++++++++++++++++------------- 3 files changed, 200 insertions(+), 70 deletions(-) diff --git a/imgui.h b/imgui.h index c52455b3e..5d5599058 100644 --- a/imgui.h +++ b/imgui.h @@ -3308,6 +3308,7 @@ struct ImDrawListSplitter enum ImDrawFlags_ { ImDrawFlags_None = 0, + //ImDrawFlags_Closed = 1, // -> FLAG MOVED BELOW. Prior to 1.92.8 (May 2026): ImDrawFlags_Closed was guaranteed to be == (1<<0) == 1, for legacy compatibility reason. Hardcoded use of 1 or true should be replaced with 'ImDrawFlags_Closed'. // Rounding for AddRect(), AddRectFilled(), PathRect() // - When not specified, we defaults to ImDrawFlags_RoundCornersAll! So you only need to use those flags if you want another configuration. @@ -3325,8 +3326,8 @@ enum ImDrawFlags_ ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, // Stroke options - ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. - //ImDrawFlags_Closed = 1, // Prior to 1.92.8 (May 2026), ImDrawFlags_Closed was guaranteed to be == 1<<0 == 1 for legacy compatibility reason. Hardcoded use of 1 or true should be replaced. + ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. + ImDrawFlags_MiterOnly = 1 << 10, // PathStroke(), AddPolyline(): use miter corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (Default) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 23d340dc4..14de91638 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10395,7 +10395,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) static bool curve_segments_override = false; static int curve_segments_override_v = 8; static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); - ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 100.0f, "%.0f"); + ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); ImGui::DragFloat("Thickness", &thickness, 0.05f, 0.0f, 32.0f, "%.02f"); ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 37c5ae4b9..29aa4bf29 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -849,7 +849,7 @@ static void CalcSegmentNormals(const ImVec2* points, const int points_count, ImV float dx = points[i+1].x - points[i].x; float dy = points[i+1].y - points[i].y; const float d2 = dx*dx + dy*dy; - const float inv_len = (d2 > 0.0f) ? 1.f / sqrtf(d2) : 0.f; //ImRsqrt(d2) : 0.f; + const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; normals[i].x = -dy * inv_len; normals[i].y = dx * inv_len; sqr_lengths[i] = d2; @@ -859,7 +859,7 @@ static void CalcSegmentNormals(const ImVec2* points, const int points_count, ImV const float dx = points[0].x - points[points_count - 1].x; const float dy = points[0].y - points[points_count - 1].y; const float d2 = dx*dx + dy*dy; - const float inv_len = (d2 > 0.0f) ? 1.f / sqrtf(d2) : 0.f; //ImRsqrt(d2) : 0.f; + const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; normals[points_count - 1].x = -dy * inv_len; normals[points_count - 1].y = dx * inv_len; sqr_lengths[points_count - 1] = d2; @@ -867,13 +867,14 @@ static void CalcSegmentNormals(const ImVec2* points, const int points_count, ImV else { normals[points_count - 1] = normals[points_count - 2]; - sqr_lengths[points_count - 1] = 0.f; + sqr_lengths[points_count - 1] = 0.0f; } } void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs) { const bool closed = (flags & ImDrawFlags_Closed) != 0; + const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; _Data->TempBuffer.reserve_discard(points_count * 2); ImVec2* normals = _Data->TempBuffer.Data; @@ -892,16 +893,17 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, // One option could be to calculate the miter values and overl & bevel flags before, then alloc, and finally commit. int idx_count = 0; int vtx_count = 0; + const int max_verts_per_point = miters_only ? 2 : 7; + const int max_tris_per_point = miters_only ? 2 : 5; if (closed) { - vtx_count = /*body*/points_count * 7 + /*closing*/3; - idx_count = (/*body*/points_count * 5 + /*closing*/4) * 3; + vtx_count = /*body*/points_count * max_verts_per_point + /*closing*/2; + idx_count = (/*body*/points_count * max_tris_per_point + /*closing*/2) * 3; } else { - // Body + caps - vtx_count = /*body*/(points_count - 2) * 7 + /*caps*/(6 * 2); - idx_count = (/*body*/(points_count - 2) * 5 + /*last seg*/4 + /*caps*/(4 * 2)) * 3; + vtx_count = /*body*/(points_count - 2) * max_verts_per_point + /*caps*/(6 * 2); + idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/4 + /*caps*/(4 * 2)) * 3; } PrimReserve(idx_count, vtx_count); @@ -978,8 +980,8 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - const bool overlap = (len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT); - const bool bevel = miter_distance_sqr > miter_distance_limit_sqr; + const bool overlap = !miters_only && ((len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT)); + const bool bevel = !miters_only && (miter_distance_sqr > miter_distance_limit_sqr); if (bevel) { @@ -990,7 +992,7 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, IM_NORMALIZE2F_OVER_ZERO(bevel_normal_x, bevel_normal_y); const float signed_miter_offset = sin_theta < 0.0f ? half_thickness : -half_thickness; - const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); + const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.0f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); const float pt_x = p1.x - bevel_normal_x * signed_miter_offset; const float pt_y = p1.y - bevel_normal_y * signed_miter_offset; const float sd_x = bevel_normal_y * side_offset; @@ -999,7 +1001,7 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, if (overlap) { // Dislocated bevel. - if (sin_theta < 0.f) + if (sin_theta < 0.0f) { IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 @@ -1043,7 +1045,7 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, else { // Bevel - if (sin_theta < 0.f) + if (sin_theta < 0.0f) { /* IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1109,7 +1111,7 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, { // Dislocated Miter const float sin_theta = n0.y * n1.x - n0.x * n1.y; - if (sin_theta < 0.f) + if (sin_theta < 0.0f) { IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 @@ -1211,6 +1213,7 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { const bool closed = (flags & ImDrawFlags_Closed) != 0; + const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; _Data->TempBuffer.reserve_discard(points_count * 2); ImVec2* normals = _Data->TempBuffer.Data; @@ -1221,7 +1224,7 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, // TODO: we can expand this by having one very long texture strip for the lines, // or if place black 2x2 pixel next to the while pixel, and use texture clamping (that thickness would expand out of the texture). - const float max_width = (IM_DRAWLIST_TEX_LINES_WIDTH_MAX-1) * _FringeScale * 2.f; + const float max_width = (IM_DRAWLIST_TEX_LINES_WIDTH_MAX-1) * _FringeScale * 2.0f; thickness = ImMin(thickness, max_width); thickness += _FringeScale; // Place half of AA fringe each side of the line. @@ -1232,16 +1235,18 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, int idx_count = 0; int vtx_count = 0; + const int max_verts_per_point = miters_only ? 3 : 5; + const int max_tris_per_point = miters_only ? 4 : 5; if (closed) { - vtx_count = /*body*/points_count * 5 + /*closing*/3; - idx_count = (/*body*/points_count * 5 + /*closing*/4) * 3; + vtx_count = /*body*/points_count * max_verts_per_point + /*closing*/3; + idx_count = (/*body*/points_count * max_tris_per_point + /*closing*/4) * 3; } else { // Body + caps - vtx_count = /*body*/(points_count - 2) * 5 + /*caps*/(6 * 2); - idx_count = (/*body*/(points_count - 2) * 5 + /*last seg*/4 + /*caps*/(4 * 2)) * 3; + vtx_count = /*body*/(points_count - 2) * max_verts_per_point + /*caps*/(6 * 2); + idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/4 + /*caps*/(4 * 2)) * 3; } PrimReserve(idx_count, vtx_count); @@ -1321,11 +1326,12 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - const bool overlap = (len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT); - const bool bevel = miter_distance_sqr > miter_distance_limit_sqr; + const bool overlap = !miters_only && ((len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT)); + const bool bevel = !miters_only && (miter_distance_sqr > miter_distance_limit_sqr); if (bevel) { + IM_ASSERT(!miters_only); // Clipped bevel const float sin_theta = n0.y * n1.x - n0.x * n1.y; float bevel_normal_x = n0.x + n1.x; @@ -1333,7 +1339,7 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, IM_NORMALIZE2F_OVER_ZERO(bevel_normal_x, bevel_normal_y); const float signed_miter_offset = sin_theta < 0.0f ? half_thickness : -half_thickness; - const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); + const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.0f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); const float pt_x = p1.x - bevel_normal_x * signed_miter_offset; const float pt_y = p1.y - bevel_normal_y * signed_miter_offset; const float sd_x = bevel_normal_y * side_offset; @@ -1342,7 +1348,7 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, if (overlap) { // Dislocated bevel. - if (sin_theta < 0.f) + if (sin_theta < 0.0f) { IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv_out, col); @@ -1382,7 +1388,7 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, else { // Bevel - if (sin_theta < 0.f) + if (sin_theta < 0.0f) { IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1422,9 +1428,10 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, { if (overlap) { + IM_ASSERT(!miters_only); // Dislocated miter const float sin_theta = n0.y * n1.x - n0.x * n1.y; - if (sin_theta < 0.f) + if (sin_theta < 0.0f) { IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv_out, col); const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1532,13 +1539,13 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 return; float screen_thickness = thickness / _FringeScale; - if (screen_thickness < 1.f/255.f) + if (screen_thickness < 1.0f / 255.0f) return; - if (screen_thickness < 1.f) + if (screen_thickness < 1.0f) { - const float alpha = thickness; + const float alpha = screen_thickness; col = ImGui::GetColorU32(col, alpha); - screen_thickness = 1.f; + screen_thickness = 1.0f; thickness = _FringeScale; } @@ -2463,7 +2470,6 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c } // p_min = upper-left, p_max = lower-right -// Note we don't render 1 pixels sized rectangles properly. void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { // If this assert triggers on legacy code: @@ -2490,8 +2496,51 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); +#if 0 // shiny_polyline + // FIXME-POLYLINE + + const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + ImVec2 adjusted_min = p_min; + ImVec2 adjusted_max = p_max; + float adjusted_rounding = rounding; + + const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); + if (stroke_pos == ImDrawFlags_StrokeInside) + { + adjusted_min += offset; + adjusted_max -= offset; + adjusted_rounding -= thickness * 0.5f; + } + else if (stroke_pos == ImDrawFlags_StrokeOutside) + { + adjusted_min -= offset; + adjusted_max += offset; + adjusted_rounding += thickness * 0.5f; + } + else if (stroke_pos == ImDrawFlags_StrokeLegacy) + { + adjusted_min += ImVec2(0.50f, 0.50f); + if (Flags & ImDrawListFlags_AntiAliasedLines) + adjusted_max -= ImVec2(0.50f, 0.50f); + else + adjusted_max -= ImVec2(0.49f, 0.49f); // Better looking lower-right corner and rounded non-AA shapes. + } + + const float width = adjusted_max.x - adjusted_min.x; + const float height = adjusted_max.y - adjusted_min.y; + if (ImMin(width, height) < (thickness + _FringeScale)) + { + // Rectangle has collapsed into filled rectangle. + AddRectFilled(p_min, p_max, col, rounding, flags); + return; + } + + // TODO: does not handle well the case that radius < thickness/2. + PathRect(adjusted_min, adjusted_max, adjusted_rounding, flags); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | flags); +#else + const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) { if ((flags & ImDrawFlags_RoundCornersMask_) == 0) @@ -2592,14 +2641,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl rounding += (rounding != 0.0f) ? thickness * 0.5f : 0.0f; PathRect(p_min - offset, p_max + offset, rounding, flags); } - else if (stroke_pos == ImDrawFlags_StrokeLegacy) - { - if (Flags & ImDrawListFlags_AntiAliasedLines) - PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); - else - PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. - } PathStroke(col, thickness, ImDrawFlags_Closed); +#endif } void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags) @@ -2758,30 +2801,46 @@ void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImV void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) { - if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) + if ((col & IM_COL32_A_MASK) == 0 || radius < 0.01f) return; + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + if (g_LEGACY_STROKES) { radius -= 0.5f; } else { - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeInside) radius -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - radius -= thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); + radius -= thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) radius += thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeLegacy) radius -= 0.5f; } + float adjusted_radius = radius; + if (stroke_pos == ImDrawFlags_StrokeInside) + adjusted_radius -= thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + adjusted_radius += thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeLegacy) + adjusted_radius -= 0.5f; + if (adjusted_radius < (thickness * 0.5f + _FringeScale * 0.5f)) + { + // The circle has collapsed into a filled circle. + AddCircleFilled(center, radius, col, num_segments); + return; + } + if (num_segments <= 0) { // Use arc with automatic segment count - _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); + const int a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); // Radius used here inteitionally so that the circle matches filled circle of same radius. + _PathArcToFastEx(center, adjusted_radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, a_step); _Path.Size--; } else @@ -2791,17 +2850,27 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); + PathArcTo(center, adjusted_radius, 0.0f, a_max, num_segments - 1); } - PathStroke(col, thickness, ImDrawFlags_Closed); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); } void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) { - if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) + if ((col & IM_COL32_A_MASK) == 0) return; + float screen_diameter = radius * 2.0f / _FringeScale; + if (screen_diameter < 1.0f / 255.0f) + return; + if (screen_diameter < 1.0f) + { + const float alpha = screen_diameter; + col = ImGui::GetColorU32(col, alpha); + radius = _FringeScale * 0.5f; + } + if (num_segments <= 0) { // Use arc with automatic segment count @@ -2828,26 +2897,30 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ return; if (g_LEGACY_STROKES) - { radius -= 0.5f; - } - else + + const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + const float unit_apothem = ImCos(IM_PI / (float)num_segments); + const float miter_thickness = thickness / unit_apothem; + + float adjusted_radius = radius; + if (stroke_pos == ImDrawFlags_StrokeInside) + adjusted_radius -= miter_thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + adjusted_radius += miter_thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeLegacy) + adjusted_radius -= 0.5f; + if (adjusted_radius < (miter_thickness * 0.5f + _FringeScale * 0.5f)) { - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeInside) - radius -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - radius -= thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); - else if (stroke_pos == ImDrawFlags_StrokeOutside) - radius += thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeLegacy) - radius -= 0.5f; + // The polygon has collapsed into a filled polygon. + AddNgonFilled(center, radius, col, num_segments); + return; } - // Because we are filling a closed shape we remove 1 from the count of segments/points + // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); - PathStroke(col, thickness, ImDrawFlags_Closed); + PathArcTo(center, adjusted_radius, 0.0f, a_max, num_segments - 1); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); } // Guaranteed to honor 'num_segments' @@ -2856,6 +2929,16 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; + float screen_diameter = radius * 2.0f / _FringeScale; + if (screen_diameter < 1.0f / 255.0f) + return; + if (screen_diameter < 1.0f) + { + const float alpha = screen_diameter; + col = ImGui::GetColorU32(col, alpha); + radius = _FringeScale * 0.5f; + } + // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); @@ -2868,6 +2951,8 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co if ((col & IM_COL32_A_MASK) == 0) return; + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + ImVec2 r; if (g_LEGACY_STROKES) { @@ -2876,7 +2961,6 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co else { r = radius; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeInside) r -= ImVec2(thickness * 0.5f, thickness * 0.5f); else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -2888,13 +2972,58 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co r += ImVec2(thickness * 0.5f, thickness * 0.5f); } - if (num_segments <= 0) - num_segments = _CalcCircleAutoSegmentCount(ImMax(r.x, r.y)); // A bit pessimistic, maybe there's a better computation to do here. + float stroke_offset = 0.0f; + if (stroke_pos == ImDrawFlags_StrokeInside) + stroke_offset = -thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + stroke_offset = thickness * 0.5f; + if ((ImMin(radius.x, radius.y) + stroke_offset) < (thickness * 0.5f + _FringeScale * 0.5f)) + { + AddEllipseFilled(center, radius, col, rot, num_segments); + return; + } - // Because we are filling a closed shape we remove 1 from the count of segments/points - const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; - PathEllipticalArcTo(center, r, rot, 0.0f, a_max, num_segments - 1); - PathStroke(col, thickness, ImDrawFlags_Closed); + if (num_segments <= 0) + num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. + + _Path.reserve(_Path.Size + (num_segments + 1)); + + // Custom tessellation, since offset ellipse is not an ellipse anymore. + const float cos_rot = ImCos(rot); + const float sin_rot = ImSin(rot); + if (stroke_offset != 0.0f) + { + const float inv_rx = 1.0f / radius.x; + const float inv_ry = 1.0f / radius.y; + for (int i = 0; i < num_segments; i++) + { + const float a = ((float)i / (float)num_segments) * IM_PI * 2.0f; + const float dir_x = ImCos(a); + const float dir_y = ImSin(a); + float nx = dir_x * inv_rx; + float ny = dir_y * inv_ry; + IM_NORMALIZE2F_OVER_ZERO(nx, ny); + ImVec2 point(dir_x * radius.x + nx * stroke_offset, dir_y * radius.y + ny * stroke_offset); + const ImVec2 rel((point.x * cos_rot) - (point.y * sin_rot), (point.x * sin_rot) + (point.y * cos_rot)); + point.x = rel.x + center.x; + point.y = rel.y + center.y; + _Path.push_back(point); + } + } + else + { + for (int i = 0; i < num_segments; i++) + { + const float a = ((float)i / (float)num_segments) * IM_PI * 2.0f; + ImVec2 point(ImCos(a) * radius.x, ImSin(a) * radius.y); + const ImVec2 rel((point.x * cos_rot) - (point.y * sin_rot), (point.x * sin_rot) + (point.y * cos_rot)); + point.x = rel.x + center.x; + point.y = rel.y + center.y; + _Path.push_back(point); + } + } + + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); } void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments) From 6c7b083e0e5167be8c5f4fa27e3516526ef091e7 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Wed, 22 Apr 2026 22:24:55 +0300 Subject: [PATCH 060/245] DrawList: improved handling of rounded stroked rectangles, where rounding is less than stroke thickness. --- imgui.h | 4 +-- imgui_draw.cpp | 83 ++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 66 insertions(+), 21 deletions(-) diff --git a/imgui.h b/imgui.h index 5d5599058..016a89a0d 100644 --- a/imgui.h +++ b/imgui.h @@ -3532,8 +3532,8 @@ struct ImDrawList IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddPolylineThin(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs); - IMGUI_API void _AddPolylineThick(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags); + IMGUI_API void _AddPolylineThin(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs); + IMGUI_API void _AddPolylineThick(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 29aa4bf29..6fb8d056f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -871,16 +871,10 @@ static void CalcSegmentNormals(const ImVec2* points, const int points_count, ImV } } -void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs) +void ImDrawList::_AddPolylineThin(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs) { const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; - - _Data->TempBuffer.reserve_discard(points_count * 2); - ImVec2* normals = _Data->TempBuffer.Data; - float* sqr_lengths = (float*)(normals + points_count); - CalcSegmentNormals(points, points_count, normals, sqr_lengths, closed); - const ImU32 col_trans = col & ~IM_COL32_A_MASK; thickness += _FringeScale; @@ -1210,16 +1204,11 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, const int points_count, PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } -void ImDrawList::_AddPolylineThick(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::_AddPolylineThick(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; - _Data->TempBuffer.reserve_discard(points_count * 2); - ImVec2* normals = _Data->TempBuffer.Data; - float* sqr_lengths = (float*)(normals + points_count); - CalcSegmentNormals(points, points_count, normals, sqr_lengths, closed); - const ImU32 col_trans = col & ~IM_COL32_A_MASK; // TODO: we can expand this by having one very long texture strip for the lines, @@ -1556,14 +1545,19 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const int int_thickness = (int)screen_thickness; const bool can_use_thin = ImAbs(screen_thickness - (float)int_thickness) < 0.01f && (int_thickness >= 1 && int_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX); + _Data->TempBuffer.reserve_discard(points_count * 2); + ImVec2* normals = _Data->TempBuffer.Data; + float* sqr_lengths = (float*)(normals + points_count); + CalcSegmentNormals(points, points_count, normals, sqr_lengths, (flags & ImDrawFlags_Closed) != 0); + if (can_use_thin) { const ImVec4 tex_uvs = _Data->TexUvLines[int_thickness]; - _AddPolylineThin(points, points_count, col, (float)int_thickness * _FringeScale, flags, tex_uvs); + _AddPolylineThin(points, normals, sqr_lengths, points_count, col, (float)int_thickness * _FringeScale, flags, tex_uvs); } else { - _AddPolylineThick(points, points_count, col, thickness, flags); + _AddPolylineThick(points, normals, sqr_lengths, points_count, col, thickness, flags); } } @@ -2469,6 +2463,25 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c PrimUnreserve(idx_allocated - idx_used, vtx_allocated - vtx_used); } +static void RectCornerArc(ImDrawList* draw_list, float cx, float cy, float radius, const int arc_step, const int arc_point_count, const int corner) +{ + if (radius == 0.f) + { + draw_list->_Path.push_back(ImVec2(cx, cy)); + return; + } + + int arc_idx = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) * corner; + for (int i = 0; i < arc_point_count; i++) + { + ImVec2 pt; + pt.x = cx - draw_list->_Data->ArcFastVtx[arc_idx].x * radius; + pt.y = cy - draw_list->_Data->ArcFastVtx[arc_idx].y * radius; + draw_list->_Path.push_back(pt); + arc_idx = (arc_idx + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; + } +} + // p_min = upper-left, p_max = lower-right void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { @@ -2499,8 +2512,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); #if 0 // shiny_polyline // FIXME-POLYLINE + const bool has_rounding = (rounding >= _FringeScale); - const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); ImVec2 adjusted_min = p_min; ImVec2 adjusted_max = p_max; float adjusted_rounding = rounding; @@ -2536,9 +2549,41 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - // TODO: does not handle well the case that radius < thickness/2. - PathRect(adjusted_min, adjusted_max, adjusted_rounding, flags); - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | flags); + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; + + if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + PathLineTo(adjusted_min); + PathLineTo(ImVec2(adjusted_max.x, adjusted_min.y)); + PathLineTo(adjusted_max); + PathLineTo(ImVec2(adjusted_min.x, adjusted_max.y)); + } + else + { + // Constrain rounding to rect dimensions + adjusted_rounding = ImMin(adjusted_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + adjusted_rounding = ImMin(adjusted_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + // We have to have some kind of curve to render the corner with PathStroke(). + // The small value limits the rounding to about half the stroke radius. + adjusted_rounding = ImMax(_FringeScale * 0.25f, adjusted_rounding); + + const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? adjusted_rounding : 0.0f; + const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? adjusted_rounding : 0.0f; + const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? adjusted_rounding : 0.0f; + const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? adjusted_rounding : 0.0f; + + // Use custom arcs so that we can specify the point count. + const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(ImMax(adjusted_rounding, thickness * 0.5f)), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); + const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; + + RectCornerArc(this, adjusted_min.x + rounding_tl, adjusted_min.y + rounding_tl, rounding_tl, arc_step, arc_point_count, 0); + RectCornerArc(this, adjusted_max.x - rounding_tr, adjusted_min.y + rounding_tr, rounding_tr, arc_step, arc_point_count, 1); + RectCornerArc(this, adjusted_max.x - rounding_br, adjusted_max.y - rounding_br, rounding_br, arc_step, arc_point_count, 2); + RectCornerArc(this, adjusted_min.x + rounding_bl, adjusted_max.y - rounding_bl, rounding_bl, arc_step, arc_point_count, 3); + } + + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); #else const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) From 049f1a799a376dbc094c4a697a49af51d81915d0 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 24 Apr 2026 10:14:11 +0300 Subject: [PATCH 061/245] DrawList: added special case rendering for the stroked rects when the raounding radius gets really small compared to the stroke thickness. --- imgui.h | 1 + imgui_draw.cpp | 135 ++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 111 insertions(+), 25 deletions(-) diff --git a/imgui.h b/imgui.h index 016a89a0d..f476f0c36 100644 --- a/imgui.h +++ b/imgui.h @@ -3534,6 +3534,7 @@ struct ImDrawList IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); IMGUI_API void _AddPolylineThin(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs); IMGUI_API void _AddPolylineThick(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags); + IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6fb8d056f..63f4f70c6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2463,23 +2463,108 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c PrimUnreserve(idx_allocated - idx_used, vtx_allocated - vtx_used); } -static void RectCornerArc(ImDrawList* draw_list, float cx, float cy, float radius, const int arc_step, const int arc_point_count, const int corner) +// Draws rounded rectangle where thickness/2 > rounding. If rendered using the regular polyline, the stroke will fold and leave artefact on the corner if rendered with transparency. +// The stroke is positioned inside the rectangle. +void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { - if (radius == 0.f) + thickness += _FringeScale; + + // Adjust the rounding to be the outside radius. + rounding += thickness * 0.5f; + + const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(rounding), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); + const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; + + int vtx_count = (4 + arc_point_count) * 4 + 4; + int idx_count = (4 + arc_point_count - 1) * 4 * 3; + + PrimReserve(idx_count, vtx_count); + ImDrawVert* start_vtx_ptr = _VtxWritePtr; + ImDrawIdx* start_idx_ptr = _IdxWritePtr; + + const float ht = thickness * 0.5f; + const ImVec2 corner_pos[4] = { + ImVec2(p_min.x - ht, p_min.y - ht), + ImVec2(p_max.x + ht, p_min.y - ht), + ImVec2(p_max.x + ht, p_max.y + ht), + ImVec2(p_min.x - ht, p_max.y + ht) + }; + static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; + static const ImDrawFlags corner_flags[4] = { ImDrawFlags_RoundCornersTopLeft, ImDrawFlags_RoundCornersTopRight, ImDrawFlags_RoundCornersBottomRight, ImDrawFlags_RoundCornersBottomLeft }; + + const float stem_offset = thickness - ImMax(thickness - rounding, _FringeScale); + + const ImVec4 tex_uvs = _Data->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX]; // TODO: max uv + const ImVec2 outer_uv0(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); + const ImVec2 outer_uv1(tex_uvs.x + ((0.5f + stem_offset) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); + const ImVec2 inner_uv0(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); + const ImVec2 inner_uv1(tex_uvs.x + ((0.5f + thickness - stem_offset) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); + + int base_idx = (int)_VtxCurrentIdx; + IM_POLYLINE_APPEND_VERTEX(0, 0, outer_uv0, col); + IM_POLYLINE_APPEND_VERTEX(0, 0, outer_uv1, col); + IM_POLYLINE_APPEND_VERTEX(0, 0, inner_uv1, col); + IM_POLYLINE_APPEND_VERTEX(0, 0, inner_uv0, col); + + for (int corner = 0; corner < 4; corner++) { - draw_list->_Path.push_back(ImVec2(cx, cy)); - return; + const ImVec2 stem = corner_pos[corner] + corner_offset[corner] * stem_offset; + const ImVec2 inner = corner_pos[corner] + corner_offset[corner] * thickness; + const bool is_rounded = flags & corner_flags[corner]; + + const int arc_idx = (int)_VtxCurrentIdx; + if (is_rounded) + { + const ImVec2 center = corner_pos[corner] + corner_offset[corner] * rounding; + int a = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) * corner; + for (int i = 0; i < arc_point_count; i++) + { + const ImVec2 dir = _Data->ArcFastVtx[a]; + IM_POLYLINE_APPEND_VERTEX(center.x - dir.x * rounding, center.y - dir.y * rounding, outer_uv0, col); + a = (a + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; + } + } + else + { + IM_POLYLINE_APPEND_VERTEX(corner_pos[corner].x, corner_pos[corner].y, outer_uv0, col); + } + + const int stem0_idx = (int)_VtxCurrentIdx; + IM_POLYLINE_APPEND_VERTEX(stem.x, stem.y, outer_uv1, col); + const int stem1_idx = (int)_VtxCurrentIdx; + IM_POLYLINE_APPEND_VERTEX(stem.x, stem.y, inner_uv1, col); + const int inner_idx = (int)_VtxCurrentIdx; + IM_POLYLINE_APPEND_VERTEX(inner.x, inner.y, inner_uv0, col); + + // Arc + if (is_rounded) + { + for (int i = 0; i < arc_point_count-1; i++) + IM_POLYLINE_APPEND_TRI(stem0_idx, arc_idx + i, arc_idx + i + 1); + } + + // Connect with previous + IM_POLYLINE_APPEND_TRI(base_idx+0, arc_idx, stem0_idx); + IM_POLYLINE_APPEND_TRI(base_idx+0, stem0_idx, base_idx+1); + IM_POLYLINE_APPEND_TRI(base_idx+2, stem1_idx, inner_idx); + IM_POLYLINE_APPEND_TRI(base_idx+2, inner_idx, base_idx+3); + + + base_idx = stem0_idx - 1; } - int arc_idx = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) * corner; - for (int i = 0; i < arc_point_count; i++) - { - ImVec2 pt; - pt.x = cx - draw_list->_Data->ArcFastVtx[arc_idx].x * radius; - pt.y = cy - draw_list->_Data->ArcFastVtx[arc_idx].y * radius; - draw_list->_Path.push_back(pt); - arc_idx = (arc_idx + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; - } + // Close + start_vtx_ptr[0] = VtxBuffer.Data[base_idx+0]; + start_vtx_ptr[1] = VtxBuffer.Data[base_idx+1]; + start_vtx_ptr[2] = VtxBuffer.Data[base_idx+2]; + start_vtx_ptr[3] = VtxBuffer.Data[base_idx+3]; + + const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); + const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); + IM_ASSERT(idx_used <= idx_count && vtx_used <= vtx_count); + + if (idx_used < idx_count || vtx_used < vtx_count) + PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } // p_min = upper-left, p_max = lower-right @@ -2564,23 +2649,23 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl // Constrain rounding to rect dimensions adjusted_rounding = ImMin(adjusted_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); adjusted_rounding = ImMin(adjusted_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - // We have to have some kind of curve to render the corner with PathStroke(). - // The small value limits the rounding to about half the stroke radius. - adjusted_rounding = ImMax(_FringeScale * 0.25f, adjusted_rounding); + + if (thickness * 0.5f > adjusted_rounding) + { + // Special case rendering to avoid rendering artifacts at the corners. + // If rendered using the regular polyline, the stroke will fold and leave artifact on the corner if rendered with transparency. + _AddRectTinyRounding(adjusted_min, adjusted_max, col, adjusted_rounding, thickness, flags); + return; + } const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? adjusted_rounding : 0.0f; const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? adjusted_rounding : 0.0f; const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? adjusted_rounding : 0.0f; const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? adjusted_rounding : 0.0f; - - // Use custom arcs so that we can specify the point count. - const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(ImMax(adjusted_rounding, thickness * 0.5f)), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); - const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; - - RectCornerArc(this, adjusted_min.x + rounding_tl, adjusted_min.y + rounding_tl, rounding_tl, arc_step, arc_point_count, 0); - RectCornerArc(this, adjusted_max.x - rounding_tr, adjusted_min.y + rounding_tr, rounding_tr, arc_step, arc_point_count, 1); - RectCornerArc(this, adjusted_max.x - rounding_br, adjusted_max.y - rounding_br, rounding_br, arc_step, arc_point_count, 2); - RectCornerArc(this, adjusted_min.x + rounding_bl, adjusted_max.y - rounding_bl, rounding_bl, arc_step, arc_point_count, 3); + PathArcToFast(ImVec2(adjusted_min.x + rounding_tl, adjusted_min.y + rounding_tl), rounding_tl, 6, 9); + PathArcToFast(ImVec2(adjusted_max.x - rounding_tr, adjusted_min.y + rounding_tr), rounding_tr, 9, 12); + PathArcToFast(ImVec2(adjusted_max.x - rounding_br, adjusted_max.y - rounding_br), rounding_br, 0, 3); + PathArcToFast(ImVec2(adjusted_min.x + rounding_bl, adjusted_max.y - rounding_bl), rounding_bl, 3, 6); } PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); From 858b2b2952b95b1dc88156824c537b4ccce4f173 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 24 Apr 2026 13:44:23 +0300 Subject: [PATCH 062/245] DrawList: added more robust AddConvexPolyFilled(). (#2183, #7972) - add bevel handling for sharp corners - add limit to the miter distance to avoid inner shape spikes - add support for ImDrawFlags_MiterOnly to keep well behaved rendering fast --- imgui.h | 5 +- imgui_draw.cpp | 219 +++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 178 insertions(+), 46 deletions(-) diff --git a/imgui.h b/imgui.h index f476f0c36..0f5edb89a 100644 --- a/imgui.h +++ b/imgui.h @@ -3432,7 +3432,8 @@ struct ImDrawList // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); IMGUI_API void AddPolylineLegacy(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); - IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags = 0); + IMGUI_API void AddConvexPolyFilledLegacy(const ImVec2* points, int num_points, ImU32 col); IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); // Image primitives @@ -3449,7 +3450,7 @@ struct ImDrawList inline void PathClear() { _Path.Size = 0; } inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } - inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } + inline void PathFillConvex(ImU32 col, ImDrawFlags flags = 0) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, flags); _Path.Size = 0; } inline void PathFillConcave(ImU32 col) { AddConcavePolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0) { AddPolyline(_Path.Data, _Path.Size, col, thickness, flags); _Path.Size = 0; } IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 63f4f70c6..e3ee377db 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1041,18 +1041,6 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, ImVec2* normals, float* // Bevel if (sin_theta < 0.0f) { -/* IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv0, col); - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); - - // Bevel tri - IM_APPEND_TRI(base_idx+2, base_idx+3, base_idx+4); - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+4); - IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); - base_idx = next_base_idx;*/ - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); // 2 IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1084,18 +1072,6 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, ImVec2* normals, float* IM_APPEND_TRI(base_idx + 3, base_idx + 4, base_idx + 5); IM_APPEND_TRI(base_idx + 3, base_idx + 5, base_idx + 2); base_idx = next_base_idx; - -/* IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv1, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv1, col); - - // Bevel tri - IM_APPEND_TRI(base_idx + 3, base_idx + 4, base_idx + 2); - // Connect prev to next - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 2); - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 1); - base_idx = next_base_idx;*/ } } } @@ -1825,7 +1801,161 @@ void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, // - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. -void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col) +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, ImDrawFlags flags) +{ + if (points_count < 3 || (col & IM_COL32_A_MASK) == 0) + return; + +/* if (ImGui::GetIO().KeyShift) + { + AddConvexPolyFilledLegacy(points, points_count, col); + return; + }*/ + + const ImVec2 uv = _Data->TexUvWhitePixel; + const float half_aa = _FringeScale * 0.5f; + ImU32 col_trans = col & ~IM_COL32_A_MASK; + const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; + + const int idx_count = ((points_count - 2) + points_count * 3) * 3; + const int vtx_count = (points_count * 3); + PrimReserve(idx_count, vtx_count); + ImDrawVert* start_vtx_ptr = _VtxWritePtr; + ImDrawIdx* start_idx_ptr = _IdxWritePtr; + + // Compute normals and segment lengths + _Data->TempBuffer.reserve_discard(points_count * 2); + ImVec2* temp_normals = _Data->TempBuffer.Data; + float* temp_sqr_lengths = (float*)(_Data->TempBuffer.Data + points_count); + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + float dx = p1.x - p0.x; + float dy = p1.y - p0.y; + float d2 = dx*dx + dy*dy; + if (d2 > 0.f) + { + float inv_len = ImRsqrt(d2); + dx *= inv_len; + dy *= inv_len; + } + temp_normals[i0].x = dy; + temp_normals[i0].y = -dx; + temp_sqr_lengths[i0] = d2; + } + + + unsigned int vtx_inner_idx = _VtxCurrentIdx; + ImDrawVert* inner_vtx_ptr = _VtxWritePtr; + _VtxWritePtr += points_count; + _VtxCurrentIdx += points_count; + + unsigned int prev_outer_idx = (unsigned int )-1; // We dont know oueter vert could yet, will need to patch once we're done. + + const float miter_distance_limit = half_aa * IM_POLYLINE_MITER_LIMIT; + const float miter_distance_limit_sqr = miter_distance_limit * miter_distance_limit; + + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + float miter_scale_factor = ImMin(1000.f, (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? (half_aa / (1.0f + cos_theta)) : FLT_MAX); // avoid division by zero + + float dm_x = (n0.x + n1.x) * miter_scale_factor; + float dm_y = (n0.y + n1.y) * miter_scale_factor; + bool bevel = false; + + if (!miters_only) + { + const float miter_distance_sqr = dm_x * dm_x + dm_y * dm_y; + bevel = miter_distance_sqr > miter_distance_limit_sqr; + + const float segment_limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); + const bool overshoot = miter_distance_sqr > segment_limit_sqr; + if (overshoot) + { + // Make sure the miter stays within the polygon bounds. + const float scale = ImSqrt(segment_limit_sqr / miter_distance_sqr); + dm_x *= scale; + dm_y *= scale; + } + } + + // Inner + inner_vtx_ptr->pos.x = (points[i1].x - dm_x); inner_vtx_ptr->pos.y = (points[i1].y - dm_y); inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; + inner_vtx_ptr++; + + unsigned int prev_inner_idx = vtx_inner_idx + i0; + unsigned int inner_idx = vtx_inner_idx + i1; + unsigned int outer_idx = _VtxCurrentIdx; + + // Outer + if (bevel) + { + _VtxWritePtr->pos.x = (points[i1].x + n0.x * half_aa); _VtxWritePtr->pos.y = (points[i1].y + n0.y * half_aa); _VtxWritePtr->uv = uv; _VtxWritePtr->col = col_trans; + _VtxWritePtr++; + _VtxCurrentIdx++; + _VtxWritePtr->pos.x = (points[i1].x + n1.x * half_aa); _VtxWritePtr->pos.y = (points[i1].y + n1.y * half_aa); _VtxWritePtr->uv = uv; _VtxWritePtr->col = col_trans; + _VtxWritePtr++; + _VtxCurrentIdx++; + } + else + { + _VtxWritePtr->pos.x = (points[i1].x + dm_x); _VtxWritePtr->pos.y = (points[i1].y + dm_y); _VtxWritePtr->uv = uv; _VtxWritePtr->col = col_trans; + _VtxWritePtr++; + _VtxCurrentIdx++; + } + + // Connect with previous + _IdxWritePtr[0] = (ImDrawIdx)prev_outer_idx; + _IdxWritePtr[1] = (ImDrawIdx)outer_idx; + _IdxWritePtr[2] = (ImDrawIdx)inner_idx; + + _IdxWritePtr[3] = (ImDrawIdx)prev_outer_idx; + _IdxWritePtr[4] = (ImDrawIdx)inner_idx; + _IdxWritePtr[5] = (ImDrawIdx)prev_inner_idx; + + _IdxWritePtr += 6; + + // Fill bevel + if (bevel) + { + _IdxWritePtr[0] = (ImDrawIdx)outer_idx; + _IdxWritePtr[1] = (ImDrawIdx)outer_idx+1; + _IdxWritePtr[2] = (ImDrawIdx)inner_idx; + _IdxWritePtr += 3; + outer_idx++; + } + + prev_outer_idx = outer_idx; + } + + // Patch first segment + start_idx_ptr[0] = (ImDrawIdx)prev_outer_idx; + start_idx_ptr[3] = (ImDrawIdx)prev_outer_idx; + + // Add indices for fill + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + i); + _IdxWritePtr += 3; + } + + const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); + const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); + IM_ASSERT(idx_used <= idx_count && vtx_used <= vtx_count); + + if (idx_used < idx_count || vtx_used < vtx_count) + PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); +} + +void ImDrawList::AddConvexPolyFilledLegacy(const ImVec2* points, const int points_count, ImU32 col) { if (points_count < 3 || (col & IM_COL32_A_MASK) == 0) return; @@ -1907,6 +2037,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun } } + void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step) { if (radius < 0.5f) @@ -2501,10 +2632,10 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, const ImVec2 inner_uv1(tex_uvs.x + ((0.5f + thickness - stem_offset) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); int base_idx = (int)_VtxCurrentIdx; - IM_POLYLINE_APPEND_VERTEX(0, 0, outer_uv0, col); - IM_POLYLINE_APPEND_VERTEX(0, 0, outer_uv1, col); - IM_POLYLINE_APPEND_VERTEX(0, 0, inner_uv1, col); - IM_POLYLINE_APPEND_VERTEX(0, 0, inner_uv0, col); + IM_APPEND_VTX(0, 0, outer_uv0, col); + IM_APPEND_VTX(0, 0, outer_uv1, col); + IM_APPEND_VTX(0, 0, inner_uv1, col); + IM_APPEND_VTX(0, 0, inner_uv0, col); for (int corner = 0; corner < 4; corner++) { @@ -2520,34 +2651,34 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, for (int i = 0; i < arc_point_count; i++) { const ImVec2 dir = _Data->ArcFastVtx[a]; - IM_POLYLINE_APPEND_VERTEX(center.x - dir.x * rounding, center.y - dir.y * rounding, outer_uv0, col); + IM_APPEND_VTX(center.x - dir.x * rounding, center.y - dir.y * rounding, outer_uv0, col); a = (a + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; } } else { - IM_POLYLINE_APPEND_VERTEX(corner_pos[corner].x, corner_pos[corner].y, outer_uv0, col); + IM_APPEND_VTX(corner_pos[corner].x, corner_pos[corner].y, outer_uv0, col); } const int stem0_idx = (int)_VtxCurrentIdx; - IM_POLYLINE_APPEND_VERTEX(stem.x, stem.y, outer_uv1, col); + IM_APPEND_VTX(stem.x, stem.y, outer_uv1, col); const int stem1_idx = (int)_VtxCurrentIdx; - IM_POLYLINE_APPEND_VERTEX(stem.x, stem.y, inner_uv1, col); + IM_APPEND_VTX(stem.x, stem.y, inner_uv1, col); const int inner_idx = (int)_VtxCurrentIdx; - IM_POLYLINE_APPEND_VERTEX(inner.x, inner.y, inner_uv0, col); + IM_APPEND_VTX(inner.x, inner.y, inner_uv0, col); // Arc if (is_rounded) { for (int i = 0; i < arc_point_count-1; i++) - IM_POLYLINE_APPEND_TRI(stem0_idx, arc_idx + i, arc_idx + i + 1); + IM_APPEND_TRI(stem0_idx, arc_idx + i, arc_idx + i + 1); } // Connect with previous - IM_POLYLINE_APPEND_TRI(base_idx+0, arc_idx, stem0_idx); - IM_POLYLINE_APPEND_TRI(base_idx+0, stem0_idx, base_idx+1); - IM_POLYLINE_APPEND_TRI(base_idx+2, stem1_idx, inner_idx); - IM_POLYLINE_APPEND_TRI(base_idx+2, inner_idx, base_idx+3); + IM_APPEND_TRI(base_idx + 0, arc_idx, stem0_idx); + IM_APPEND_TRI(base_idx + 0, stem0_idx, base_idx + 1); + IM_APPEND_TRI(base_idx + 2, stem1_idx, inner_idx); + IM_APPEND_TRI(base_idx + 2, inner_idx, base_idx + 3); base_idx = stem0_idx - 1; @@ -2862,7 +2993,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c else { PathRect(p_min, p_max, rounding, flags); - PathFillConvex(col); + PathFillConvex(col, ImDrawFlags_MiterOnly); } } @@ -3017,7 +3148,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); } - PathFillConvex(col); + PathFillConvex(col, ImDrawFlags_MiterOnly); } // Guaranteed to honor 'num_segments' @@ -3072,7 +3203,7 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); - PathFillConvex(col); + PathFillConvex(col, ImDrawFlags_MiterOnly); } // Ellipse @@ -3277,7 +3408,7 @@ void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, cons int vert_start_idx = VtxBuffer.Size; PathRect(p_min, p_max, rounding, flags); - PathFillConvex(col); + PathFillConvex(col, ImDrawFlags_MiterOnly); int vert_end_idx = VtxBuffer.Size; ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); @@ -7857,7 +7988,7 @@ void ImGui::RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e); // BR } } - draw_list->PathFillConvex(col); + draw_list->PathFillConvex(col, ImDrawFlags_MiterOnly); } void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding) From ea2e5c79c06fe8a4f87c31307554f00ee924b266 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 27 Apr 2026 08:36:18 +0300 Subject: [PATCH 063/245] DrawList: added square cap rendering. - Added square cap rendering to the DrawPolyline, which can be turned on by ImDrawFlags_SquareCap - Added draw flags to AddBezierCubic() and AddBezierQuadratic() --- imgui.h | 5 +++-- imgui_demo.cpp | 8 +++++--- imgui_draw.cpp | 24 ++++++++++++++++-------- 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/imgui.h b/imgui.h index 0f5edb89a..95718866f 100644 --- a/imgui.h +++ b/imgui.h @@ -3328,6 +3328,7 @@ enum ImDrawFlags_ // Stroke options ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. ImDrawFlags_MiterOnly = 1 << 10, // PathStroke(), AddPolyline(): use miter corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. + ImDrawFlags_SquareCap = 1 << 11, // PathStroke(), AddPolyline(): use square cap line ends. // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (Default) @@ -3424,8 +3425,8 @@ struct ImDrawList IMGUI_API void AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); - IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points) - IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points) + IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0, ImDrawFlags flags = 0); // Cubic Bezier (4 control points) + IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0, ImDrawFlags flags = 0); // Quadratic Bezier (3 control points) // General polygon // - Only simple polygons are supported by filling functions (no self-intersections, no holes). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 14de91638..45eff63c3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10395,6 +10395,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) static bool curve_segments_override = false; static int curve_segments_override_v = 8; static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); + static bool square_caps = false; ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); ImGui::DragFloat("Thickness", &thickness, 0.05f, 0.0f, 32.0f, "%.02f"); ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); @@ -10405,6 +10406,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); ImGui::ColorEdit4("Color", &colf.x); + ImGui::Checkbox("Square caps", &square_caps); static ImDrawFlags flags = ImDrawFlags_None; ImGui::AlignTextToFramePadding(); @@ -10420,6 +10422,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) const ImU32 col = ImColor(colf); const float spacing = 10.0f; const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; + const ImDrawFlags stroke_flags = square_caps ? ImDrawFlags_SquareCap : ImDrawFlags_None; const float rounding = sz / 5.0f; const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; @@ -10444,7 +10447,6 @@ static void ShowExampleAppCustomRendering(bool* p_open) //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); draw_list->AddLineH(x, x + sz, y, col, th, flags); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) draw_list->AddLineV(x, y, y + sz, col, th, flags); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th, flags); x += sz + spacing; draw_list->AddLine(ImVec2(x, y + sz), ImVec2(x, y), col, th, flags); x += spacing; @@ -10456,11 +10458,11 @@ static void ShowExampleAppCustomRendering(bool* p_open) x += sz + spacing; // Quadratic Bezier Curve (3 control points) - draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments); + draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments, stroke_flags); x += sz + spacing; // Cubic Bezier Curve (4 control points) - draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments); + draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments, stroke_flags); x = p.x + 4; y += sz + spacing; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e3ee377db..c6f84a232 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -928,6 +928,8 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, ImVec2* normals, float* len_sqr1 = sqr_lengths[0]; const ImVec2 dir(n1.y, -n1.x); + if (flags & ImDrawFlags_SquareCap) + p1 -= dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. const ImVec2 pa = p1 - dir * half_aa; const ImVec2 pb = p1 + dir * half_aa; @@ -1147,6 +1149,8 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, ImVec2* normals, float* // End cap const ImVec2 dir(n1.y, -n1.x); + if (flags & ImDrawFlags_SquareCap) + p1 += dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. const ImVec2 pa = p1 - dir * half_aa; const ImVec2 pb = p1 + dir * half_aa; @@ -1241,6 +1245,8 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, ImVec2* normals, float* // Start cap const ImVec2 dir(n1.y, -n1.x); + if (flags & ImDrawFlags_SquareCap) + p1 -= dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. const ImVec2 pa = p1 - dir * half_aa; const ImVec2 pb = p1 + dir * half_aa; @@ -1458,6 +1464,8 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, ImVec2* normals, float* // End cap const ImVec2 dir(n1.y, -n1.x); + if (flags & ImDrawFlags_SquareCap) + p1 += dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. const ImVec2 pa = p1 - dir * half_aa; const ImVec2 pb = p1 + dir * half_aa; @@ -1851,7 +1859,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun _VtxWritePtr += points_count; _VtxCurrentIdx += points_count; - unsigned int prev_outer_idx = (unsigned int )-1; // We dont know oueter vert could yet, will need to patch once we're done. + unsigned int prev_outer_idx = 0; // We dont know outer vert could yet, will need to patch once we're done. const float miter_distance_limit = half_aa * IM_POLYLINE_MITER_LIMIT; const float miter_distance_limit_sqr = miter_distance_limit * miter_distance_limit; @@ -2389,7 +2397,7 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; - AddPolyline(points, 2, col, thickness); + AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); return; } @@ -2423,7 +2431,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness); + AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); return; } @@ -2454,7 +2462,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(x + 0.5f, max_y + 0.5f), ImVec2(x + 0.5f, min_y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness); + AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); return; } @@ -3302,25 +3310,25 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im } // Cubic Bezier takes 4 controls points -void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments) +void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(p1); PathBezierCubicCurveTo(p2, p3, p4, num_segments); - PathStroke(col, thickness); + PathStroke(col, thickness, flags); } // Quadratic Bezier takes 3 controls points -void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments) +void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(p1); PathBezierQuadraticCurveTo(p2, p3, num_segments); - PathStroke(col, thickness); + PathStroke(col, thickness, flags); } void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) From d1d2f5aead3f121622bf624846c4c5e3eb0a668a Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 27 Apr 2026 15:00:04 +0300 Subject: [PATCH 064/245] DrawList: use dedicated larger texture for fractional thickness lines. --- imgui.h | 6 +++-- imgui_draw.cpp | 69 +++++++++++++++++++++++++++++++++++++++--------- imgui_internal.h | 4 ++- 3 files changed, 63 insertions(+), 16 deletions(-) diff --git a/imgui.h b/imgui.h index 95718866f..74feafc8b 100644 --- a/imgui.h +++ b/imgui.h @@ -3205,6 +3205,7 @@ struct ImGuiSelectionExternalStorage // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX #define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) +#define IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX (128) #endif #ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX @@ -3534,8 +3535,8 @@ struct ImDrawList IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddPolylineThin(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs); - IMGUI_API void _AddPolylineThick(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags); + IMGUI_API void _AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs); + IMGUI_API void _AddPolylineFractThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); }; @@ -3899,6 +3900,7 @@ struct ImFontAtlas ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + ImVec4 TexUvLineFract; // UVs for fraction thickness baked anti-aliased lines ImVec4 TexUvCornerFills[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX]; // UVs for baked anti-aliased corners ImVec4 TexUvCornerStrokes[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners int TexNextUniqueID; // Next value to be stored in TexData->UniqueID diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c6f84a232..818bd5b0c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -871,7 +871,7 @@ static void CalcSegmentNormals(const ImVec2* points, const int points_count, ImV } } -void ImDrawList::_AddPolylineThin(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs) +void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs) { const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; @@ -1184,7 +1184,7 @@ void ImDrawList::_AddPolylineThin(const ImVec2* points, ImVec2* normals, float* PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } -void ImDrawList::_AddPolylineThick(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::_AddPolylineFractThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; @@ -1193,7 +1193,7 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, ImVec2* normals, float* // TODO: we can expand this by having one very long texture strip for the lines, // or if place black 2x2 pixel next to the while pixel, and use texture clamping (that thickness would expand out of the texture). - const float max_width = (IM_DRAWLIST_TEX_LINES_WIDTH_MAX-1) * _FringeScale * 2.0f; + const float max_width = IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX * _FringeScale * 2.0f; thickness = ImMin(thickness, max_width); thickness += _FringeScale; // Place half of AA fringe each side of the line. @@ -1229,7 +1229,7 @@ void ImDrawList::_AddPolylineThick(const ImVec2* points, ImVec2* normals, float* ImVec2 n1; float len_sqr1; - const ImVec4 tex_uvs = _Data->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX]; + const ImVec4 tex_uvs = _Data->TexUvLineFract; const ImVec2 uv_out(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); const ImVec2 uv_in(tex_uvs.x + ((half_thickness + 0.5f) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); @@ -1526,22 +1526,22 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // TODO: support splitting very long lines to multiple draw calls. // We can use cheaper rendering if the thickness is integer size. - const int int_thickness = (int)screen_thickness; - const bool can_use_thin = ImAbs(screen_thickness - (float)int_thickness) < 0.01f && (int_thickness >= 1 && int_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX); + const int truncated_thickness = (int)screen_thickness; + const bool is_int_thickness = ImAbs(screen_thickness - (float)truncated_thickness) < 0.01f && (truncated_thickness >= 1 && truncated_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX); _Data->TempBuffer.reserve_discard(points_count * 2); ImVec2* normals = _Data->TempBuffer.Data; float* sqr_lengths = (float*)(normals + points_count); CalcSegmentNormals(points, points_count, normals, sqr_lengths, (flags & ImDrawFlags_Closed) != 0); - if (can_use_thin) + if (is_int_thickness) { - const ImVec4 tex_uvs = _Data->TexUvLines[int_thickness]; - _AddPolylineThin(points, normals, sqr_lengths, points_count, col, (float)int_thickness * _FringeScale, flags, tex_uvs); + const ImVec4 tex_uvs = _Data->TexUvLines[truncated_thickness]; + _AddPolylineIntThickness(points, normals, sqr_lengths, points_count, col, (float)truncated_thickness * _FringeScale, flags, tex_uvs); } else { - _AddPolylineThick(points, normals, sqr_lengths, points_count, col, thickness, flags); + _AddPolylineFractThickness(points, normals, sqr_lengths, points_count, col, thickness, flags); } } @@ -1842,7 +1842,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun float dx = p1.x - p0.x; float dy = p1.y - p0.y; float d2 = dx*dx + dy*dy; - if (d2 > 0.f) + if (d2 > 0.0f) { float inv_len = ImRsqrt(d2); dx *= inv_len; @@ -1873,7 +1873,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun // theta is the angle between two segments const float cos_theta = n0.x * n1.x + n0.y * n1.y; // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - float miter_scale_factor = ImMin(1000.f, (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? (half_aa / (1.0f + cos_theta)) : FLT_MAX); // avoid division by zero + float miter_scale_factor = ImMin(1000.0f, (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? (half_aa / (1.0f + cos_theta)) : FLT_MAX); // avoid division by zero float dm_x = (n0.x + n1.x) * miter_scale_factor; float dm_y = (n0.y + n1.y) * miter_scale_factor; @@ -2606,6 +2606,10 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c // The stroke is positioned inside the rectangle. void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { + // Note: this is smaller than in AddPolyline(), since the stem offset can be biased all the way to one side. + const float max_width = IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX * _FringeScale; + thickness = ImMin(thickness, max_width); + thickness += _FringeScale; // Adjust the rounding to be the outside radius. @@ -2633,7 +2637,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, const float stem_offset = thickness - ImMax(thickness - rounding, _FringeScale); - const ImVec4 tex_uvs = _Data->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX]; // TODO: max uv + const ImVec4 tex_uvs = _Data->TexUvLineFract; // TODO: max uv const ImVec2 outer_uv0(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); const ImVec2 outer_uv1(tex_uvs.x + ((0.5f + stem_offset) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); const ImVec2 inner_uv0(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); @@ -5470,6 +5474,44 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } + + // Single larger line for fraction width textured lines. + // Alternative solution could be to fix while and black pixel next to the texture border + // and use the texture clamping to expand the opaque pixel. + // : + // [*][ ] + // : + // <-- width would expand out of the texture expanding the while pixel to as far as needed. + add_and_draw = atlas->GetCustomRect(builder->PackIdLineFractTexData, &r) == false; + if (add_and_draw) + { + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX + 1, 1); + builder->PackIdLineFractTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); + IM_ASSERT(builder->PackIdLineFractTexData != ImFontAtlasRectId_Invalid); + } + + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + // Write each slice + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) + { + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y); + *write_ptr++ = 0x00; + for (int i = 0; i < IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX; i++) + *write_ptr++ = 0xFF; + } + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y); + *write_ptr++ = IM_COL32(255, 255, 255, 0); + for (int i = 0; i < IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX; i++) + *write_ptr++ = IM_COL32_WHITE; + } + + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)r.x, (float)r.y) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)r.x + 1.0f + IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX, (float)r.y) * atlas->TexUvScale; + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvLineFract = ImVec4(uv0.x, half_v, uv1.x, half_v); } //----------------------------------------------------------------------------------------------------------------------------- @@ -5843,6 +5885,7 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; shared_data->TexUvLines = atlas->TexUvLines; + shared_data->TexUvLineFract = atlas->TexUvLineFract; shared_data->TexUvCornerFills = atlas->TexUvCornerFills; shared_data->TexUvCornerStrokes = atlas->TexUvCornerStrokes; } diff --git a/imgui_internal.h b/imgui_internal.h index 9db27ab74..547f4ddc4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -921,6 +921,7 @@ struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) + ImVec4 TexUvLineFract; // UV of fractional anti-aliased lines in the atlas (== FontAtlas->TexUvLineFract) const ImVec4* TexUvCornerFills; // UV of rounded corner (== FontAtlas->TexUvCornerFills) const ImVec4* TexUvCornerStrokes; ImFontAtlas* FontAtlas; // Current font atlas @@ -4058,9 +4059,10 @@ struct ImFontAtlasBuilder // Custom rectangle identifiers ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; + ImFontAtlasRectId PackIdLineFractTexData; ImFontAtlasRectId PackIdCornersTexData; - ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdCornersTexData = -1; } + ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } }; IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); From c2e029fb98356a04ce1b79236e815961e9305127 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 7 May 2026 09:25:46 +0300 Subject: [PATCH 065/245] DrawList: added stroke position to path rendering. - added generic stroke position to all path rendering - removed stroke folding in favor of limiting the miter width (simplifies the geometry cases) - removed fractional stroke rendering in favor of using the integer sized rendering for everything - the rationale is that the in-between sizes are a bit blurry anyways, and the error we get from scaling is visually acceptable - added stroke position option for the demo - updated the degenerate shape handling - remove AddLine() stroke pos handling - removed up commented out code. --- imgui.h | 9 +- imgui_demo.cpp | 12 +- imgui_draw.cpp | 922 ++++++++++++++----------------------------------- 3 files changed, 260 insertions(+), 683 deletions(-) diff --git a/imgui.h b/imgui.h index 74feafc8b..6b777437a 100644 --- a/imgui.h +++ b/imgui.h @@ -3414,9 +3414,9 @@ struct ImDrawList IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, float thickness = 1.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); - IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); - IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f, ImDrawFlags = 0); IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); @@ -3454,7 +3454,7 @@ struct ImDrawList inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } inline void PathFillConvex(ImU32 col, ImDrawFlags flags = 0) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, flags); _Path.Size = 0; } inline void PathFillConcave(ImU32 col) { AddConcavePolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } - inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0) { AddPolyline(_Path.Data, _Path.Size, col, thickness, flags); _Path.Size = 0; } + inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = ImDrawFlags_StrokeCenter) { AddPolyline(_Path.Data, _Path.Size, col, thickness, flags); _Path.Size = 0; } IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments = 0); // Ellipse @@ -3535,8 +3535,7 @@ struct ImDrawList IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs); - IMGUI_API void _AddPolylineFractThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags); + IMGUI_API void _AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs, float fringe); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 45eff63c3..392609ce3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10397,7 +10397,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); static bool square_caps = false; ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); - ImGui::DragFloat("Thickness", &thickness, 0.05f, 0.0f, 32.0f, "%.02f"); + ImGui::DragFloat("Thickness", &thickness, 0.1f, 0.0f, 30.0f, "%.02f"); ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); @@ -10422,7 +10422,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) const ImU32 col = ImColor(colf); const float spacing = 10.0f; const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; - const ImDrawFlags stroke_flags = square_caps ? ImDrawFlags_SquareCap : ImDrawFlags_None; + const ImDrawFlags cap_flags = square_caps ? ImDrawFlags_SquareCap : ImDrawFlags_None; const float rounding = sz / 5.0f; const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; @@ -10450,19 +10450,19 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th, flags); x += sz + spacing; draw_list->AddLine(ImVec2(x, y + sz), ImVec2(x, y), col, th, flags); x += spacing; - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th, flags); x += sz + spacing; // Diagonal line + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th, flags | cap_flags); x += sz + spacing; // Diagonal line // Path draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f, 3.141592f * -0.5f); - draw_list->PathStroke(col, th, flags); + draw_list->PathStroke(col, th, flags | cap_flags); x += sz + spacing; // Quadratic Bezier Curve (3 control points) - draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments, stroke_flags); + draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments, flags | cap_flags); x += sz + spacing; // Cubic Bezier Curve (4 control points) - draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments, stroke_flags); + draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments, flags | cap_flags); x = p.x + 4; y += sz + spacing; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 818bd5b0c..3d64cb7b7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -841,53 +841,31 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c #define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) #define IM_POLYLINE_MITER_LIMIT (4.0f) -static void CalcSegmentNormals(const ImVec2* points, const int points_count, ImVec2* normals, float* sqr_lengths, bool closed) +void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs, float fringe) { - // Calculate normals for each line segment - for (int i = 0; i < points_count - 1; i++) - { - float dx = points[i+1].x - points[i].x; - float dy = points[i+1].y - points[i].y; - const float d2 = dx*dx + dy*dy; - const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; - normals[i].x = -dy * inv_len; - normals[i].y = dx * inv_len; - sqr_lengths[i] = d2; - } - if (closed) - { - const float dx = points[0].x - points[points_count - 1].x; - const float dy = points[0].y - points[points_count - 1].y; - const float d2 = dx*dx + dy*dy; - const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; - normals[points_count - 1].x = -dy * inv_len; - normals[points_count - 1].y = dx * inv_len; - sqr_lengths[points_count - 1] = d2; - } - else - { - normals[points_count - 1] = normals[points_count - 2]; - sqr_lengths[points_count - 1] = 0.0f; - } -} - -void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs) -{ - const bool closed = (flags & ImDrawFlags_Closed) != 0; - const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - thickness += _FringeScale; - const float half_thickness = thickness * 0.5f; - const float miter_distance_limit = half_thickness * IM_POLYLINE_MITER_LIMIT; - const float miter_distance_limit_sqr = miter_distance_limit * miter_distance_limit; - const float half_aa = _FringeScale * 0.5f; + const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + const bool closed = (flags & ImDrawFlags_Closed) != 0; + const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; + const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; + + float thickness0 = (thickness + fringe) * 0.5f; + float thickness1 = thickness0; + if (stroke_pos == ImDrawFlags_StrokeOutside) + { + thickness0 = thickness + fringe * 0.5f; + thickness1 = fringe * 0.5f; + } + else if (stroke_pos == ImDrawFlags_StrokeInside) + { + thickness0 = fringe * 0.5f; + thickness1 = thickness + fringe * 0.5f; + } - // TODO: Each point will generate 2-7 vertices. The worst case happens really rarely. This can be issue with large polylines and 16it indices. - // One option could be to calculate the miter values and overl & bevel flags before, then alloc, and finally commit. int idx_count = 0; int vtx_count = 0; - const int max_verts_per_point = miters_only ? 2 : 7; + const int max_verts_per_point = miters_only ? 2 : 4; const int max_tris_per_point = miters_only ? 2 : 5; if (closed) { @@ -911,10 +889,14 @@ void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, ImVec2 n1; float len_sqr1; - const float half_texel = (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x; + const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; const ImVec2 uv0(tex_uvs.x + half_texel, tex_uvs.y); const ImVec2 uv1(tex_uvs.z - half_texel, tex_uvs.y); - const ImVec2 uv2((uv0.x+uv1.x)*0.5f, tex_uvs.y); + const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. + const ImVec2 uv2(uv0.x + (uv1.x - uv0.x) * ratio, tex_uvs.y); + + const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. + const float half_thickness = thickness * 0.5f; int point_idx = 0; int point_end = points_count; @@ -929,17 +911,17 @@ void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, const ImVec2 dir(n1.y, -n1.x); if (flags & ImDrawFlags_SquareCap) - p1 -= dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. + p1 -= dir * half_thickness; const ImVec2 pa = p1 - dir * half_aa; const ImVec2 pb = p1 + dir * half_aa; base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * half_thickness , pa.y - n1.y * half_thickness , uv0, col_trans); - IM_APPEND_VTX(pa.x + n1.x * half_thickness , pa.y + n1.y * half_thickness , uv1, col_trans); + IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col_trans); + IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col_trans); int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pb.x - n1.x * half_thickness , pb.y - n1.y * half_thickness , uv0, col); - IM_APPEND_VTX(pb.x + n1.x * half_thickness , pb.y + n1.y * half_thickness , uv1, col); + IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col); + IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1 , uv1, col); // AA cap IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); @@ -959,95 +941,90 @@ void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, IM_APPEND_VTX(0, 0, uv1, col); } - while (point_idx < point_end) + if (miters_only) { - ImVec2 n0 = n1; - float len_sqr0 = len_sqr1; - p1 = points[point_idx]; - n1 = normals[point_idx]; - len_sqr1 = sqr_lengths[point_idx]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float miter_scale_factor = (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? half_thickness / (1.0f + cos_theta) : FLT_MAX; // avoid division by zero - const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; - const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; - const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - - const bool overlap = !miters_only && ((len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT)); - const bool bevel = !miters_only && (miter_distance_sqr > miter_distance_limit_sqr); - - if (bevel) + while (point_idx < point_end) { - // Clipped bevel + ImVec2 n0 = n1; + p1 = points[point_idx]; + n1 = normals[point_idx]; + + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float miter_scale_factor = ImMin(1000.0f, (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? 1.0f / (1.0f + cos_theta) : FLT_MAX); // avoid division by zero + const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; + const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; + + // Miter + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 + IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 3 + + // Connect prev to next + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + + base_idx = next_base_idx; + + point_idx++; + } + } + else + { + while (point_idx < point_end) + { + ImVec2 n0 = n1; + float len_sqr0 = len_sqr1; + p1 = points[point_idx]; + n1 = normals[point_idx]; + len_sqr1 = sqr_lengths[point_idx]; + + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; const float sin_theta = n0.y * n1.x - n0.x * n1.y; - float bevel_normal_x = n0.x + n1.x; - float bevel_normal_y = n0.y + n1.y; - IM_NORMALIZE2F_OVER_ZERO(bevel_normal_x, bevel_normal_y); - const float signed_miter_offset = sin_theta < 0.0f ? half_thickness : -half_thickness; - const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.0f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); - const float pt_x = p1.x - bevel_normal_x * signed_miter_offset; - const float pt_y = p1.y - bevel_normal_y * signed_miter_offset; - const float sd_x = bevel_normal_y * side_offset; - const float sd_y = -bevel_normal_x * side_offset; + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float miter_scale_factor = (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? 1.0f / (1.0f + cos_theta) : FLT_MAX; // avoid division by zero - if (overlap) + float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; + float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; + const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; + + if (miter_distance_sqr > miter_distance_limit_sqr) { - // Dislocated bevel. - if (sin_theta < 0.0f) - { - IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 - IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); // 4 - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv0, col); // 5 - IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 6 - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 7 - IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 8 + // Clipped bevel - // Connect prev to next - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - // Bevel tris - IM_APPEND_TRI(base_idx + 6, base_idx + 2, base_idx + 4); - IM_APPEND_TRI(base_idx + 6, base_idx + 4, base_idx + 5); - IM_APPEND_TRI(base_idx + 6, base_idx + 5, base_idx + 7); - base_idx = next_base_idx; - } - else + // Limit the inner miter offset to avoid overshooting. + const float ref_thickness = (sin_theta < 0.0f) ? thickness1 : thickness0; + const float ref_thickness_sqr = ref_thickness * ref_thickness; + const float limit_sqr = ImMax(ImMax(len_sqr0, len_sqr1), ref_thickness_sqr); + const float ref_miter_dist_sqr = miter_distance_sqr * ref_thickness_sqr; + if (ref_miter_dist_sqr > limit_sqr) { - IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 - IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv1, col); // 4 - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv1, col); // 5 - IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 6 - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 7 - IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 8 - - // Connect prev to next - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - // Bevel - IM_APPEND_TRI(base_idx + 6, base_idx + 7, base_idx + 5); - IM_APPEND_TRI(base_idx + 6, base_idx + 5, base_idx + 4); - IM_APPEND_TRI(base_idx + 6, base_idx + 4, base_idx + 3); - base_idx = next_base_idx; + const float scale = ImSqrt(limit_sqr / ref_miter_dist_sqr); + miter_offset_x *= scale; + miter_offset_y *= scale; } - } - else - { + + float bn_x = n0.x + n1.x; + float bn_y = n0.y + n1.y; + IM_NORMALIZE2F_OVER_ZERO(bn_x, bn_y); + + const float side_offset = ((n0.x * bn_x + n0.y * bn_y) - 1.0f) / (n0.y * bn_x - n0.x * bn_y); + const float sd_x = bn_y * side_offset; + const float sd_y = -bn_x * side_offset; + // Bevel if (sin_theta < 0.0f) { - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv0, col); // 2 + IM_APPEND_VTX(p1.x - (bn_x + sd_x) * thickness0, p1.y - (bn_y + sd_y) * thickness0, uv0, col); // 2 + // TODO: calc uv2 correctly. IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv0, col); // 4 - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); // 5 + IM_APPEND_VTX(p1.x - (bn_x - sd_x) * thickness0, p1.y - (bn_y - sd_y) * thickness0, uv0, col); // 4 + IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 5 // Connect prev to next IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 5); @@ -1060,11 +1037,12 @@ void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, } else { - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv1, col); // 2 + IM_APPEND_VTX(p1.x + (bn_x + sd_x) * thickness1, p1.y + (bn_y + sd_y) * thickness1, uv1, col); // 2 + // TODO: calc uv2 correctly. IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); // 4 - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv1, col); // 5 + IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 4 + IM_APPEND_VTX(p1.x + (bn_x - sd_x) * thickness1, p1.y + (bn_y - sd_y) * thickness1, uv1, col); // 5 // Connect prev to next IM_APPEND_TRI(base_idx + 0, base_idx + 4, base_idx + 2); @@ -1076,69 +1054,22 @@ void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, base_idx = next_base_idx; } } - } - else - { - if (overlap) - { - // Dislocated Miter - const float sin_theta = n0.y * n1.x - n0.x * n1.y; - if (sin_theta < 0.0f) - { - - IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 - IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 - IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); // 4 - IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 5 - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 6 - IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 7 - - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); - // Miter - IM_APPEND_TRI(base_idx+5, base_idx+2, base_idx+4); - IM_APPEND_TRI(base_idx+5, base_idx+4, base_idx+6); - - base_idx = next_base_idx; - } - else - { - IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv0, col); // 2 - IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv1, col); // 3 - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); // 4 - IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 5 - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv0, col); // 6 - IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv1, col); // 7 - - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); - // Miter - IM_APPEND_TRI(base_idx+5, base_idx+4, base_idx+3); - IM_APPEND_TRI(base_idx+5, base_idx+7, base_idx+4); - - base_idx = next_base_idx; - } - } else { // Miter const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv0, col); // 2 - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv1, col); // 3 + IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 + IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 3 // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); base_idx = next_base_idx; } - } - point_idx++; + point_idx++; + } } // End cap @@ -1150,16 +1081,16 @@ void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, // End cap const ImVec2 dir(n1.y, -n1.x); if (flags & ImDrawFlags_SquareCap) - p1 += dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. + p1 += dir * half_thickness; const ImVec2 pa = p1 - dir * half_aa; const ImVec2 pb = p1 + dir * half_aa; int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * half_thickness, pa.y - n1.y * half_thickness, uv0, col); - IM_APPEND_VTX(pa.x + n1.x * half_thickness, pa.y + n1.y * half_thickness, uv1, col); + IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col); + IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col); - IM_APPEND_VTX(pb.x - n1.x * half_thickness, pb.y - n1.y * half_thickness, uv0, col_trans); - IM_APPEND_VTX(pb.x + n1.x * half_thickness, pb.y + n1.y * half_thickness, uv1, col_trans); + IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col_trans); + IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1, uv1, col_trans); // Connect IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); @@ -1184,328 +1115,6 @@ void ImDrawList::_AddPolylineIntThickness(const ImVec2* points, ImVec2* normals, PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } -void ImDrawList::_AddPolylineFractThickness(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) -{ - const bool closed = (flags & ImDrawFlags_Closed) != 0; - const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; - - const ImU32 col_trans = col & ~IM_COL32_A_MASK; - - // TODO: we can expand this by having one very long texture strip for the lines, - // or if place black 2x2 pixel next to the while pixel, and use texture clamping (that thickness would expand out of the texture). - const float max_width = IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX * _FringeScale * 2.0f; - thickness = ImMin(thickness, max_width); - - thickness += _FringeScale; // Place half of AA fringe each side of the line. - const float half_thickness = thickness * 0.5f; - const float miter_distance_limit = half_thickness * IM_POLYLINE_MITER_LIMIT; - const float miter_distance_limit_sqr = miter_distance_limit * miter_distance_limit; - const float half_aa = _FringeScale * 0.5f; - - int idx_count = 0; - int vtx_count = 0; - const int max_verts_per_point = miters_only ? 3 : 5; - const int max_tris_per_point = miters_only ? 4 : 5; - if (closed) - { - vtx_count = /*body*/points_count * max_verts_per_point + /*closing*/3; - idx_count = (/*body*/points_count * max_tris_per_point + /*closing*/4) * 3; - } - else - { - // Body + caps - vtx_count = /*body*/(points_count - 2) * max_verts_per_point + /*caps*/(6 * 2); - idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/4 + /*caps*/(4 * 2)) * 3; - } - - PrimReserve(idx_count, vtx_count); - - ImDrawVert* start_vtx_ptr = _VtxWritePtr; - ImDrawIdx* start_idx_ptr = _IdxWritePtr; - - int base_idx = (int)_VtxCurrentIdx; - - ImVec2 p1; - ImVec2 n1; - float len_sqr1; - - const ImVec4 tex_uvs = _Data->TexUvLineFract; - const ImVec2 uv_out(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); - const ImVec2 uv_in(tex_uvs.x + ((half_thickness + 0.5f) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); - - int point_idx = 0; - int point_end = points_count; - if (!closed) - { - point_idx++; - point_end--; - p1 = points[0]; - n1 = normals[0]; - len_sqr1 = sqr_lengths[0]; - - // Start cap - const ImVec2 dir(n1.y, -n1.x); - if (flags & ImDrawFlags_SquareCap) - p1 -= dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. - const ImVec2 pa = p1 - dir * half_aa; - const ImVec2 pb = p1 + dir * half_aa; - - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * half_thickness , pa.y - n1.y * half_thickness , uv_out, col_trans); - IM_APPEND_VTX(pa.x, pa.y, uv_in, col_trans); - IM_APPEND_VTX(pa.x + n1.x * half_thickness , pa.y + n1.y * half_thickness , uv_out, col_trans); - - int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pb.x - n1.x * half_thickness , pb.y - n1.y * half_thickness , uv_out, col); - IM_APPEND_VTX(pb.x, pb.y, uv_in, col); - IM_APPEND_VTX(pb.x + n1.x * half_thickness , pb.y + n1.y * half_thickness , uv_out, col); - - // AA cap - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); - IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); - base_idx = next_base_idx; - } - else - { - p1 = points[points_count-1]; - n1 = normals[points_count-1]; - len_sqr1 = sqr_lengths[points_count-1]; - - // This will be filled later, allocate space. - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(0, 0, uv_out, col); - IM_APPEND_VTX(0, 0, uv_in, col); - IM_APPEND_VTX(0, 0, uv_out, col); - } - - while (point_idx < point_end) - { - ImVec2 n0 = n1; - float len_sqr0 = len_sqr1; - p1 = points[point_idx]; - n1 = normals[point_idx]; - len_sqr1 = sqr_lengths[point_idx]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float miter_scale_factor = (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? half_thickness / (1.0f + cos_theta) : FLT_MAX; // avoid division by zero - const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; - const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; - const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - - const bool overlap = !miters_only && ((len_sqr0 < miter_distance_sqr) || (len_sqr1 < miter_distance_sqr) || (cos_theta <= IM_POLYLINE_MITER_ANGLE_LIMIT)); - const bool bevel = !miters_only && (miter_distance_sqr > miter_distance_limit_sqr); - - if (bevel) - { - IM_ASSERT(!miters_only); - // Clipped bevel - const float sin_theta = n0.y * n1.x - n0.x * n1.y; - float bevel_normal_x = n0.x + n1.x; - float bevel_normal_y = n0.y + n1.y; - IM_NORMALIZE2F_OVER_ZERO(bevel_normal_x, bevel_normal_y); - - const float signed_miter_offset = sin_theta < 0.0f ? half_thickness : -half_thickness; - const float side_offset = half_thickness * ((n0.x * bevel_normal_x + n0.y * bevel_normal_y) - 1.0f) / (n0.y * bevel_normal_x - n0.x * bevel_normal_y); - const float pt_x = p1.x - bevel_normal_x * signed_miter_offset; - const float pt_y = p1.y - bevel_normal_y * signed_miter_offset; - const float sd_x = bevel_normal_y * side_offset; - const float sd_y = -bevel_normal_x * side_offset; - - if (overlap) - { - // Dislocated bevel. - if (sin_theta < 0.0f) - { - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); - IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv_out, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); - IM_APPEND_VTX(p1.x, p1.y, uv_in, col); - IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv_out, col); - - // Bevel tri - IM_APPEND_TRI(base_idx+3, base_idx+5, base_idx+6); - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+6); - IM_APPEND_TRI(base_idx+0, base_idx+6, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+4); - IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+2); - base_idx = next_base_idx; - } - else - { - IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv_out, col); - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv_out, col); - IM_APPEND_VTX(p1.x, p1.y, uv_in, col); - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); - - // Bevel tri - IM_APPEND_TRI(base_idx+6, base_idx+7, base_idx+4); - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+6); - IM_APPEND_TRI(base_idx+0, base_idx+6, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+4); - IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+2); - base_idx = next_base_idx; - } - } - else - { - // Bevel - if (sin_theta < 0.0f) - { - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); - IM_APPEND_VTX(p1.x, p1.y, uv_in, col); - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv_out, col); - - // Bevel tri - IM_APPEND_TRI(base_idx+3, base_idx+4, base_idx+5); - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+5); - IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+6); - IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+2); - base_idx = next_base_idx; - } - else - { - IM_APPEND_VTX(pt_x + sd_x, pt_y + sd_y, uv_out, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv_out, col); - IM_APPEND_VTX(p1.x, p1.y, uv_in, col); - IM_APPEND_VTX(pt_x - sd_x, pt_y - sd_y, uv_out, col); - - // Bevel tri - IM_APPEND_TRI(base_idx+5, base_idx+6, base_idx+3); - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+5); - IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+3); - IM_APPEND_TRI(base_idx+1, base_idx+3, base_idx+2); - base_idx = next_base_idx; - } - } - } - else - { - if (overlap) - { - IM_ASSERT(!miters_only); - // Dislocated miter - const float sin_theta = n0.y * n1.x - n0.x * n1.y; - if (sin_theta < 0.0f) - { - IM_APPEND_VTX(p1.x + n0.x * half_thickness, p1.y + n0.y * half_thickness, uv_out, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv_out, col); - IM_APPEND_VTX(p1.x, p1.y, uv_in, col); - IM_APPEND_VTX(p1.x + n1.x * half_thickness, p1.y + n1.y * half_thickness, uv_out, col); - - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+5); - IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+3); - IM_APPEND_TRI(base_idx+1, base_idx+3, base_idx+2); - - base_idx = next_base_idx; - } - else - { - IM_APPEND_VTX(p1.x - n0.x * half_thickness, p1.y - n0.y * half_thickness, uv_out, col); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - n1.x * half_thickness, p1.y - n1.y * half_thickness, uv_out, col); - IM_APPEND_VTX(p1.x, p1.y, uv_in, col); - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv_out, col); - - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+5); - IM_APPEND_TRI(base_idx+0, base_idx+5, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+6); - IM_APPEND_TRI(base_idx+1, base_idx+6, base_idx+2); - - base_idx = next_base_idx; - } - } - else - { - // Miter - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x, p1.y - miter_offset_y, uv_out, col); - IM_APPEND_VTX(p1.x, p1.y, uv_in, col); - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv_out, col); - - // Connect prev to next - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); - IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); - - base_idx = next_base_idx; - } - } - - point_idx++; - } - - // End cap - if (!closed) - { - p1 = points[points_count-1]; - n1 = normals[points_count-1]; - - // End cap - const ImVec2 dir(n1.y, -n1.x); - if (flags & ImDrawFlags_SquareCap) - p1 += dir * (half_thickness - half_aa); // At this point half_thickness has half fringe width baked in. - const ImVec2 pa = p1 - dir * half_aa; - const ImVec2 pb = p1 + dir * half_aa; - - int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * half_thickness, pa.y - n1.y * half_thickness, uv_out, col); - IM_APPEND_VTX(pa.x, pa.y, uv_in, col); - IM_APPEND_VTX(pa.x + n1.x * half_thickness, pa.y + n1.y * half_thickness, uv_out, col); - - IM_APPEND_VTX(pb.x - n1.x * half_thickness, pb.y - n1.y * half_thickness, uv_out, col_trans); - IM_APPEND_VTX(pb.x, pb.y, uv_in, col_trans); - IM_APPEND_VTX(pb.x + n1.x * half_thickness, pb.y + n1.y * half_thickness, uv_out, col_trans); - - // Connect - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); - IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); - base_idx = next_base_idx; - - // AA cap - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+4); - IM_APPEND_TRI(base_idx+0, base_idx+4, base_idx+1); - IM_APPEND_TRI(base_idx+1, base_idx+4, base_idx+5); - IM_APPEND_TRI(base_idx+1, base_idx+5, base_idx+2); - } - else - { - // Connect the path. - start_vtx_ptr[0] = VtxBuffer.Data[base_idx+0]; - start_vtx_ptr[1] = VtxBuffer.Data[base_idx+1]; - start_vtx_ptr[2] = VtxBuffer.Data[base_idx+2]; - } - - // Restore unused memory - const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); - const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); - IM_ASSERT(vtx_used <= vtx_count && idx_used <= idx_count); - PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); -} - void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) @@ -1522,27 +1131,46 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 thickness = _FringeScale; } - // TODO: square vs miter cap // TODO: support splitting very long lines to multiple draw calls. - // We can use cheaper rendering if the thickness is integer size. - const int truncated_thickness = (int)screen_thickness; - const bool is_int_thickness = ImAbs(screen_thickness - (float)truncated_thickness) < 0.01f && (truncated_thickness >= 1 && truncated_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX); - + // Allocate data for temp buffers _Data->TempBuffer.reserve_discard(points_count * 2); ImVec2* normals = _Data->TempBuffer.Data; float* sqr_lengths = (float*)(normals + points_count); - CalcSegmentNormals(points, points_count, normals, sqr_lengths, (flags & ImDrawFlags_Closed) != 0); - if (is_int_thickness) + // Calculate normals for each line segment + for (int i = 0; i < points_count - 1; i++) { - const ImVec4 tex_uvs = _Data->TexUvLines[truncated_thickness]; - _AddPolylineIntThickness(points, normals, sqr_lengths, points_count, col, (float)truncated_thickness * _FringeScale, flags, tex_uvs); + float dx = points[i + 1].x - points[i].x; + float dy = points[i + 1].y - points[i].y; + const float d2 = dx * dx + dy * dy; + const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; TODO: ImRsqrt is not accurate enough. + normals[i].x = -dy * inv_len; + normals[i].y = dx * inv_len; + sqr_lengths[i] = d2; + } + if ((flags & ImDrawFlags_Closed) != 0) + { + const float dx = points[0].x - points[points_count - 1].x; + const float dy = points[0].y - points[points_count - 1].y; + const float d2 = dx * dx + dy * dy; + const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; TODO: ImRsqrt is not accurate enough. + normals[points_count - 1].x = -dy * inv_len; + normals[points_count - 1].y = dx * inv_len; + sqr_lengths[points_count - 1] = d2; } else { - _AddPolylineFractThickness(points, normals, sqr_lengths, points_count, col, thickness, flags); + normals[points_count - 1] = normals[points_count - 2]; + sqr_lengths[points_count - 1] = 0.0f; } + + // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. + const int texture_idx = ImClamp((int)(screen_thickness + 0.95f), 1, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + const float fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. + const ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; + + _AddPolyline(points, normals, sqr_lengths, points_count, col, thickness, flags, tex_uvs, fringe); } void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) @@ -1884,14 +1512,16 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun const float miter_distance_sqr = dm_x * dm_x + dm_y * dm_y; bevel = miter_distance_sqr > miter_distance_limit_sqr; - const float segment_limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); - const bool overshoot = miter_distance_sqr > segment_limit_sqr; - if (overshoot) + if (bevel) { - // Make sure the miter stays within the polygon bounds. - const float scale = ImSqrt(segment_limit_sqr / miter_distance_sqr); - dm_x *= scale; - dm_y *= scale; + // Limit inner bevel so that it is does not shoot out outside the polygon. + const float segment_limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); + if (miter_distance_sqr > segment_limit_sqr) + { + const float scale = ImSqrt(segment_limit_sqr / miter_distance_sqr); + dm_x *= scale; + dm_y *= scale; + } } } @@ -2393,32 +2023,14 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th if ((col & IM_COL32_A_MASK) == 0) return; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); // WIP: only Legacy is used. - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (g_LEGACY_STROKES) { const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); return; } - ImVec2 off(0, 0); - if (stroke_pos != ImDrawFlags_StrokeCenter) - { - // FIXME: this should be removed when the generic PathStroke() stroke pos is merged. - float nx = -(p1.y - p2.y); - float ny = p1.x - p2.x; - IM_NORMALIZE2F_OVER_ZERO(nx, ny); - float offset = 0.0f; - if (stroke_pos == ImDrawFlags_StrokeInside) - offset = -thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - offset = -(thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale)); - else if (stroke_pos == ImDrawFlags_StrokeOutside) - offset = thickness * 0.5f; - off.x = nx * offset; - off.y = ny * offset; - } - const ImVec2 points[2] = { p1 + off, p2 + off }; + const ImVec2 points[2] = { p1, p2 }; AddPolyline(points, 2, col, thickness, flags); } @@ -2612,9 +2224,6 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, thickness += _FringeScale; - // Adjust the rounding to be the outside radius. - rounding += thickness * 0.5f; - const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(rounding), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; @@ -2625,12 +2234,11 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImDrawVert* start_vtx_ptr = _VtxWritePtr; ImDrawIdx* start_idx_ptr = _IdxWritePtr; - const float ht = thickness * 0.5f; const ImVec2 corner_pos[4] = { - ImVec2(p_min.x - ht, p_min.y - ht), - ImVec2(p_max.x + ht, p_min.y - ht), - ImVec2(p_max.x + ht, p_max.y + ht), - ImVec2(p_min.x - ht, p_max.y + ht) + ImVec2(p_min.x, p_min.y), + ImVec2(p_max.x, p_min.y), + ImVec2(p_max.x, p_max.y), + ImVec2(p_min.x, p_max.y) }; static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; static const ImDrawFlags corner_flags[4] = { ImDrawFlags_RoundCornersTopLeft, ImDrawFlags_RoundCornersTopRight, ImDrawFlags_RoundCornersBottomRight, ImDrawFlags_RoundCornersBottomLeft }; @@ -2742,38 +2350,41 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl // FIXME-POLYLINE const bool has_rounding = (rounding >= _FringeScale); - ImVec2 adjusted_min = p_min; - ImVec2 adjusted_max = p_max; - float adjusted_rounding = rounding; + ImVec2 outer_min = p_min; + ImVec2 outer_max = p_max; + float outer_rounding = rounding; - const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); - if (stroke_pos == ImDrawFlags_StrokeInside) + if (stroke_pos == ImDrawFlags_StrokeLegacy) { - adjusted_min += offset; - adjusted_max -= offset; - adjusted_rounding -= thickness * 0.5f; + outer_min += ImVec2(0.50f, 0.50f); + if (Flags & ImDrawListFlags_AntiAliasedLines) + outer_max -= ImVec2(0.50f, 0.50f); + else + outer_max -= ImVec2(0.49f, 0.49f); // Better looking lower-right corner and rounded non-AA shapes. + stroke_pos = ImDrawFlags_StrokeCenter; + } + + if (stroke_pos == ImDrawFlags_StrokeCenter) + { + const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); + outer_min -= offset; + outer_max += offset; + outer_rounding += has_rounding ? thickness * 0.5f : 0.0f; } else if (stroke_pos == ImDrawFlags_StrokeOutside) { - adjusted_min -= offset; - adjusted_max += offset; - adjusted_rounding += thickness * 0.5f; - } - else if (stroke_pos == ImDrawFlags_StrokeLegacy) - { - adjusted_min += ImVec2(0.50f, 0.50f); - if (Flags & ImDrawListFlags_AntiAliasedLines) - adjusted_max -= ImVec2(0.50f, 0.50f); - else - adjusted_max -= ImVec2(0.49f, 0.49f); // Better looking lower-right corner and rounded non-AA shapes. + const ImVec2 offset(thickness, thickness); + outer_min -= offset; + outer_max += offset; + outer_rounding += has_rounding ? thickness : 0.0f; } - const float width = adjusted_max.x - adjusted_min.x; - const float height = adjusted_max.y - adjusted_min.y; - if (ImMin(width, height) < (thickness + _FringeScale)) + const float width = outer_max.x - outer_min.x; + const float height = outer_max.y - outer_min.y; + if (ImMin(width, height) < (thickness + _FringeScale) * 2.0f) { // Rectangle has collapsed into filled rectangle. - AddRectFilled(p_min, p_max, col, rounding, flags); + AddRectFilled(outer_min, outer_max, col, outer_rounding, flags); return; } @@ -2782,36 +2393,35 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { - PathLineTo(adjusted_min); - PathLineTo(ImVec2(adjusted_max.x, adjusted_min.y)); - PathLineTo(adjusted_max); - PathLineTo(ImVec2(adjusted_min.x, adjusted_max.y)); + PathLineTo(outer_min); + PathLineTo(ImVec2(outer_max.x, outer_min.y)); + PathLineTo(outer_max); + PathLineTo(ImVec2(outer_min.x, outer_max.y)); } else { // Constrain rounding to rect dimensions - adjusted_rounding = ImMin(adjusted_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); - adjusted_rounding = ImMin(adjusted_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + outer_rounding = ImMin(outer_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - if (thickness * 0.5f > adjusted_rounding) + if (thickness > outer_rounding) { // Special case rendering to avoid rendering artifacts at the corners. // If rendered using the regular polyline, the stroke will fold and leave artifact on the corner if rendered with transparency. - _AddRectTinyRounding(adjusted_min, adjusted_max, col, adjusted_rounding, thickness, flags); + _AddRectTinyRounding(outer_min, outer_max, col, outer_rounding, thickness, flags); return; } - - const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? adjusted_rounding : 0.0f; - const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? adjusted_rounding : 0.0f; - const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? adjusted_rounding : 0.0f; - const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? adjusted_rounding : 0.0f; - PathArcToFast(ImVec2(adjusted_min.x + rounding_tl, adjusted_min.y + rounding_tl), rounding_tl, 6, 9); - PathArcToFast(ImVec2(adjusted_max.x - rounding_tr, adjusted_min.y + rounding_tr), rounding_tr, 9, 12); - PathArcToFast(ImVec2(adjusted_max.x - rounding_br, adjusted_max.y - rounding_br), rounding_br, 0, 3); - PathArcToFast(ImVec2(adjusted_min.x + rounding_bl, adjusted_max.y - rounding_bl), rounding_bl, 3, 6); + const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? outer_rounding : 0.0f; + const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? outer_rounding : 0.0f; + const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? outer_rounding : 0.0f; + const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? outer_rounding : 0.0f; + PathArcToFast(ImVec2(outer_min.x + rounding_tl, outer_min.y + rounding_tl), rounding_tl, 6, 9); + PathArcToFast(ImVec2(outer_max.x - rounding_tr, outer_min.y + rounding_tr), rounding_tr, 9, 12); + PathArcToFast(ImVec2(outer_max.x - rounding_br, outer_max.y - rounding_br), rounding_br, 0, 3); + PathArcToFast(ImVec2(outer_min.x + rounding_bl, outer_max.y - rounding_bl), rounding_bl, 3, 6); } - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); #else const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) @@ -3026,7 +2636,7 @@ void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_ma PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left); } -void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness) +void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -3035,7 +2645,7 @@ void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, c PathLineTo(p2); PathLineTo(p3); PathLineTo(p4); - PathStroke(col, thickness, ImDrawFlags_Closed); + PathStroke(col, thickness, flags | ImDrawFlags_Closed); } void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col) @@ -3050,7 +2660,7 @@ void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& PathFillConvex(col); } -void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness) +void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -3058,7 +2668,7 @@ void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p PathLineTo(p1); PathLineTo(p2); PathLineTo(p3); - PathStroke(col, thickness, ImDrawFlags_Closed); + PathStroke(col, thickness, flags | ImDrawFlags_Closed); } void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col) @@ -3078,42 +2688,34 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu return; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - - if (g_LEGACY_STROKES) + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { radius -= 0.5f; - } - else - { - if (stroke_pos == ImDrawFlags_StrokeInside) - radius -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - radius -= thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); - else if (stroke_pos == ImDrawFlags_StrokeOutside) - radius += thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeLegacy) - radius -= 0.5f; + stroke_pos = ImDrawFlags_StrokeCenter; } - float adjusted_radius = radius; - if (stroke_pos == ImDrawFlags_StrokeInside) - adjusted_radius -= thickness * 0.5f; + // FIXME-POLYLINE: missing ImDrawFlags_StrokeCenterPixelAligned. + float outer_radius = radius; + if (stroke_pos == ImDrawFlags_StrokeCenter) + outer_radius = radius + thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeInside) + outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) - adjusted_radius += thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeLegacy) - adjusted_radius -= 0.5f; - if (adjusted_radius < (thickness * 0.5f + _FringeScale * 0.5f)) + outer_radius = radius + thickness; + if (outer_radius < (thickness + _FringeScale)) { // The circle has collapsed into a filled circle. - AddCircleFilled(center, radius, col, num_segments); + AddCircleFilled(center, outer_radius, col, num_segments); return; } if (num_segments <= 0) { // Use arc with automatic segment count - const int a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); // Radius used here inteitionally so that the circle matches filled circle of same radius. - _PathArcToFastEx(center, adjusted_radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, a_step); + // FIXME-POLYLINE: Review + //const int a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); // Radius used here intentionally so that the circle matches filled circle of same radius. + //_PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, a_step); + _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); _Path.Size--; } else @@ -3123,10 +2725,10 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, adjusted_radius, 0.0f, a_max, num_segments - 1); + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); } - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos); } void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) @@ -3169,31 +2771,35 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; - if (g_LEGACY_STROKES) + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + { radius -= 0.5f; + stroke_pos = ImDrawFlags_StrokeCenter; + } - const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); const float unit_apothem = ImCos(IM_PI / (float)num_segments); const float miter_thickness = thickness / unit_apothem; - float adjusted_radius = radius; - if (stroke_pos == ImDrawFlags_StrokeInside) - adjusted_radius -= miter_thickness * 0.5f; + float outer_radius = radius; + if (stroke_pos == ImDrawFlags_StrokeCenter) + outer_radius = radius + miter_thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeInside) + outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) - adjusted_radius += miter_thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeLegacy) - adjusted_radius -= 0.5f; - if (adjusted_radius < (miter_thickness * 0.5f + _FringeScale * 0.5f)) + outer_radius = radius + miter_thickness; + + if (outer_radius < (miter_thickness + _FringeScale)) { // The polygon has collapsed into a filled polygon. - AddNgonFilled(center, radius, col, num_segments); + AddNgonFilled(center, outer_radius, col, num_segments); return; } // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, adjusted_radius, 0.0f, a_max, num_segments - 1); - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); + PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos); } // Guaranteed to honor 'num_segments' @@ -3224,8 +2830,9 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co if ((col & IM_COL32_A_MASK) == 0) return; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - + // Note: since offset ellipse is not ellipse anymore, we cannot fall back to filled ellipse when outline covers the whole shape like in other shapes. + // FIXME-POLYLINE + /* ImVec2 r; if (g_LEGACY_STROKES) { @@ -3234,6 +2841,7 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co else { r = radius; + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeInside) r -= ImVec2(thickness * 0.5f, thickness * 0.5f); else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) @@ -3244,7 +2852,8 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co else if (stroke_pos == ImDrawFlags_StrokeOutside) r += ImVec2(thickness * 0.5f, thickness * 0.5f); } - + */ + /* float stroke_offset = 0.0f; if (stroke_pos == ImDrawFlags_StrokeInside) stroke_offset = -thickness * 0.5f; @@ -3255,48 +2864,17 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co AddEllipseFilled(center, radius, col, rot, num_segments); return; } + */ if (num_segments <= 0) num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. _Path.reserve(_Path.Size + (num_segments + 1)); - // Custom tessellation, since offset ellipse is not an ellipse anymore. - const float cos_rot = ImCos(rot); - const float sin_rot = ImSin(rot); - if (stroke_offset != 0.0f) - { - const float inv_rx = 1.0f / radius.x; - const float inv_ry = 1.0f / radius.y; - for (int i = 0; i < num_segments; i++) - { - const float a = ((float)i / (float)num_segments) * IM_PI * 2.0f; - const float dir_x = ImCos(a); - const float dir_y = ImSin(a); - float nx = dir_x * inv_rx; - float ny = dir_y * inv_ry; - IM_NORMALIZE2F_OVER_ZERO(nx, ny); - ImVec2 point(dir_x * radius.x + nx * stroke_offset, dir_y * radius.y + ny * stroke_offset); - const ImVec2 rel((point.x * cos_rot) - (point.y * sin_rot), (point.x * sin_rot) + (point.y * cos_rot)); - point.x = rel.x + center.x; - point.y = rel.y + center.y; - _Path.push_back(point); - } - } - else - { - for (int i = 0; i < num_segments; i++) - { - const float a = ((float)i / (float)num_segments) * IM_PI * 2.0f; - ImVec2 point(ImCos(a) * radius.x, ImSin(a) * radius.y); - const ImVec2 rel((point.x * cos_rot) - (point.y * sin_rot), (point.x * sin_rot) + (point.y * cos_rot)); - point.x = rel.x + center.x; - point.y = rel.y + center.y; - _Path.push_back(point); - } - } - - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly); + // Because we are filling a closed shape we remove 1 from the count of segments/points + const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | flags); } void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments) From 5782f4e0eec8e5eb2b7995ba109f17c43cf00aa4 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 12 May 2026 11:17:49 +0300 Subject: [PATCH 066/245] DrawList: path rendering optimizations. - added ImRsqrtPrecise() which adds Newton-Raphson iteration for more precision - change calculation of miter_scale_factor so that it does not have a branch - renamed IM_POLYLINE_APPEND_* macros to IM_APPEND_* and also use them in fill convex poly - changed the convex poly miter calculation to match the polyline to make debugging and changes easier - split the convex poly to separate loop when ImDrawFlags_MiterOnly is specified for less branches in common case # Conflicts: # imgui_draw.cpp --- imgui_draw.cpp | 191 ++++++++++++++++++++++++++--------------------- imgui_internal.h | 4 + 2 files changed, 111 insertions(+), 84 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3d64cb7b7..a37e35b8e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -924,8 +924,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1 , uv1, col); // AA cap - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); + IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); base_idx = next_base_idx; } else @@ -953,7 +953,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const float cos_theta = n0.x * n1.x + n0.y * n1.y; // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float miter_scale_factor = ImMin(1000.0f, (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? 1.0f / (1.0f + cos_theta) : FLT_MAX); // avoid division by zero + const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. + const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; @@ -986,10 +987,11 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const float sin_theta = n0.y * n1.x - n0.x * n1.y; // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float miter_scale_factor = (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? 1.0f / (1.0f + cos_theta) : FLT_MAX; // avoid division by zero - + const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. + const float miter_scale_factor = ImMin(1000.f, 1.f / (1.0f + cos_theta_clamped)); float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; + const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; if (miter_distance_sqr > miter_distance_limit_sqr) @@ -1144,7 +1146,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 float dx = points[i + 1].x - points[i].x; float dy = points[i + 1].y - points[i].y; const float d2 = dx * dx + dy * dy; - const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; TODO: ImRsqrt is not accurate enough. + const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; normals[i].x = -dy * inv_len; normals[i].y = dx * inv_len; sqr_lengths[i] = d2; @@ -1154,7 +1156,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float dx = points[0].x - points[points_count - 1].x; const float dy = points[0].y - points[points_count - 1].y; const float d2 = dx * dx + dy * dy; - const float inv_len = (d2 > 0.0f) ? 1.0f / sqrtf(d2) : 0.0f; //ImRsqrt(d2) : 0.0f; TODO: ImRsqrt is not accurate enough. + const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; normals[points_count - 1].x = -dy * inv_len; normals[points_count - 1].y = dx * inv_len; sqr_lengths[points_count - 1] = d2; @@ -1452,6 +1454,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun const float half_aa = _FringeScale * 0.5f; ImU32 col_trans = col & ~IM_COL32_A_MASK; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; + const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; const int idx_count = ((points_count - 2) + points_count * 3) * 3; const int vtx_count = (points_count * 3); @@ -1472,7 +1475,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun float d2 = dx*dx + dy*dy; if (d2 > 0.0f) { - float inv_len = ImRsqrt(d2); + const float inv_len = ImRsqrtPrecise(d2); dx *= inv_len; dy *= inv_len; } @@ -1489,100 +1492,121 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun unsigned int prev_outer_idx = 0; // We dont know outer vert could yet, will need to patch once we're done. - const float miter_distance_limit = half_aa * IM_POLYLINE_MITER_LIMIT; - const float miter_distance_limit_sqr = miter_distance_limit * miter_distance_limit; - for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + if (miters_only) { - // Average normals - const ImVec2& n0 = temp_normals[i0]; - const ImVec2& n1 = temp_normals[i1]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - float miter_scale_factor = ImMin(1000.0f, (cos_theta > IM_POLYLINE_MITER_ANGLE_LIMIT) ? (half_aa / (1.0f + cos_theta)) : FLT_MAX); // avoid division by zero - - float dm_x = (n0.x + n1.x) * miter_scale_factor; - float dm_y = (n0.y + n1.y) * miter_scale_factor; - bool bevel = false; - - if (!miters_only) + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { - const float miter_distance_sqr = dm_x * dm_x + dm_y * dm_y; - bevel = miter_distance_sqr > miter_distance_limit_sqr; + // Average normals + const ImVec2 p1 = points[i1]; + const ImVec2 n0 = temp_normals[i0]; + const ImVec2 n1 = temp_normals[i1]; + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. + const float miter_scale_factor = ImMin(1000.f, 1.f / (1.0f + cos_theta_clamped)); + const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor * half_aa; + const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor * half_aa; + + // Inner + inner_vtx_ptr->pos.x = p1.x - miter_offset_x; + inner_vtx_ptr->pos.y = p1.y - miter_offset_y; + inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; + inner_vtx_ptr++; + + const unsigned int prev_inner_idx = vtx_inner_idx + i0; + const unsigned int inner_idx = vtx_inner_idx + i1; + const unsigned int outer_idx = _VtxCurrentIdx; + + // Outer + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv, col_trans); + // Connect with previous + IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); + IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); + + prev_outer_idx = outer_idx; + } + } + else + { + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2 p1 = points[i1]; + const ImVec2 n0 = temp_normals[i0]; + const ImVec2 n1 = temp_normals[i1]; + + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. + const float miter_scale_factor = ImMin(1000.f, 1.f / (1.0f + cos_theta_clamped)); + float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; + float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; + + const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; + bool bevel = miter_distance_sqr > miter_distance_limit_sqr; if (bevel) { // Limit inner bevel so that it is does not shoot out outside the polygon. - const float segment_limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); - if (miter_distance_sqr > segment_limit_sqr) + const float ref_thickness_sqr = half_aa * half_aa; + const float limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); + const float ref_miter_dist_sqr = miter_distance_sqr * ref_thickness_sqr; + if (ref_miter_dist_sqr > limit_sqr) { - const float scale = ImSqrt(segment_limit_sqr / miter_distance_sqr); - dm_x *= scale; - dm_y *= scale; + const float scale = ImSqrt(limit_sqr / ref_miter_dist_sqr); + miter_offset_x *= scale; + miter_offset_y *= scale; } } + + miter_offset_x *= half_aa; + miter_offset_y *= half_aa; + + // Inner + inner_vtx_ptr->pos.x = p1.x - miter_offset_x; + inner_vtx_ptr->pos.y = p1.y - miter_offset_y; + inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; + inner_vtx_ptr++; + + const unsigned int prev_inner_idx = vtx_inner_idx + i0; + const unsigned int inner_idx = vtx_inner_idx + i1; + unsigned int outer_idx = _VtxCurrentIdx; + + // Outer + if (bevel) + { + IM_APPEND_VTX(p1.x + n0.x * half_aa, p1.y + n0.y * half_aa, uv, col_trans); + IM_APPEND_VTX(p1.x + n1.x * half_aa, p1.y + n1.y * half_aa, uv, col_trans); + // Connect with previous + IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); + IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); + // Fill bevel + IM_APPEND_TRI(outer_idx, outer_idx + 1, inner_idx); + outer_idx++; + } + else + { + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv, col_trans); + // Connect with previous + IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); + IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); + } + + prev_outer_idx = outer_idx; } - - // Inner - inner_vtx_ptr->pos.x = (points[i1].x - dm_x); inner_vtx_ptr->pos.y = (points[i1].y - dm_y); inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; - inner_vtx_ptr++; - - unsigned int prev_inner_idx = vtx_inner_idx + i0; - unsigned int inner_idx = vtx_inner_idx + i1; - unsigned int outer_idx = _VtxCurrentIdx; - - // Outer - if (bevel) - { - _VtxWritePtr->pos.x = (points[i1].x + n0.x * half_aa); _VtxWritePtr->pos.y = (points[i1].y + n0.y * half_aa); _VtxWritePtr->uv = uv; _VtxWritePtr->col = col_trans; - _VtxWritePtr++; - _VtxCurrentIdx++; - _VtxWritePtr->pos.x = (points[i1].x + n1.x * half_aa); _VtxWritePtr->pos.y = (points[i1].y + n1.y * half_aa); _VtxWritePtr->uv = uv; _VtxWritePtr->col = col_trans; - _VtxWritePtr++; - _VtxCurrentIdx++; - } - else - { - _VtxWritePtr->pos.x = (points[i1].x + dm_x); _VtxWritePtr->pos.y = (points[i1].y + dm_y); _VtxWritePtr->uv = uv; _VtxWritePtr->col = col_trans; - _VtxWritePtr++; - _VtxCurrentIdx++; - } - - // Connect with previous - _IdxWritePtr[0] = (ImDrawIdx)prev_outer_idx; - _IdxWritePtr[1] = (ImDrawIdx)outer_idx; - _IdxWritePtr[2] = (ImDrawIdx)inner_idx; - - _IdxWritePtr[3] = (ImDrawIdx)prev_outer_idx; - _IdxWritePtr[4] = (ImDrawIdx)inner_idx; - _IdxWritePtr[5] = (ImDrawIdx)prev_inner_idx; - - _IdxWritePtr += 6; - - // Fill bevel - if (bevel) - { - _IdxWritePtr[0] = (ImDrawIdx)outer_idx; - _IdxWritePtr[1] = (ImDrawIdx)outer_idx+1; - _IdxWritePtr[2] = (ImDrawIdx)inner_idx; - _IdxWritePtr += 3; - outer_idx++; - } - - prev_outer_idx = outer_idx; } - // Patch first segment + // Patch first segment to wrap around start_idx_ptr[0] = (ImDrawIdx)prev_outer_idx; start_idx_ptr[3] = (ImDrawIdx)prev_outer_idx; // Add indices for fill for (int i = 2; i < points_count; i++) { - _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + i); - _IdxWritePtr += 3; + IM_APPEND_TRI(vtx_inner_idx, vtx_inner_idx + i - 1, vtx_inner_idx + i); } const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); @@ -2300,7 +2324,6 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, IM_APPEND_TRI(base_idx + 2, stem1_idx, inner_idx); IM_APPEND_TRI(base_idx + 2, inner_idx, base_idx + 3); - base_idx = stem0_idx - 1; } diff --git a/imgui_internal.h b/imgui_internal.h index 547f4ddc4..5d63fe902 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -506,11 +506,15 @@ inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } #ifdef IMGUI_ENABLE_SSE inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } +// Converge to more precise solution using single step of Newton-Raphson method, repeating increase precision +inline float ImRsqrtPrecise(float x) { const float r = _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); return r * (1.5f - x * 0.5f * r * r); } #else inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } +inline float ImRsqrtPrecise(float x) { return 1.0f / sqrtf(x); } #endif inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } #endif + // - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double // (Exceptionally using templates here but we could also redefine them for those types) template T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } From 5d9b691248183a4ed3838474c5e8463e7c0f7cf8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 May 2026 17:17:15 +0200 Subject: [PATCH 067/245] DrawList: misc fixes, amends (replace uses of GetColorU32, macros fixes, default flags). Demo: added rotating square, added MiterOnly checkbox. --- imgui.h | 2 +- imgui_demo.cpp | 29 +++++++++++++++++++---------- imgui_draw.cpp | 30 +++++++++++++++++++----------- 3 files changed, 39 insertions(+), 22 deletions(-) diff --git a/imgui.h b/imgui.h index 6b777437a..4bebc2bd4 100644 --- a/imgui.h +++ b/imgui.h @@ -3454,7 +3454,7 @@ struct ImDrawList inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } inline void PathFillConvex(ImU32 col, ImDrawFlags flags = 0) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, flags); _Path.Size = 0; } inline void PathFillConcave(ImU32 col) { AddConcavePolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } - inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = ImDrawFlags_StrokeCenter) { AddPolyline(_Path.Data, _Path.Size, col, thickness, flags); _Path.Size = 0; } + inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0) { AddPolyline(_Path.Data, _Path.Size, col, thickness, flags); _Path.Size = 0; } IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments = 0); // Ellipse diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 392609ce3..74ce27ef8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10395,7 +10395,6 @@ static void ShowExampleAppCustomRendering(bool* p_open) static bool curve_segments_override = false; static int curve_segments_override_v = 8; static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); - static bool square_caps = false; ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); ImGui::DragFloat("Thickness", &thickness, 0.1f, 0.0f, 30.0f, "%.02f"); ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); @@ -10406,7 +10405,6 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); ImGui::ColorEdit4("Color", &colf.x); - ImGui::Checkbox("Square caps", &square_caps); static ImDrawFlags flags = ImDrawFlags_None; ImGui::AlignTextToFramePadding(); @@ -10417,12 +10415,13 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::SameLine(); ImGui::RadioButton("CenterPixelAligned", &flags, ImDrawFlags_StrokeCenterPixelAligned); ImGui::SameLine(); ImGui::RadioButton("Outside", &flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); ImGui::RadioButton("Legacy", &flags, ImDrawFlags_StrokeLegacy); + ImGui::CheckboxFlags("MiterOnly", &flags, ImDrawFlags_MiterOnly); + ImGui::SameLine(); ImGui::CheckboxFlags("SquareCap", &flags, ImDrawFlags_SquareCap); const ImVec2 p = ImGui::GetCursorScreenPos(); const ImU32 col = ImColor(colf); const float spacing = 10.0f; const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; - const ImDrawFlags cap_flags = square_caps ? ImDrawFlags_SquareCap : ImDrawFlags_None; const float rounding = sz / 5.0f; const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; @@ -10441,8 +10440,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, th, flags); x += sz + spacing; // Square draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, flags); x += sz + spacing; // Square with all rounded corners draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, flags | corners_tl_br); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th/*, flags*/);x += sz + spacing; // Triangle - //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle + draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th, flags);x += sz + spacing; // Triangle + //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th, flags); x+= sz*0.4f + spacing; // Thin triangle PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); x += sz + spacing; // Concave Shape //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); draw_list->AddLineH(x, x + sz, y, col, th, flags); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) @@ -10450,19 +10449,29 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th, flags); x += sz + spacing; draw_list->AddLine(ImVec2(x, y + sz), ImVec2(x, y), col, th, flags); x += spacing; - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th, flags | cap_flags); x += sz + spacing; // Diagonal line + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th, flags); x += sz + spacing; // Diagonal line + + // Rotating square made of lines + float side_step = 3.141592f * 0.5f; + for (int side = 0; side < 4; side++) + { + float t = (float)ImGui::GetTime() * 0.3f + side * side_step; + ImVec2 center(x + sz * 0.5f, y + sz * 0.5f); + draw_list->AddLine({ center.x + cosf(t) * sz * 0.5f, center.y + sinf(t) * sz * 0.5f }, { center.x + cosf(t + side_step) * sz * 0.5f, center.y + sinf(t + side_step) * sz * 0.5f }, col, th, flags); + } + x += sz + spacing; // Path - draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f, 3.141592f * -0.5f); - draw_list->PathStroke(col, th, flags | cap_flags); + draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f * -0.5f, 3.141592f); + draw_list->PathStroke(col, th, flags); x += sz + spacing; // Quadratic Bezier Curve (3 control points) - draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments, flags | cap_flags); + draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments, flags); x += sz + spacing; // Cubic Bezier Curve (4 control points) - draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments, flags | cap_flags); + draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments, flags); x = p.x + 4; y += sz + spacing; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a37e35b8e..06be9491d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -819,6 +819,7 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c #define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) #define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0 +// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. // We avoid using the 'do { } while (false)` idiom in those macros as they typically have overhead in debug builds. #define IM_APPEND_VTX(PX, PY, UV, COL) \ { \ @@ -845,7 +846,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ { const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const ImDrawFlags stroke_pos = (flags & ImDrawFlags_StrokeMask_); + const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; @@ -988,7 +989,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.f, 1.f / (1.0f + cos_theta_clamped)); + const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; @@ -1117,6 +1118,14 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } +static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) +{ + IM_ASSERT_PARANOID(a >= 0.0f && a < 1.0f); // We don't clamp! + ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; + a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range. + return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); +} + void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) @@ -1127,8 +1136,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 return; if (screen_thickness < 1.0f) { - const float alpha = screen_thickness; - col = ImGui::GetColorU32(col, alpha); + col = ImAlphaMultiply(col, screen_thickness); screen_thickness = 1.0f; thickness = _FringeScale; } @@ -1506,7 +1514,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun const float cos_theta = n0.x * n1.x + n0.y * n1.y; // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.f, 1.f / (1.0f + cos_theta_clamped)); + const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor * half_aa; const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor * half_aa; @@ -1542,7 +1550,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun const float cos_theta = n0.x * n1.x + n0.y * n1.y; // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.f, 1.f / (1.0f + cos_theta_clamped)); + const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; @@ -2085,6 +2093,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th } else { + // FIXME-POLYLINE: Implement square caps AddRectFilled(ImVec2(min_x, y), ImVec2(max_x, y + thickness), col); } } @@ -2116,6 +2125,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th } else { + // FIXME-POLYLINE: Implement square caps AddRectFilled(ImVec2(x, min_y), ImVec2(x + thickness, max_y), col); } } @@ -2446,6 +2456,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); #else + // textured_round_corners const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) { @@ -2764,8 +2775,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, return; if (screen_diameter < 1.0f) { - const float alpha = screen_diameter; - col = ImGui::GetColorU32(col, alpha); + col = ImAlphaMultiply(col, screen_diameter); radius = _FringeScale * 0.5f; } @@ -2811,7 +2821,6 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) outer_radius = radius + miter_thickness; - if (outer_radius < (miter_thickness + _FringeScale)) { // The polygon has collapsed into a filled polygon. @@ -2836,8 +2845,7 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in return; if (screen_diameter < 1.0f) { - const float alpha = screen_diameter; - col = ImGui::GetColorU32(col, alpha); + col = ImAlphaMultiply(col, screen_diameter); radius = _FringeScale * 0.5f; } From c1f781d7af4abe61b4c6bcea0e0d9f9f2edd7a57 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 22 May 2026 09:59:29 +0300 Subject: [PATCH 068/245] DrawList: manually fix cases from merge, added missing cases of ImDrawFlags_StrokeCenterPixelAligned. --- imgui_draw.cpp | 347 +++++++++++++++++++------------------------------ 1 file changed, 133 insertions(+), 214 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 06be9491d..c88fb2440 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -812,6 +812,20 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c _IdxWritePtr += 6; } + +static float CalculateCenterPixelAlignedOffset(float thickness, float _FringeScale) +{ + // Old jumpy one. + // return IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; + + // Calculate outside offset for stroke position CenterPixelAligned + // so that one side the of the line is always at pixel boundary. + // On integer thickness both sides of the line are on pixel boundary. + const float screen_thickness = thickness / _FringeScale; + const int s_thickness = (int)screen_thickness; + return ((float)(s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; +} + // On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. // - Those macros expects l-values and need to be used as their own statement. // - Those macros are intentionally not surrounded by the 'do {} while (0)' idiom because even that translates to runtime with debug compilers. @@ -851,18 +865,14 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; - float thickness0 = (thickness + fringe) * 0.5f; - float thickness1 = thickness0; + float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) if (stroke_pos == ImDrawFlags_StrokeOutside) - { thickness0 = thickness + fringe * 0.5f; - thickness1 = fringe * 0.5f; - } + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + thickness0 = CalculateCenterPixelAlignedOffset(thickness, _FringeScale) + fringe * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeInside) - { thickness0 = fringe * 0.5f; - thickness1 = thickness + fringe * 0.5f; - } + float thickness1 = (thickness + fringe) - thickness0; int idx_count = 0; int vtx_count = 0; @@ -2026,19 +2036,6 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } } -static float CalculateCenterPixelAlignedOffset(float thickness, float _FringeScale) -{ - // Old jumpy one. - // return IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; - - // Calculate outside offset for stroke position CenterPixelAligned - // so that one side the of the line is always at pixel boundary. - // On integer thickness both sides of the line are on pixel boundary. - const float screen_thickness = thickness / _FringeScale; - const int s_thickness = (int)screen_thickness; - return ((float)(s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; -} - extern bool g_LEGACY_STROKES; // We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. @@ -2055,7 +2052,8 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th if ((col & IM_COL32_A_MASK) == 0) return; - if (g_LEGACY_STROKES) + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); @@ -2075,26 +2073,33 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); + AddPolyline(points, 2, col, thickness, stroke_pos); return; } + float top_y = y; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) - y -= thickness * 0.5f; + top_y -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - y -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); + top_y -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) - y -= thickness; + top_y -= thickness; - if (_FringeScaleIsInteger && ImIsTruncated4(min_x, max_x, y, thickness)) + if (_FringeScaleIsInteger && ImIsTruncated4(min_x, max_x, top_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) { + // For pixel aligned case, use simple rectangle. PrimReserve(6, 4); - PrimRect(ImVec2(min_x, y), ImVec2(max_x, y + thickness), col); + PrimRect(ImVec2(min_x, top_y), ImVec2(max_x, top_y + thickness), col); } else { - // FIXME-POLYLINE: Implement square caps - AddRectFilled(ImVec2(min_x, y), ImVec2(max_x, y + thickness), col); + // Replace stroke pos with the already calculated one. + flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; + + // For generic case use line, since it needs less triangles than AA rectangle. + PathLineTo(ImVec2(min_x, y)); + PathLineTo(ImVec2(max_x, y)); + PathStroke(col, thickness, flags); } } @@ -2107,26 +2112,34 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(x + 0.5f, max_y + 0.5f), ImVec2(x + 0.5f, min_y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); + AddPolyline(points, 2, col, thickness, stroke_pos); return; } + float left_x = x; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) - x -= thickness * 0.5f; + left_x -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - x -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); + left_x -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) - x -= thickness; + left_x -= thickness; - if (_FringeScaleIsInteger && ImIsTruncated4(x, min_y, max_y, thickness)) + if (_FringeScaleIsInteger && ImIsTruncated4(left_x, min_y, max_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) { + // For pixel aligned case, use simple rectangle. PrimReserve(6, 4); - PrimRect(ImVec2(x, min_y), ImVec2(x + thickness, max_y), col); + PrimRect(ImVec2(left_x, min_y), ImVec2(left_x + thickness, max_y), col); } else { - // FIXME-POLYLINE: Implement square caps - AddRectFilled(ImVec2(x, min_y), ImVec2(x + thickness, max_y), col); + // Replace stroke pos with the already calculated one. + flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; + + // For generic case use line, since it needs less triangles than AA rectangle. + // Drawing for bottom to top, so that the inside stroke pos expands to right. + PathLineTo(ImVec2(x, max_y)); + PathLineTo(ImVec2(x, min_y)); + PathStroke(col, thickness, flags); } } @@ -2368,49 +2381,37 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if ((col & IM_COL32_A_MASK) == 0) return; - if (g_LEGACY_STROKES) + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { if (Flags & ImDrawListFlags_AntiAliasedLines) PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); else PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. - PathStroke(col, thickness, ImDrawFlags_Closed); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeCenter); return; } - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); -#if 0 // shiny_polyline - // FIXME-POLYLINE - const bool has_rounding = (rounding >= _FringeScale); + const bool has_rounding = (rounding >= _FringeScale * 0.5f); + // Calculate the outer boundary of the rectangle based on the stroke position. ImVec2 outer_min = p_min; ImVec2 outer_max = p_max; float outer_rounding = rounding; - if (stroke_pos == ImDrawFlags_StrokeLegacy) - { - outer_min += ImVec2(0.50f, 0.50f); - if (Flags & ImDrawListFlags_AntiAliasedLines) - outer_max -= ImVec2(0.50f, 0.50f); - else - outer_max -= ImVec2(0.49f, 0.49f); // Better looking lower-right corner and rounded non-AA shapes. - stroke_pos = ImDrawFlags_StrokeCenter; - } - + float offset = 0.0f; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) - { - const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); - outer_min -= offset; - outer_max += offset; - outer_rounding += has_rounding ? thickness * 0.5f : 0.0f; - } + offset = thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + offset = CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) - { - const ImVec2 offset(thickness, thickness); - outer_min -= offset; - outer_max += offset; - outer_rounding += has_rounding ? thickness : 0.0f; - } + offset = thickness; + outer_min.x -= offset; + outer_min.y -= offset; + outer_max.x += offset; + outer_max.y += offset; + outer_rounding += has_rounding ? offset : 0.0f; const float width = outer_max.x - outer_min.x; const float height = outer_max.y - outer_min.y; @@ -2423,6 +2424,61 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if ((flags & ImDrawFlags_RoundCornersMask_) == 0) flags |= ImDrawFlags_RoundCornersAll; + if (has_rounding) + { + // Constrain rounding to rect dimensions + outer_rounding = ImMin(outer_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + } + + if (_FringeScaleIsInteger && ImIsTruncated4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && ImIsTruncated4(outer_rounding, thickness, 0.0f, 0.0f)) + { + int s_rounding = (int)(outer_rounding / _FringeScale); + int s_thickness = (int)(thickness / _FringeScale); + + if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + // Pixel aligned non-rounded rect. + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; + const float t = (float)s_thickness * _FringeScale; + + PrimReserve(8*3, 8); + const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(outer_min.x, outer_min.y, opaque_uv, col); + IM_APPEND_VTX(outer_min.x + t, outer_min.y + t, opaque_uv, col); + IM_APPEND_VTX(outer_max.x, outer_min.y, opaque_uv, col); + IM_APPEND_VTX(outer_max.x - t, outer_min.y + t, opaque_uv, col); + IM_APPEND_VTX(outer_max.x, outer_max.y, opaque_uv, col); + IM_APPEND_VTX(outer_max.x - t, outer_max.y - t, opaque_uv, col); + IM_APPEND_VTX(outer_min.x, outer_max.y, opaque_uv, col); + IM_APPEND_VTX(outer_min.x + t, outer_max.y - t, opaque_uv, col); + + IM_APPEND_TRI(idx + 0, idx + 3, idx + 1); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); + + IM_APPEND_TRI(idx + 2, idx + 5, idx + 3); + IM_APPEND_TRI(idx + 2, idx + 4, idx + 5); + + IM_APPEND_TRI(idx + 4, idx + 7, idx + 5); + IM_APPEND_TRI(idx + 4, idx + 6, idx + 7); + + IM_APPEND_TRI(idx + 6, idx + 1, idx + 7); + IM_APPEND_TRI(idx + 6, idx + 0, idx + 1); + + return; + } + if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + { + // Pixel aligned rect with round corners rendered using baked textures. + IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); + const int size = ImMax(s_rounding, s_thickness); // This is matching the baking calculations. + const int idx = (s_thickness - 1) * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + s_rounding - 1; + IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); + const ImVec4 tex_uvs = _Data->TexUvCornerStrokes[idx]; + _AddRectBaked(outer_min, outer_max, col, (float)size * _FringeScale, (float)thickness, tex_uvs, flags); + return; + } + } if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { @@ -2433,10 +2489,6 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl } else { - // Constrain rounding to rect dimensions - outer_rounding = ImMin(outer_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); - outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - if (thickness > outer_rounding) { // Special case rendering to avoid rendering artifacts at the corners. @@ -2455,111 +2507,6 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl } PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); -#else - // textured_round_corners - const bool is_truncated = _FringeScaleIsInteger && ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated4(rounding, thickness, 0.0f, 0.0f); - if ((stroke_pos == ImDrawFlags_StrokeInside || stroke_pos == ImDrawFlags_StrokeOutside || stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) && is_truncated) - { - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags |= ImDrawFlags_RoundCornersAll; - - rounding = ImMin(rounding, ImFabs(p_max.x - p_min.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); - rounding = ImMin(rounding, ImFabs(p_max.y - p_min.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - - int s_rounding = (int)(rounding / _FringeScale); - int s_thickness = (int)(thickness / _FringeScale); - - // AddRectBaked() renders the stroke inside the rectangle, so we need to adjust the outside case - // This branch does not handle the center, since odd thickness strokes are not pixel aligned, even if the rectangle is. - // Pixel aligned center works, since the stroke is aligned to pixels. - ImVec2 s_min = p_min; - ImVec2 s_max = p_max; - if (stroke_pos == ImDrawFlags_StrokeOutside) - { - s_min.x -= thickness; - s_min.y -= thickness; - s_max.x += thickness; - s_max.y += thickness; - if (s_rounding != 0) - s_rounding += s_thickness; - } - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - { - const float offset = (float)(s_thickness / 2) * _FringeScale; // Using integer div, since we want IM_TRUNC(thickness/2). - s_min.x -= offset; - s_min.y -= offset; - s_max.x += offset; - s_max.y += offset; - if (s_rounding != 0) - s_rounding += s_thickness / 2; - } - - if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) - { - const ImVec2 opaque_uv = _Data->TexUvWhitePixel; - const float t = (float)s_thickness * _FringeScale; - - PrimReserve(8*3, 8); - const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(s_min.x, s_min.y, opaque_uv, col); - IM_APPEND_VTX(s_min.x + t, s_min.y + t, opaque_uv, col); - IM_APPEND_VTX(s_max.x, s_min.y, opaque_uv, col); - IM_APPEND_VTX(s_max.x - t, s_min.y + t, opaque_uv, col); - IM_APPEND_VTX(s_max.x, s_max.y, opaque_uv, col); - IM_APPEND_VTX(s_max.x - t, s_max.y - t, opaque_uv, col); - IM_APPEND_VTX(s_min.x, s_max.y, opaque_uv, col); - IM_APPEND_VTX(s_min.x + t, s_max.y - t, opaque_uv, col); - - IM_APPEND_TRI(idx + 0, idx + 3, idx + 1); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - - IM_APPEND_TRI(idx + 2, idx + 5, idx + 3); - IM_APPEND_TRI(idx + 2, idx + 4, idx + 5); - - IM_APPEND_TRI(idx + 4, idx + 7, idx + 5); - IM_APPEND_TRI(idx + 4, idx + 6, idx + 7); - - IM_APPEND_TRI(idx + 6, idx + 1, idx + 7); - IM_APPEND_TRI(idx + 6, idx + 0, idx + 1); - - return; - } - if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) - { - IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); - const int size = ImMax(s_rounding, s_thickness); // This is matching the baking calculations. - const int idx = (s_thickness - 1) * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + s_rounding - 1; - IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); - const ImVec4 tex_uvs = _Data->TexUvCornerStrokes[idx]; - _AddRectBaked(s_min, s_max, col, (float)size * _FringeScale, (float)thickness, tex_uvs, flags); - return; - } - } - - const ImVec2 offset(thickness * 0.5f, thickness * 0.5f); - if (stroke_pos == ImDrawFlags_StrokeInside) - { - rounding -= (rounding != 0.0f) ? thickness * 0.5f : 0.0f; - PathRect(p_min + offset, p_max - offset, rounding, flags); - } - else if (stroke_pos == ImDrawFlags_StrokeCenter) - { - PathRect(p_min, p_max, rounding, flags); - } - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - { - // PathRect() centers the stroke, just calculate the fractional offset. - const float fract = (thickness * 0.5f) - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); - rounding += (rounding != 0.0f) ? fract : 0.0f; - PathRect(ImVec2(p_min.x + fract, p_min.y + fract), ImVec2(p_max.x - fract, p_max.y - fract), rounding, flags); - } - else if (stroke_pos == ImDrawFlags_StrokeOutside) - { - rounding += (rounding != 0.0f) ? thickness * 0.5f : 0.0f; - PathRect(p_min - offset, p_max + offset, rounding, flags); - } - PathStroke(col, thickness, ImDrawFlags_Closed); -#endif } void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags) @@ -2728,10 +2675,11 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu stroke_pos = ImDrawFlags_StrokeCenter; } - // FIXME-POLYLINE: missing ImDrawFlags_StrokeCenterPixelAligned. float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + outer_radius = radius + CalculateCenterPixelAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2746,10 +2694,8 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu if (num_segments <= 0) { // Use arc with automatic segment count - // FIXME-POLYLINE: Review - //const int a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); // Radius used here intentionally so that the circle matches filled circle of same radius. - //_PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, a_step); - _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); + const int a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(outer_radius); // Use outer_radius for segment count to be consistent with rounded rect. + _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, a_step); _Path.Size--; } else @@ -2817,6 +2763,8 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + miter_thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) + outer_radius = radius + CalculateCenterPixelAlignedOffset(miter_thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2861,41 +2809,12 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co if ((col & IM_COL32_A_MASK) == 0) return; - // Note: since offset ellipse is not ellipse anymore, we cannot fall back to filled ellipse when outline covers the whole shape like in other shapes. - // FIXME-POLYLINE - /* - ImVec2 r; - if (g_LEGACY_STROKES) + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); + + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { - r = radius; + stroke_pos = ImDrawFlags_StrokeCenter; } - else - { - r = radius; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeInside) - r -= ImVec2(thickness * 0.5f, thickness * 0.5f); - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - { - const float fract = thickness * 0.5f - CalculateCenterPixelAlignedOffset(thickness, _FringeScale); - r -= ImVec2(fract, fract); - } - else if (stroke_pos == ImDrawFlags_StrokeOutside) - r += ImVec2(thickness * 0.5f, thickness * 0.5f); - } - */ - /* - float stroke_offset = 0.0f; - if (stroke_pos == ImDrawFlags_StrokeInside) - stroke_offset = -thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeOutside) - stroke_offset = thickness * 0.5f; - if ((ImMin(radius.x, radius.y) + stroke_offset) < (thickness * 0.5f + _FringeScale * 0.5f)) - { - AddEllipseFilled(center, radius, col, rot, num_segments); - return; - } - */ if (num_segments <= 0) num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. @@ -2905,7 +2824,7 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1); - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | flags); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos); } void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments) From 170a374f5993170e5161193176cfb2e1f2c7b393 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 22 May 2026 10:09:57 +0300 Subject: [PATCH 069/245] DrawList: added ImDrawFlags_NoAAEnds which allows to disable line end AA. --- imgui.h | 5 ++-- imgui_demo.cpp | 3 +- imgui_draw.cpp | 75 +++++++++++++++++++++++++++++++++----------------- 3 files changed, 54 insertions(+), 29 deletions(-) diff --git a/imgui.h b/imgui.h index 4bebc2bd4..0a495a688 100644 --- a/imgui.h +++ b/imgui.h @@ -3330,13 +3330,14 @@ enum ImDrawFlags_ ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. ImDrawFlags_MiterOnly = 1 << 10, // PathStroke(), AddPolyline(): use miter corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. ImDrawFlags_SquareCap = 1 << 11, // PathStroke(), AddPolyline(): use square cap line ends. + ImDrawFlags_NoAAEnds = 1 << 12, // PathStroke(), AddPolyline(): do not generate anti-aliased line ends. This can speed up single line rendering. // Stroke position relative to the shape outline - ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (Default) + ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline ImDrawFlags_StrokeCenterPixelAligned = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline - ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy position + ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly and NoAAEnds flags. ImDrawFlags_StrokeMask_ = 0x07 << 16, ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 74ce27ef8..dec9d485e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10417,6 +10417,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::SameLine(); ImGui::RadioButton("Legacy", &flags, ImDrawFlags_StrokeLegacy); ImGui::CheckboxFlags("MiterOnly", &flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); ImGui::CheckboxFlags("SquareCap", &flags, ImDrawFlags_SquareCap); + ImGui::SameLine(); ImGui::CheckboxFlags("NoAAEnds", &flags, ImDrawFlags_NoAAEnds); const ImVec2 p = ImGui::GetCursorScreenPos(); const ImU32 col = ImColor(colf); @@ -10455,7 +10456,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) float side_step = 3.141592f * 0.5f; for (int side = 0; side < 4; side++) { - float t = (float)ImGui::GetTime() * 0.3f + side * side_step; + float t = (float)ImGui::GetTime() * 0.1f + side * side_step; ImVec2 center(x + sz * 0.5f, y + sz * 0.5f); draw_list->AddLine({ center.x + cosf(t) * sz * 0.5f, center.y + sinf(t) * sz * 0.5f }, { center.x + cosf(t + side_step) * sz * 0.5f, center.y + sinf(t + side_step) * sz * 0.5f }, col, th, flags); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c88fb2440..d10ec91d0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -923,21 +923,31 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const ImVec2 dir(n1.y, -n1.x); if (flags & ImDrawFlags_SquareCap) p1 -= dir * half_thickness; - const ImVec2 pa = p1 - dir * half_aa; - const ImVec2 pb = p1 + dir * half_aa; - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col_trans); - IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col_trans); + if (flags & ImDrawFlags_NoAAEnds) + { + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); + IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); + } + else + { + const ImVec2 pa = p1 - dir * half_aa; + const ImVec2 pb = p1 + dir * half_aa; - int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col); - IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1 , uv1, col); + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col_trans); + IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col_trans); - // AA cap - IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); - base_idx = next_base_idx; + int next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col); + IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1, uv1, col); + + // AA cap + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + base_idx = next_base_idx; + } } else { @@ -1095,24 +1105,37 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const ImVec2 dir(n1.y, -n1.x); if (flags & ImDrawFlags_SquareCap) p1 += dir * half_thickness; - const ImVec2 pa = p1 - dir * half_aa; - const ImVec2 pb = p1 + dir * half_aa; - int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col); - IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col); + if (flags & ImDrawFlags_NoAAEnds) + { + IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); + IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); - IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col_trans); - IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1, uv1, col_trans); + // Connect + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + } + else + { + const ImVec2 pa = p1 - dir * half_aa; + const ImVec2 pb = p1 + dir * half_aa; - // Connect - IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); - base_idx = next_base_idx; + int next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col); + IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col); - // AA cap - IM_APPEND_TRI(base_idx+0, base_idx+2, base_idx+3); - IM_APPEND_TRI(base_idx+0, base_idx+3, base_idx+1); + IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col_trans); + IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1, uv1, col_trans); + + // Connect + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + base_idx = next_base_idx; + + // AA cap + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + } } else { From ce3d970fc7e101a9d61e3cc93547c6f6e4ee765f Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 22 May 2026 12:36:20 +0300 Subject: [PATCH 070/245] DrawList: optimized AA end overhead in debug builds. - inline some code and reuse vars (ctors get function calls in debug msvc) to reduce the AA line end over in debug builds --- imgui_draw.cpp | 53 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d10ec91d0..ac8fb7193 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -889,6 +889,20 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/4 + /*caps*/(4 * 2)) * 3; } + + const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; + const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. + ImVec2 uv0, uv1, uv2; + uv0.x = tex_uvs.x + half_texel; + uv0.y = tex_uvs.y; + uv1.x = tex_uvs.z - half_texel; + uv1.y = tex_uvs.y; + uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; + uv2.y = tex_uvs.y; + + const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. + const float half_thickness = thickness * 0.5f; + PrimReserve(idx_count, vtx_count); ImDrawVert* start_vtx_ptr = _VtxWritePtr; @@ -896,19 +910,11 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ int base_idx = (int)_VtxCurrentIdx; + ImVec2 pa, pb, dir; ImVec2 p1; ImVec2 n1; float len_sqr1; - const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; - const ImVec2 uv0(tex_uvs.x + half_texel, tex_uvs.y); - const ImVec2 uv1(tex_uvs.z - half_texel, tex_uvs.y); - const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. - const ImVec2 uv2(uv0.x + (uv1.x - uv0.x) * ratio, tex_uvs.y); - - const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. - const float half_thickness = thickness * 0.5f; - int point_idx = 0; int point_end = points_count; if (!closed) @@ -920,9 +926,14 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ n1 = normals[0]; len_sqr1 = sqr_lengths[0]; - const ImVec2 dir(n1.y, -n1.x); + dir.x = n1.y; + dir.y = -n1.x; + if (flags & ImDrawFlags_SquareCap) - p1 -= dir * half_thickness; + { + p1.x -= dir.x * half_thickness; + p1.y -= dir.y * half_thickness; + } if (flags & ImDrawFlags_NoAAEnds) { @@ -932,8 +943,10 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ } else { - const ImVec2 pa = p1 - dir * half_aa; - const ImVec2 pb = p1 + dir * half_aa; + pa.x = p1.x - dir.x * half_aa; + pa.y = p1.y - dir.y * half_aa; + pb.x = p1.x + dir.x * half_aa; + pb.y = p1.y + dir.y * half_aa; base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col_trans); @@ -1102,9 +1115,13 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ n1 = normals[points_count-1]; // End cap - const ImVec2 dir(n1.y, -n1.x); + dir.x = n1.y; + dir.y = -n1.x; if (flags & ImDrawFlags_SquareCap) - p1 += dir * half_thickness; + { + p1.x += dir.x * half_thickness; + p1.y += dir.y * half_thickness; + } if (flags & ImDrawFlags_NoAAEnds) { @@ -1117,8 +1134,10 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ } else { - const ImVec2 pa = p1 - dir * half_aa; - const ImVec2 pb = p1 + dir * half_aa; + pa.x = p1.x - dir.x * half_aa; + pa.y = p1.y - dir.y * half_aa; + pb.x = p1.x + dir.x * half_aa; + pb.y = p1.y + dir.y * half_aa; int next_base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col); From d879e9781b6b45aa2c9fae7443a26924dc6cf9f1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 May 2026 16:00:55 +0200 Subject: [PATCH 071/245] DrawList: wired AddPolylineLegacy() to g_LEGACY_STROKES. Fixed AddLine(), AddLineV(), AddLineH() legacy path. --- imgui_draw.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ac8fb7193..400fe6067 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -861,6 +861,9 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const ImU32 col_trans = col & ~IM_COL32_A_MASK; const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); + if (stroke_pos == ImDrawFlags_StrokeLegacy) + flags |= ImDrawFlags_MiterOnly | ImDrawFlags_NoAAEnds; + const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; @@ -1178,8 +1181,16 @@ static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } +extern bool g_LEGACY_STROKES; + void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { + if (g_LEGACY_STROKES) + { + AddPolylineLegacy(points, points_count, col, thickness, flags); + return; + } + if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) return; @@ -2078,8 +2089,6 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } } -extern bool g_LEGACY_STROKES; - // We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. // The earlier should use verbatim legacy code but will be removed before release once we confirm that both matches. ImDrawFlags ImDrawList::_GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos) @@ -2688,6 +2697,8 @@ void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p if ((col & IM_COL32_A_MASK) == 0) return; + ImDrawFlags stroke_pos = g_LEGACY_STROKES ? ImDrawFlags_StrokeLegacy : _GetStrokePos(flags, ImDrawFlags_StrokeInside); + flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; PathLineTo(p1); PathLineTo(p2); PathLineTo(p3); From 0e219e6c4ddbe16e606d9cfe74357517ab7fa2fa Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 May 2026 16:49:40 +0200 Subject: [PATCH 072/245] Demo: rework Custom Rendering's Primitives rendering. Fill + Stroke overlap. Use {} style for ImVec2. --- imgui_demo.cpp | 214 +++++++++++++++++++++++++++++-------------------- 1 file changed, 126 insertions(+), 88 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dec9d485e..c3a63ac27 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10394,7 +10394,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) static int circle_segments_override_v = 12; static bool curve_segments_override = false; static int curve_segments_override_v = 8; - static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); + static ImVec4 colf_stroke = ImVec4(1.00f, 1.00f, 0.40f, 1.0f); + static ImVec4 colf_fill = ImVec4(0.70f, 0.18f, 0.62f, 1.0f); ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); ImGui::DragFloat("Thickness", &thickness, 0.1f, 0.0f, 30.0f, "%.02f"); ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); @@ -10404,114 +10405,151 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Checkbox("##curvessegmentoverride", &curve_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); - ImGui::ColorEdit4("Color", &colf.x); + ImGui::ColorEdit4("Stroke Color", &colf_stroke.x); + ImGui::ColorEdit4("Fill Color", &colf_fill.x); static ImDrawFlags flags = ImDrawFlags_None; - ImGui::AlignTextToFramePadding(); - ImGui::Text("Stroke:"); - ImGui::SameLine(); ImGui::RadioButton("Default", &flags, ImDrawFlags_None); - ImGui::SameLine(); ImGui::RadioButton("Inside", &flags, ImDrawFlags_StrokeInside); - ImGui::SameLine(); ImGui::RadioButton("Center", &flags, ImDrawFlags_StrokeCenter); - ImGui::SameLine(); ImGui::RadioButton("CenterPixelAligned", &flags, ImDrawFlags_StrokeCenterPixelAligned); - ImGui::SameLine(); ImGui::RadioButton("Outside", &flags, ImDrawFlags_StrokeOutside); - ImGui::SameLine(); ImGui::RadioButton("Legacy", &flags, ImDrawFlags_StrokeLegacy); - ImGui::CheckboxFlags("MiterOnly", &flags, ImDrawFlags_MiterOnly); - ImGui::SameLine(); ImGui::CheckboxFlags("SquareCap", &flags, ImDrawFlags_SquareCap); - ImGui::SameLine(); ImGui::CheckboxFlags("NoAAEnds", &flags, ImDrawFlags_NoAAEnds); + ImGui::Text("Stroke Flags:"); + ImGui::RadioButton("Default", &flags, ImDrawFlags_None); ImGui::SameLine(); + ImGui::RadioButton("Inside", &flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); + ImGui::RadioButton("Center", &flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); + ImGui::RadioButton("CenterPixelAligned", &flags, ImDrawFlags_StrokeCenterPixelAligned); ImGui::SameLine(); + ImGui::RadioButton("Outside", &flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); + ImGui::RadioButton("Legacy", &flags, ImDrawFlags_StrokeLegacy); + ImGui::CheckboxFlags("MiterOnly", &flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); + ImGui::CheckboxFlags("SquareCap", &flags, ImDrawFlags_SquareCap); ImGui::SameLine(); + ImGui::CheckboxFlags("NoAAEnds", &flags, ImDrawFlags_NoAAEnds); + ImGui::Spacing(); - const ImVec2 p = ImGui::GetCursorScreenPos(); - const ImU32 col = ImColor(colf); + ImVec2 start_pos = ImGui::GetCursorScreenPos(); + const float pi = 3.141592f; const float spacing = 10.0f; const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; const float rounding = sz / 5.0f; + const float half_sz = sz * 0.5f; + const float half_szi = (float)(int)(sz * 0.5f); const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; const ImVec2 cp3[3] = { ImVec2(0.0f, sz * 0.6f), ImVec2(sz * 0.5f, -sz * 0.4f), ImVec2(sz, sz) }; // Control points for curves const ImVec2 cp4[4] = { ImVec2(0.0f, 0.0f), ImVec2(sz * 1.3f, sz * 0.3f), ImVec2(sz - sz * 1.3f, sz - sz * 0.3f), ImVec2(sz, sz) }; - - float x = p.x + 4.0f; - float y = p.y + 4.0f; - for (int n = 0; n < 2; n++) + ImVec2 rotating_square[4]; + for (int side = 0; side < 4; side++) { - // First line uses a thickness of 1.0f, second line uses the configurable thickness - float th = (n == 0) ? 1.0f : thickness; - draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th, flags); x += sz + spacing; // N-gon - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th, flags); x += sz + spacing; // Circle - draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th, flags); x += sz + spacing; // Ellipse - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, th, flags); x += sz + spacing; // Square - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, flags); x += sz + spacing; // Square with all rounded corners - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, flags | corners_tl_br); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th, flags);x += sz + spacing; // Triangle - //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th, flags); x+= sz*0.4f + spacing; // Thin triangle - PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); x += sz + spacing; // Concave Shape - //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); - draw_list->AddLineH(x, x + sz, y, col, th, flags); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) - draw_list->AddLineV(x, y, y + sz, col, th, flags); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th, flags); x += sz + spacing; - draw_list->AddLine(ImVec2(x, y + sz), ImVec2(x, y), col, th, flags); x += spacing; + float t = (float)ImGui::GetTime() * 0.1f + side * pi * 0.5f; + rotating_square[side] = { (float)cosf(t) * half_sz, (float)sin(t) * half_sz }; + } - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th, flags); x += sz + spacing; // Diagonal line - - // Rotating square made of lines - float side_step = 3.141592f * 0.5f; - for (int side = 0; side < 4; side++) + float x = start_pos.x; + float y = start_pos.y; + for (int row = 0; row < 4; row++) + { + x = start_pos.x; + bool draw_fill = (row == 2 || row == 3); + bool draw_strokes = (row == 0 || row == 1 || row == 3); + if (draw_fill) { - float t = (float)ImGui::GetTime() * 0.1f + side * side_step; - ImVec2 center(x + sz * 0.5f, y + sz * 0.5f); - draw_list->AddLine({ center.x + cosf(t) * sz * 0.5f, center.y + sinf(t) * sz * 0.5f }, { center.x + cosf(t + side_step) * sz * 0.5f, center.y + sinf(t + side_step) * sz * 0.5f }, col, th, flags); + // FILLED SHAPES + const ImU32 col = ImColor(colf_fill); + draw_list->AddNgonFilled({ x + half_sz, y + half_sz }, half_sz, col, ngon_sides); x += sz + spacing; // N-gon + draw_list->AddCircleFilled({ x + half_sz, y + half_sz }, half_sz, col, circle_segments); x += sz + spacing; // Circle + draw_list->AddEllipseFilled({ x + half_sz, y + half_sz }, { sz * 0.5f, sz * 0.3f }, col, -0.3f, circle_segments); x += sz + spacing;// Ellipse + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col); x += sz + spacing; // Square + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding); x += sz + spacing; // Square with all rounded corners + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangleFilled({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col); x += sz + spacing; // Triangle + draw_list->AddTriangleFilled({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col); x += (float)(int)(sz * 0.4f) + spacing; // Thin triangle + PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape + draw_list->AddRectFilled({ x, y }, { x + sz, y + thickness }, col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled({ x, y }, { x + thickness, y + sz }, col); x += half_szi + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) + if (!(draw_fill && draw_strokes)) //-V560 + { + draw_list->AddRectFilled({ x + 0, y }, { x + 0 + 1, y + 1 }, col); // Pixels (faster than AddLine) + draw_list->AddRectFilled({ x + 2, y }, { x + 2 + 2, y + 2 }, col); + draw_list->AddRectFilled({ x + 5, y }, { x + 5 + 3, y + 3 }, col); + } + x += spacing + sz; + + // Rotating square + for (int n = 0; n < 4; n++) + draw_list->PathLineTo({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }); + draw_list->PathFillConvex(col, flags); + x += sz + spacing; + + // Path + draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi); + draw_list->PathFillConvex(col); + x += sz + spacing; + + // Quadratic Bezier Curve (3 control points) + draw_list->PathLineTo({ x + cp3[0].x, y + cp3[0].y }); + draw_list->PathBezierQuadraticCurveTo({ x + cp3[1].x, y + cp3[1].y }, { x + cp3[2].x, y + cp3[2].y }, curve_segments); + draw_list->PathFillConvex(col); + x += sz + spacing; + + if (!(draw_fill && draw_strokes)) //-V560 + { + draw_list->AddRectFilledMultiColor({ x, y }, { x + sz, y + sz }, IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); + x += sz + spacing; + } } - x += sz + spacing; + if (draw_fill && draw_strokes) + x = start_pos.x; + if (draw_strokes) + { + // STROKES + // First row uses a thickness of 1.0f, second row uses the configurable thickness + const ImU32 col = ImColor(colf_stroke); + float th = (row == 0) ? 1.0f : thickness; + draw_list->AddNgon({ x + half_sz, y + half_sz }, half_sz, col, ngon_sides, th, flags); x += sz + spacing; // N-gon + draw_list->AddCircle({ x + half_sz, y + half_sz }, half_sz, col, circle_segments, th, flags); x += sz + spacing; // Circle + draw_list->AddEllipse({ x + half_sz, y + half_sz }, { sz * 0.5f, sz * 0.3f }, col, -0.3f, circle_segments, th, flags); x += sz + spacing; // Ellipse + draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, 0.0f, th, flags); x += sz + spacing; // Square + draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags); x += sz + spacing; // Square with all rounded corners + draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags | corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangle({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col, th, flags); x += sz + spacing; // Triangle + draw_list->AddTriangle({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col, th, flags); x += (float)(int)(sz * 0.4f) + spacing; // Thin triangle + PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); x += sz + spacing; // Concave Shape + //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); - // Path - draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f * -0.5f, 3.141592f); - draw_list->PathStroke(col, th, flags); - x += sz + spacing; + draw_list->AddLineH(x, x + sz, y, col, th, flags); // Horizontal line + draw_list->AddLine({ x, y + half_szi }, { x + sz, y + half_szi }, col, th, flags); + x += sz + spacing; - // Quadratic Bezier Curve (3 control points) - draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments, flags); - x += sz + spacing; + draw_list->AddLineV(x, y, y + sz, col, th, flags); // Vertical line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine({ x + half_szi, y + sz }, { x + half_szi, y }, col, th, flags); + x += half_sz + spacing; - // Cubic Bezier Curve (4 control points) - draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments, flags); + if (!(draw_fill && draw_strokes)) //-V560 + draw_list->AddLine({ x, y }, { x + sz, y + sz }, col, th, flags); x += sz + spacing; // Diagonal line - x = p.x + 4; + // Rotating square + for (int n = 0; n < 4; n++) + draw_list->PathLineTo({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }); + draw_list->PathStroke(col, flags | ImDrawFlags_Closed, th); + //for (int n = 0; n < 4; n++) // ...made of individual line + // draw_list->AddLine({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }, { x + half_sz + rotating_square[(n + 1) & 3].x, y + half_sz + rotating_square[(n + 1) & 3].y }, col, th, flags); + x += sz + spacing; + + // Path + draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi); + draw_list->PathStroke(col, th, flags); + x += sz + spacing; + + // Quadratic Bezier Curve (3 control points) + draw_list->AddBezierQuadratic({ x + cp3[0].x, y + cp3[0].y }, { x + cp3[1].x, y + cp3[1].y }, { x + cp3[2].x, y + cp3[2].y }, col, th, curve_segments, flags); + x += sz + spacing; + + // Cubic Bezier Curve (4 control points) + if (!(draw_fill && draw_strokes)) //-V560 + { + draw_list->AddBezierCubic({ x + cp4[0].x, y + cp4[0].y }, { x + cp4[1].x, y + cp4[1].y }, { x + cp4[2].x, y + cp4[2].y }, { x + cp4[3].x, y + cp4[3].y }, col, th, curve_segments, flags); + x += sz + spacing; + } + } y += sz + spacing; } - // Filled shapes - draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, ngon_sides); x += sz + spacing; // N-gon - draw_list->AddCircleFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, circle_segments); x += sz + spacing; // Circle - draw_list->AddEllipseFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), ImVec2(sz * 0.5f, sz * 0.3f), col, -0.3f, circle_segments); x += sz + spacing;// Ellipse - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle - //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle - PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing; // Vertical line (faster than AddLine, but only handle integer thickness) - x += sz + spacing; - x += spacing; - draw_list->AddRectFilled(ImVec2(x + 0, y), ImVec2(x + 0 + 1, y + 1), col); // Pixels (faster than AddLine) - draw_list->AddRectFilled(ImVec2(x + 2, y), ImVec2(x + 2 + 2, y + 2), col); - draw_list->AddRectFilled(ImVec2(x + 5, y), ImVec2(x + 5 + 3, y + 3), col); - x += spacing + sz; - - // Path - draw_list->PathArcTo(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, 3.141592f * -0.5f, 3.141592f); - draw_list->PathFillConvex(col); - x += sz + spacing; - - // Quadratic Bezier Curve (3 control points) - draw_list->PathLineTo(ImVec2(x + cp3[0].x, y + cp3[0].y)); - draw_list->PathBezierQuadraticCurveTo(ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), curve_segments); - draw_list->PathFillConvex(col); - x += sz + spacing; - - draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); - x += sz + spacing; - - ImGui::Dummy(ImVec2((sz + spacing) * 13.2f, (sz + spacing) * 3.0f)); + ImGui::Dummy(ImVec2((sz + spacing) * 15.0f, (sz + spacing) * 4.0f)); ImGui::PopItemFlag(); ImGui::PopItemWidth(); ImGui::EndTabItem(); From e3fb7657ba6c7af876ea1f76a36598f66622004c Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 May 2026 16:50:57 +0200 Subject: [PATCH 073/245] DrawList: renamed ImDrawFlags_StrokeCenterPixelAligned to ImDrawFlags_StrokeCenterAligned. --- imgui.h | 2 +- imgui_demo.cpp | 2 +- imgui_draw.cpp | 28 ++++++++++++++-------------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/imgui.h b/imgui.h index 0a495a688..f17f1888e 100644 --- a/imgui.h +++ b/imgui.h @@ -3335,7 +3335,7 @@ enum ImDrawFlags_ // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline - ImDrawFlags_StrokeCenterPixelAligned = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. + ImDrawFlags_StrokeCenterAligned = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly and NoAAEnds flags. ImDrawFlags_StrokeMask_ = 0x07 << 16, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c3a63ac27..77b005711 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10413,7 +10413,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::RadioButton("Default", &flags, ImDrawFlags_None); ImGui::SameLine(); ImGui::RadioButton("Inside", &flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); ImGui::RadioButton("Center", &flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); - ImGui::RadioButton("CenterPixelAligned", &flags, ImDrawFlags_StrokeCenterPixelAligned); ImGui::SameLine(); + ImGui::RadioButton("CenterAligned", &flags, ImDrawFlags_StrokeCenterAligned); ImGui::SameLine(); ImGui::RadioButton("Outside", &flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); ImGui::RadioButton("Legacy", &flags, ImDrawFlags_StrokeLegacy); ImGui::CheckboxFlags("MiterOnly", &flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 400fe6067..7ed4e695f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -813,12 +813,12 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c } -static float CalculateCenterPixelAlignedOffset(float thickness, float _FringeScale) +static float CalculateCenterAlignedOffset(float thickness, float _FringeScale) { // Old jumpy one. // return IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; - // Calculate outside offset for stroke position CenterPixelAligned + // Calculate outside offset for stroke position CenterAligned // so that one side the of the line is always at pixel boundary. // On integer thickness both sides of the line are on pixel boundary. const float screen_thickness = thickness / _FringeScale; @@ -871,8 +871,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) if (stroke_pos == ImDrawFlags_StrokeOutside) thickness0 = thickness + fringe * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - thickness0 = CalculateCenterPixelAlignedOffset(thickness, _FringeScale) + fringe * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) + thickness0 = CalculateCenterAlignedOffset(thickness, _FringeScale) + fringe * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeInside) thickness0 = fringe * 0.5f; float thickness1 = (thickness + fringe) - thickness0; @@ -2131,8 +2131,8 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th float top_y = y; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) top_y -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - top_y -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) + top_y -= CalculateCenterAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) top_y -= thickness; @@ -2170,8 +2170,8 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th float left_x = x; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) left_x -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - left_x -= CalculateCenterPixelAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) + left_x -= CalculateCenterAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) left_x -= thickness; @@ -2454,8 +2454,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl float offset = 0.0f; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) offset = thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - offset = CalculateCenterPixelAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) + offset = CalculateCenterAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) offset = thickness; outer_min.x -= offset; @@ -2731,8 +2731,8 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - outer_radius = radius + CalculateCenterPixelAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) + outer_radius = radius + CalculateCenterAlignedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2816,8 +2816,8 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + miter_thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterPixelAligned) - outer_radius = radius + CalculateCenterPixelAlignedOffset(miter_thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) + outer_radius = radius + CalculateCenterAlignedOffset(miter_thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) From 4d5fcdd4baddf02754bbc045de409eefd806daac Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 22 May 2026 20:36:19 +0200 Subject: [PATCH 074/245] DrawList: Textured Round Corners: use same array for fill and strokes. Feels like a little less book-keeping. --- imgui.h | 11 +++++------ imgui_demo.cpp | 2 +- imgui_draw.cpp | 22 ++++++++++------------ imgui_internal.h | 3 +-- 4 files changed, 17 insertions(+), 21 deletions(-) diff --git a/imgui.h b/imgui.h index f17f1888e..96cdaf0c9 100644 --- a/imgui.h +++ b/imgui.h @@ -3204,15 +3204,15 @@ struct ImGuiSelectionExternalStorage // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) -#define IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX (128) +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) +#define IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX (128) #endif #ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX -#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) +#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) #endif #ifndef IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX -#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (3) +#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (4) // 0: fill, 1-3: strokes thickness #endif // ImDrawIdx: vertex index. [Compile-time configurable type] @@ -3901,8 +3901,7 @@ struct ImFontAtlas ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines ImVec4 TexUvLineFract; // UVs for fraction thickness baked anti-aliased lines - ImVec4 TexUvCornerFills[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX]; // UVs for baked anti-aliased corners - ImVec4 TexUvCornerStrokes[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners + ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 77b005711..76da3ec53 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10525,7 +10525,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Rotating square for (int n = 0; n < 4; n++) draw_list->PathLineTo({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }); - draw_list->PathStroke(col, flags | ImDrawFlags_Closed, th); + draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); //for (int n = 0; n < 4; n++) // ...made of individual line // draw_list->AddLine({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }, { x + half_sz + rotating_square[(n + 1) & 3].x, y + half_sz + rotating_square[(n + 1) & 3].y }, col, th, flags); x += sz + spacing; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7ed4e695f..f30c378a0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2523,9 +2523,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl // Pixel aligned rect with round corners rendered using baked textures. IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); const int size = ImMax(s_rounding, s_thickness); // This is matching the baking calculations. - const int idx = (s_thickness - 1) * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + s_rounding - 1; + const int idx = (s_thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + s_rounding - 1; IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); - const ImVec4 tex_uvs = _Data->TexUvCornerStrokes[idx]; + const ImVec4 tex_uvs = _Data->TexUvCorners[idx]; _AddRectBaked(outer_min, outer_max, col, (float)size * _FringeScale, (float)thickness, tex_uvs, flags); return; } @@ -2633,9 +2633,9 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c { IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); const int size = ImMax(2, s_rounding); // This is matching the baking calculations. - const int idx = s_rounding - 1; + const int idx = (s_rounding - 1); IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); - ImVec4 tex_uvs = _Data->TexUvCornerFills[idx]; + ImVec4 tex_uvs = _Data->TexUvCorners[idx]; _AddRectFilledBaked(p_min, p_max, col, (float)size * _FringeScale, tex_uvs, flags); } else @@ -4867,13 +4867,13 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) pack_size.x = ImMax(pack_size.x, row_width); pack_size.y += row_height; // Rounded corners - for (int t = 0; t < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; t++) + for (int thickness = 1; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) { row_width = 0; row_height = 0; for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) { - const int size = ImMax(2, ImMax(i+1, t+1)) + 2; + const int size = ImMax(2, ImMax(i + 1, thickness)) + 2; row_width += size; row_height = ImMax(row_height, size); } @@ -4929,7 +4929,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; - atlas->TexUvCornerFills[n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + atlas->TexUvCorners[n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); x += w; row_height = ImMax(row_height, h); @@ -4937,14 +4937,13 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) y += row_height; // Stroked - for (int t = 0; t < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; t++) + for (int thickness = 1; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) { x = r.x; row_height = 0; for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) { const int rounding = n+1; - const int thickness = t+1; const int s = ImMax(rounding, thickness); const int w = s + 2; const int h = s + 2; @@ -4984,7 +4983,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; - atlas->TexUvCornerStrokes[t*IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + atlas->TexUvCorners[thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); x += w; row_height = ImMax(row_height, h); @@ -5467,8 +5466,7 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; shared_data->TexUvLines = atlas->TexUvLines; shared_data->TexUvLineFract = atlas->TexUvLineFract; - shared_data->TexUvCornerFills = atlas->TexUvCornerFills; - shared_data->TexUvCornerStrokes = atlas->TexUvCornerStrokes; + shared_data->TexUvCorners = atlas->TexUvCorners; } } diff --git a/imgui_internal.h b/imgui_internal.h index 5d63fe902..fb8e37441 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -926,8 +926,7 @@ struct IMGUI_API ImDrawListSharedData ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) ImVec4 TexUvLineFract; // UV of fractional anti-aliased lines in the atlas (== FontAtlas->TexUvLineFract) - const ImVec4* TexUvCornerFills; // UV of rounded corner (== FontAtlas->TexUvCornerFills) - const ImVec4* TexUvCornerStrokes; + const ImVec4* TexUvCorners; // UV of rounded corner (== FontAtlas->TexUvCorners) ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current font (used for simplified AddText overload) float FontSize; // Current font size (used for simplified AddText overload) From 81f316a3bf566c651944f3226500746fe464525f Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 25 May 2026 10:40:13 +0300 Subject: [PATCH 075/245] DrawList: fixed and optimized _AddRectTinyRounding. - fixed bug where fringe size was not properly applied in _AddRectTinyRounding - optimized _AddRectTinyRounding to use less vertices - changed _AddRectTinyRounding to use similar texturing logic as lines - remove unused fractional line width texture --- imgui.h | 2 - imgui_draw.cpp | 143 ++++++++++++++++++++--------------------------- imgui_internal.h | 1 - 3 files changed, 62 insertions(+), 84 deletions(-) diff --git a/imgui.h b/imgui.h index 96cdaf0c9..dbecdca92 100644 --- a/imgui.h +++ b/imgui.h @@ -3205,7 +3205,6 @@ struct ImGuiSelectionExternalStorage // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX #define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) -#define IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX (128) #endif #ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX @@ -3900,7 +3899,6 @@ struct ImFontAtlas ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines - ImVec4 TexUvLineFract; // UVs for fraction thickness baked anti-aliased lines ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f30c378a0..3ea9192eb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2316,96 +2316,116 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c // The stroke is positioned inside the rectangle. void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { - // Note: this is smaller than in AddPolyline(), since the stem offset can be biased all the way to one side. - const float max_width = IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX * _FringeScale; - thickness = ImMin(thickness, max_width); + float screen_thickness = thickness / _FringeScale; + if (screen_thickness < 1.0f / 255.0f) + return; + if (screen_thickness < 1.0f) + { + col = ImAlphaMultiply(col, screen_thickness); + screen_thickness = 1.0f; + thickness = _FringeScale; + } - thickness += _FringeScale; + // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. + const int texture_idx = ImClamp((int)(screen_thickness + 0.95f), 1, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + const float fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. + const ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(rounding), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; - int vtx_count = (4 + arc_point_count) * 4 + 4; + int vtx_count = (4 + arc_point_count) * 3 + 3; int idx_count = (4 + arc_point_count - 1) * 4 * 3; PrimReserve(idx_count, vtx_count); ImDrawVert* start_vtx_ptr = _VtxWritePtr; ImDrawIdx* start_idx_ptr = _IdxWritePtr; - const ImVec2 corner_pos[4] = { - ImVec2(p_min.x, p_min.y), - ImVec2(p_max.x, p_min.y), - ImVec2(p_max.x, p_max.y), - ImVec2(p_min.x, p_max.y) - }; static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; static const ImDrawFlags corner_flags[4] = { ImDrawFlags_RoundCornersTopLeft, ImDrawFlags_RoundCornersTopRight, ImDrawFlags_RoundCornersBottomRight, ImDrawFlags_RoundCornersBottomLeft }; + const float half_fringe = fringe * 0.5f; + const ImVec2 corner_pos[4] = { + ImVec2(p_min.x - half_fringe, p_min.y - half_fringe), + ImVec2(p_max.x + half_fringe, p_min.y - half_fringe), + ImVec2(p_max.x + half_fringe, p_max.y + half_fringe), + ImVec2(p_min.x - half_fringe, p_max.y + half_fringe) + }; + thickness += fringe; + rounding += half_fringe; + // We need to stem offset to be atleast fringe scale away, to maintain the fringe size. const float stem_offset = thickness - ImMax(thickness - rounding, _FringeScale); - const ImVec4 tex_uvs = _Data->TexUvLineFract; // TODO: max uv - const ImVec2 outer_uv0(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); - const ImVec2 outer_uv1(tex_uvs.x + ((0.5f + stem_offset) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); - const ImVec2 inner_uv0(tex_uvs.x + (0.5f / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); - const ImVec2 inner_uv1(tex_uvs.x + ((0.5f + thickness - stem_offset) / _FringeScale) * _Data->FontAtlas->TexUvScale.x, tex_uvs.y); + const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; + const float ratio = stem_offset / thickness; + ImVec2 inner_uv, outer_uv, stem_uv; + inner_uv.x = tex_uvs.x + half_texel; + inner_uv.y = tex_uvs.y; + outer_uv.x = tex_uvs.z - half_texel; + outer_uv.y = tex_uvs.y; + stem_uv.x = inner_uv.x + (outer_uv.x - inner_uv.x) * ratio; + stem_uv.y = tex_uvs.y; + // Previous vertices, copied from the last vertices. int base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(0, 0, outer_uv0, col); - IM_APPEND_VTX(0, 0, outer_uv1, col); - IM_APPEND_VTX(0, 0, inner_uv1, col); - IM_APPEND_VTX(0, 0, inner_uv0, col); + IM_APPEND_VTX(0, 0, inner_uv, col); + IM_APPEND_VTX(0, 0, stem_uv, col); + IM_APPEND_VTX(0, 0, outer_uv, col); + + ImVec2 outer, stem, inner, center; for (int corner = 0; corner < 4; corner++) { - const ImVec2 stem = corner_pos[corner] + corner_offset[corner] * stem_offset; - const ImVec2 inner = corner_pos[corner] + corner_offset[corner] * thickness; + outer = corner_pos[corner]; + stem.x = corner_pos[corner].x + corner_offset[corner].x * stem_offset; + stem.y = corner_pos[corner].y + corner_offset[corner].y * stem_offset; + inner.x = corner_pos[corner].x + corner_offset[corner].x * thickness; + inner.y = corner_pos[corner].y + corner_offset[corner].y * thickness; + const bool is_rounded = flags & corner_flags[corner]; const int arc_idx = (int)_VtxCurrentIdx; if (is_rounded) { - const ImVec2 center = corner_pos[corner] + corner_offset[corner] * rounding; + center.x = outer.x + corner_offset[corner].x * rounding; + center.y = outer.y + corner_offset[corner].y * rounding; int a = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) * corner; for (int i = 0; i < arc_point_count; i++) { - const ImVec2 dir = _Data->ArcFastVtx[a]; - IM_APPEND_VTX(center.x - dir.x * rounding, center.y - dir.y * rounding, outer_uv0, col); + IM_APPEND_VTX(center.x - _Data->ArcFastVtx[a].x * rounding, center.y - _Data->ArcFastVtx[a].y * rounding, inner_uv, col); a = (a + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; } } else { - IM_APPEND_VTX(corner_pos[corner].x, corner_pos[corner].y, outer_uv0, col); + IM_APPEND_VTX(outer.x, outer.y, inner_uv, col); } - const int stem0_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(stem.x, stem.y, outer_uv1, col); - const int stem1_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(stem.x, stem.y, inner_uv1, col); + const int stem_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(stem.x, stem.y, stem_uv, col); const int inner_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(inner.x, inner.y, inner_uv0, col); + IM_APPEND_VTX(inner.x, inner.y, outer_uv, col); // Arc if (is_rounded) { - for (int i = 0; i < arc_point_count-1; i++) - IM_APPEND_TRI(stem0_idx, arc_idx + i, arc_idx + i + 1); + for (int i = 0; i < arc_point_count - 1; i++) + IM_APPEND_TRI(stem_idx, arc_idx + i, arc_idx + i + 1); } // Connect with previous - IM_APPEND_TRI(base_idx + 0, arc_idx, stem0_idx); - IM_APPEND_TRI(base_idx + 0, stem0_idx, base_idx + 1); - IM_APPEND_TRI(base_idx + 2, stem1_idx, inner_idx); - IM_APPEND_TRI(base_idx + 2, inner_idx, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, arc_idx, stem_idx); + IM_APPEND_TRI(base_idx + 0, stem_idx, base_idx + 1); + IM_APPEND_TRI(base_idx + 1, stem_idx, inner_idx); + IM_APPEND_TRI(base_idx + 1, inner_idx, base_idx + 2); - base_idx = stem0_idx - 1; + base_idx = stem_idx - 1; } // Close - start_vtx_ptr[0] = VtxBuffer.Data[base_idx+0]; - start_vtx_ptr[1] = VtxBuffer.Data[base_idx+1]; - start_vtx_ptr[2] = VtxBuffer.Data[base_idx+2]; - start_vtx_ptr[3] = VtxBuffer.Data[base_idx+3]; + start_vtx_ptr[0] = VtxBuffer.Data[base_idx + 0]; + start_vtx_ptr[1] = VtxBuffer.Data[base_idx + 1]; + start_vtx_ptr[2] = VtxBuffer.Data[base_idx + 2]; const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); @@ -5054,44 +5074,6 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } - - // Single larger line for fraction width textured lines. - // Alternative solution could be to fix while and black pixel next to the texture border - // and use the texture clamping to expand the opaque pixel. - // : - // [*][ ] - // : - // <-- width would expand out of the texture expanding the while pixel to as far as needed. - add_and_draw = atlas->GetCustomRect(builder->PackIdLineFractTexData, &r) == false; - if (add_and_draw) - { - ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX + 1, 1); - builder->PackIdLineFractTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); - IM_ASSERT(builder->PackIdLineFractTexData != ImFontAtlasRectId_Invalid); - } - - // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle - // Write each slice - if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) - { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y); - *write_ptr++ = 0x00; - for (int i = 0; i < IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX; i++) - *write_ptr++ = 0xFF; - } - else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) - { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y); - *write_ptr++ = IM_COL32(255, 255, 255, 0); - for (int i = 0; i < IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX; i++) - *write_ptr++ = IM_COL32_WHITE; - } - - // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)r.x, (float)r.y) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)r.x + 1.0f + IM_DRAWLIST_TEX_LINE_FRACT_WIDTH_MAX, (float)r.y) * atlas->TexUvScale; - float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - atlas->TexUvLineFract = ImVec4(uv0.x, half_v, uv1.x, half_v); } //----------------------------------------------------------------------------------------------------------------------------- @@ -5465,7 +5447,6 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) { shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; shared_data->TexUvLines = atlas->TexUvLines; - shared_data->TexUvLineFract = atlas->TexUvLineFract; shared_data->TexUvCorners = atlas->TexUvCorners; } } diff --git a/imgui_internal.h b/imgui_internal.h index fb8e37441..d632533f3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -925,7 +925,6 @@ struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) - ImVec4 TexUvLineFract; // UV of fractional anti-aliased lines in the atlas (== FontAtlas->TexUvLineFract) const ImVec4* TexUvCorners; // UV of rounded corner (== FontAtlas->TexUvCorners) ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current font (used for simplified AddText overload) From 3f7da1e184334b5210bb81c05b230b1a521bac67 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 26 May 2026 15:48:28 +0300 Subject: [PATCH 076/245] DrawList: improved shape drawing input validation for thin shapes and small thickness. --- imgui_draw.cpp | 82 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 76 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3ea9192eb..3812880d3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2138,6 +2138,16 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if (_FringeScaleIsInteger && ImIsTruncated4(min_x, max_x, top_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) { + float screen_thickness = thickness / _FringeScale; + if (screen_thickness < 1.f / 255.f) + return; + if (screen_thickness < 1.f) + { + col = ImAlphaMultiply(col, screen_thickness); + screen_thickness = 1.f; + thickness = _FringeScale; + } + // For pixel aligned case, use simple rectangle. PrimReserve(6, 4); PrimRect(ImVec2(min_x, top_y), ImVec2(max_x, top_y + thickness), col); @@ -2177,6 +2187,16 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if (_FringeScaleIsInteger && ImIsTruncated4(left_x, min_y, max_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) { + float screen_thickness = thickness / _FringeScale; + if (screen_thickness < 1.f / 255.f) + return; + if (screen_thickness < 1.f) + { + col = ImAlphaMultiply(col, screen_thickness); + screen_thickness = 1.f; + thickness = _FringeScale; + } + // For pixel aligned case, use simple rectangle. PrimReserve(6, 4); PrimRect(ImVec2(left_x, min_y), ImVec2(left_x + thickness, max_y), col); @@ -2506,6 +2526,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl { int s_rounding = (int)(outer_rounding / _FringeScale); int s_thickness = (int)(thickness / _FringeScale); + if (s_thickness <= 0) + return; if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { @@ -2634,14 +2656,35 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if ((col & IM_COL32_A_MASK) == 0) return; + ImVec2 b_min = p_min; + ImVec2 b_max = p_max; + const float width = b_max.x - b_min.x; + const float height = b_max.y - b_min.y; + + const float inv_fringe_scale = 1.f / _FringeScale; + const float screen_width = width * inv_fringe_scale; + const float screen_height = height * inv_fringe_scale; + + if (ImMin(screen_width, screen_height) < 1.f / 255.f) + return; + if (screen_width < 1.f) + { + col = ImAlphaMultiply(col, screen_width); + b_max.x = b_min.x + _FringeScale; + } + if (screen_height < 1.f) + { + col = ImAlphaMultiply(col, screen_height); + b_max.y = b_min.y + _FringeScale; + } + if (ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated(rounding)) { if ((flags & ImDrawFlags_RoundCornersMask_) == 0) flags |= ImDrawFlags_RoundCornersAll; - rounding = ImMin(rounding, ImFabs(p_max.x - p_min.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); - rounding = ImMin(rounding, ImFabs(p_max.y - p_min.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - + rounding = ImMin(rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); const int s_rounding = (int)(rounding / _FringeScale); if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) @@ -2738,7 +2781,7 @@ void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImV void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) { - if ((col & IM_COL32_A_MASK) == 0 || radius < 0.01f) + if ((col & IM_COL32_A_MASK) == 0) return; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); @@ -2748,6 +2791,8 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu stroke_pos = ImDrawFlags_StrokeCenter; } + radius = ImMax(0.01f, radius); + float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + thickness * 0.5f; @@ -2830,6 +2875,8 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ stroke_pos = ImDrawFlags_StrokeCenter; } + radius = ImMax(0.01f, radius); + const float unit_apothem = ImCos(IM_PI / (float)num_segments); const float miter_thickness = thickness / unit_apothem; @@ -2889,14 +2936,18 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co stroke_pos = ImDrawFlags_StrokeCenter; } + ImVec2 rad = radius; + rad.x = ImMax(0.01f, rad.x); + rad.y = ImMax(0.01f, rad.y); + if (num_segments <= 0) - num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. + num_segments = _CalcCircleAutoSegmentCount(ImMax(rad.x, rad.y)); // A bit pessimistic, maybe there's a better computation to do here. _Path.reserve(_Path.Size + (num_segments + 1)); // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; - PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1); + PathEllipticalArcTo(center, rad, rot, 0.0f, a_max, num_segments - 1); PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos); } @@ -2905,6 +2956,25 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im if ((col & IM_COL32_A_MASK) == 0) return; + ImVec2 rad = radius; + + const float inv_fringe_scale = 1.f / _FringeScale; + float screen_diameter_x = rad.x* 2.f * inv_fringe_scale; + float screen_diameter_y = rad.y * 2.f * inv_fringe_scale; + if (screen_diameter_x < 1.f / 255.f || screen_diameter_y < 1.f / 255.f) + return; + + if (screen_diameter_x < 1.f) + { + col = ImAlphaMultiply(col, screen_diameter_x); + rad.x = _FringeScale * 0.5f; + } + if (screen_diameter_y < 1.f) + { + col = ImAlphaMultiply(col, screen_diameter_y); + rad.y = _FringeScale * 0.5f; + } + if (num_segments <= 0) num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. From 91e769fbba0cab2f3fdd4632d6f83d6dee69c8d1 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 26 May 2026 15:52:59 +0300 Subject: [PATCH 077/245] DrawList: fixed visual pop in stroke rendering when thickness is between 1 and 2 pixels. - added animated thickness to demo to make it easier to evaluate thickness visual progression - added super sampled textures in thickness range [1..3] to avoid visual pop --- imgui.h | 7 ++- imgui_demo.cpp | 20 ++++-- imgui_draw.cpp | 165 ++++++++++++++++++++++++++++++++++++------------- 3 files changed, 142 insertions(+), 50 deletions(-) diff --git a/imgui.h b/imgui.h index dbecdca92..5c2833141 100644 --- a/imgui.h +++ b/imgui.h @@ -3207,6 +3207,10 @@ struct ImGuiSelectionExternalStorage #define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) #endif +#ifndef IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX +#define IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX (2) // How many samples for lines between [1..2) thickness. +#endif + #ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX #define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) #endif @@ -3537,6 +3541,7 @@ struct ImDrawList IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); IMGUI_API void _AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs, float fringe); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); + IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4& tex_uvs, float& fringe); }; // All draw data to render a Dear ImGui frame @@ -3898,7 +3903,7 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 1]; // UVs for baked anti-aliased lines ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 76da3ec53..bd99567e3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10388,17 +10388,25 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Draw a bunch of primitives ImGui::Text("All primitives"); static float sz = 42.0f; - static float thickness = 3.0f; - static int ngon_sides = 6; + static bool animate_thickness = false; + static float base_thickness = 3.0f; + static int ngon_segments = 6; static bool circle_segments_override = false; static int circle_segments_override_v = 12; static bool curve_segments_override = false; static int curve_segments_override_v = 8; static ImVec4 colf_stroke = ImVec4(1.00f, 1.00f, 0.40f, 1.0f); static ImVec4 colf_fill = ImVec4(0.70f, 0.18f, 0.62f, 1.0f); + const float thickness_anim_period = 5.f; + float thickness_wave = 1.0f - fabs(fmod((float)ImGui::GetTime(), thickness_anim_period) * (2.0f / thickness_anim_period) - 1.0f); + float thickness = animate_thickness ? thickness_wave * base_thickness : base_thickness; + ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); - ImGui::DragFloat("Thickness", &thickness, 0.1f, 0.0f, 30.0f, "%.02f"); - ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); + ImGui::DragFloat("Thickness", &base_thickness, 0.1f, 0.0f, 30.0f, "%.02f"); + ImGui::Checkbox("Animate Thickness", &animate_thickness); + ImGui::SameLine(); + ImGui::Text("%.2f", thickness); + ImGui::SliderInt("N-gon sides", &ngon_segments, 3, 12); ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 40); @@ -10450,7 +10458,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) { // FILLED SHAPES const ImU32 col = ImColor(colf_fill); - draw_list->AddNgonFilled({ x + half_sz, y + half_sz }, half_sz, col, ngon_sides); x += sz + spacing; // N-gon + draw_list->AddNgonFilled({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments); x += sz + spacing; // N-gon draw_list->AddCircleFilled({ x + half_sz, y + half_sz }, half_sz, col, circle_segments); x += sz + spacing; // Circle draw_list->AddEllipseFilled({ x + half_sz, y + half_sz }, { sz * 0.5f, sz * 0.3f }, col, -0.3f, circle_segments); x += sz + spacing;// Ellipse draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col); x += sz + spacing; // Square @@ -10500,7 +10508,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) // First row uses a thickness of 1.0f, second row uses the configurable thickness const ImU32 col = ImColor(colf_stroke); float th = (row == 0) ? 1.0f : thickness; - draw_list->AddNgon({ x + half_sz, y + half_sz }, half_sz, col, ngon_sides, th, flags); x += sz + spacing; // N-gon + draw_list->AddNgon({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments, th, flags); x += sz + spacing; // N-gon draw_list->AddCircle({ x + half_sz, y + half_sz }, half_sz, col, circle_segments, th, flags); x += sz + spacing; // Circle draw_list->AddEllipse({ x + half_sz, y + half_sz }, { sz * 0.5f, sz * 0.3f }, col, -0.3f, circle_segments, th, flags); x += sz + spacing; // Ellipse draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, 0.0f, th, flags); x += sz + spacing; // Square diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3812880d3..d86534984 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1181,6 +1181,27 @@ static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } +void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4& tex_uvs, float& fringe) +{ + if (screen_thickness <= 2.f) + { + // Handle the thickness between [1..2]. The texture scaling in this range will cause visual pop near 1, so we generate super sampled textures in this range. + // There IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX maps 2.0. + constexpr float base_width = 1.f; + const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 0.5f), 0, IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX); + const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; + fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. + tex_uvs = _Data->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + texture_idx]; + } + else + { + // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. + const int texture_idx = ImClamp((int)(screen_thickness + 0.95f), 1, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. + tex_uvs = _Data->TexUvLines[texture_idx]; + } +} + extern bool g_LEGACY_STROKES; void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) @@ -1238,10 +1259,9 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 sqr_lengths[points_count - 1] = 0.0f; } - // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. - const int texture_idx = ImClamp((int)(screen_thickness + 0.95f), 1, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - const float fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. - const ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; + ImVec4 tex_uvs; + float fringe; + _SelectFringeTexture(screen_thickness, tex_uvs, fringe); _AddPolyline(points, normals, sqr_lengths, points_count, col, thickness, flags, tex_uvs, fringe); } @@ -2346,10 +2366,9 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, thickness = _FringeScale; } - // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. - const int texture_idx = ImClamp((int)(screen_thickness + 0.95f), 1, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - const float fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. - const ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; + ImVec4 tex_uvs; + float fringe; + _SelectFringeTexture(screen_thickness, tex_uvs, fringe); const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(rounding), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; @@ -5095,54 +5114,114 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false; if (add_and_draw) { - ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 1); builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid); } - // Register texture region for thick lines - // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row - // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them - for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { - // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle - const int y = n; - const int line_width = n; - const int pad_left = (r.w - line_width) / 2; - const int pad_right = r.w - (pad_left + line_width); - IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels - - // Write each slice - if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row + // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = 0x00; + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + const int y = n; + const int line_width = n; + const int pad_left = (r.w - line_width) / 2; + const int pad_right = r.w - (pad_left + line_width); + IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = 0xFF; + // Write each slice + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) + { + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = 0x00; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = 0x00; + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = 0xFF; + + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = 0x00; + } + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = IM_COL32(255, 255, 255, 0); + + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = IM_COL32_WHITE; + + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); + } + + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } - else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + } + + { + + ImU8 ramp[IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX]; + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; n++) + ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX) * 255.f); + + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 1; n++) { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = IM_COL32(255, 255, 255, 0); + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + const int y = IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n; + const int line_width = IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + n; + IM_ASSERT(IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + line_width + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX <= r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = IM_COL32_WHITE; + // Write each slice + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) + { + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); + int idx = 0; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); + for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; i++) + write_ptr[idx++] = ramp[i]; + + for (int i = 0; i < line_width; i++) + write_ptr[idx++] = 0xFF; + + for (int i = IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX-1; i >= 0; i--) + write_ptr[idx++] = ramp[i]; + + while (idx < r.w) + write_ptr[idx++] = 0x0; + } + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) + { + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); + + int idx = 0; + + for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; i++) + write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); + + for (int i = 0; i < line_width; i++) + write_ptr[idx++] = IM_COL32(255, 255, 255, 255); + + for (int i = IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX - 1; i >= 0; i--) + write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); + + while (idx < r.w) + write_ptr[idx++] = IM_COL32(255, 255, 255, 0); + } + + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } - - // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; - float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } From 6f00e0b39f8f4376bf005ab412bed272b563c379 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 May 2026 16:25:55 +0200 Subject: [PATCH 078/245] Demo: fixed using Miter/Square/NoAAends checkboxes interfering with stroke mode. warnings. Demo: update "Lines" demo to help diagnose brightness change. --- imgui_demo.cpp | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bd99567e3..0d7d1df64 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10397,15 +10397,18 @@ static void ShowExampleAppCustomRendering(bool* p_open) static int curve_segments_override_v = 8; static ImVec4 colf_stroke = ImVec4(1.00f, 1.00f, 0.40f, 1.0f); static ImVec4 colf_fill = ImVec4(0.70f, 0.18f, 0.62f, 1.0f); - const float thickness_anim_period = 5.f; - float thickness_wave = 1.0f - fabs(fmod((float)ImGui::GetTime(), thickness_anim_period) * (2.0f / thickness_anim_period) - 1.0f); - float thickness = animate_thickness ? thickness_wave * base_thickness : base_thickness; ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); - ImGui::DragFloat("Thickness", &base_thickness, 0.1f, 0.0f, 30.0f, "%.02f"); - ImGui::Checkbox("Animate Thickness", &animate_thickness); + + const float thickness_anim_period = 5.f; + const float thickness_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), thickness_anim_period) * (2.0f / thickness_anim_period) - 1.0f); + const float thickness = animate_thickness ? thickness_wave * base_thickness : base_thickness; + ImGui::DragFloat("Thickness", &base_thickness, 0.02f, 0.0f, 30.0f, "%.02f"); + ImGui::SameLine(); + ImGui::Checkbox("Animate", &animate_thickness); ImGui::SameLine(); ImGui::Text("%.2f", thickness); + ImGui::SliderInt("N-gon sides", &ngon_segments, 3, 12); ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); @@ -10416,18 +10419,20 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::ColorEdit4("Stroke Color", &colf_stroke.x); ImGui::ColorEdit4("Fill Color", &colf_fill.x); - static ImDrawFlags flags = ImDrawFlags_None; + static ImDrawFlags stroke_flags = ImDrawFlags_None; + static ImDrawFlags other_flags = ImDrawFlags_None; ImGui::Text("Stroke Flags:"); - ImGui::RadioButton("Default", &flags, ImDrawFlags_None); ImGui::SameLine(); - ImGui::RadioButton("Inside", &flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); - ImGui::RadioButton("Center", &flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); - ImGui::RadioButton("CenterAligned", &flags, ImDrawFlags_StrokeCenterAligned); ImGui::SameLine(); - ImGui::RadioButton("Outside", &flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); - ImGui::RadioButton("Legacy", &flags, ImDrawFlags_StrokeLegacy); - ImGui::CheckboxFlags("MiterOnly", &flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); - ImGui::CheckboxFlags("SquareCap", &flags, ImDrawFlags_SquareCap); ImGui::SameLine(); - ImGui::CheckboxFlags("NoAAEnds", &flags, ImDrawFlags_NoAAEnds); + ImGui::RadioButton("Default", &stroke_flags, ImDrawFlags_None); ImGui::SameLine(); + ImGui::RadioButton("Inside", &stroke_flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); + ImGui::RadioButton("Center", &stroke_flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); + ImGui::RadioButton("CenterAligned", &stroke_flags, ImDrawFlags_StrokeCenterAligned); ImGui::SameLine(); + ImGui::RadioButton("Outside", &stroke_flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); + ImGui::RadioButton("Legacy", &stroke_flags, ImDrawFlags_StrokeLegacy); + ImGui::CheckboxFlags("MiterOnly", &other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); + ImGui::CheckboxFlags("SquareCap", &other_flags, ImDrawFlags_SquareCap); ImGui::SameLine(); + ImGui::CheckboxFlags("NoAAEnds", &other_flags, ImDrawFlags_NoAAEnds); ImGui::Spacing(); + const ImDrawFlags flags = stroke_flags | other_flags; ImVec2 start_pos = ImGui::GetCursorScreenPos(); const float pi = 3.141592f; From 9f5bfdf83b518af09efc34cd34517ced505ec2db Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 May 2026 16:26:14 +0200 Subject: [PATCH 079/245] DrawList: AddQuad() defaults to ImDrawFlags_StrokeInside. --- imgui_draw.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d86534984..dd22954da 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2755,6 +2755,8 @@ void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, c if ((col & IM_COL32_A_MASK) == 0) return; + ImDrawFlags stroke_pos = g_LEGACY_STROKES ? ImDrawFlags_StrokeLegacy : _GetStrokePos(flags, ImDrawFlags_StrokeInside); + flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; PathLineTo(p1); PathLineTo(p2); PathLineTo(p3); From 90e45bdde028ef9677d88b5dc9ec7b8338a72e5c Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 26 May 2026 17:37:50 +0300 Subject: [PATCH 080/245] DrawList: extend the detailed stroke textures up stroke thickness 4. --- imgui.h | 12 +++++++++--- imgui_draw.cpp | 34 +++++++++++++++++----------------- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/imgui.h b/imgui.h index 5c2833141..527147137 100644 --- a/imgui.h +++ b/imgui.h @@ -3207,10 +3207,16 @@ struct ImGuiSelectionExternalStorage #define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) #endif -#ifndef IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX -#define IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX (2) // How many samples for lines between [1..2) thickness. +#ifndef IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] #endif +#ifndef IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT +#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (2) // How many samples per integer thickness level. +#endif + +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX (IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) + #ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX #define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) #endif @@ -3903,7 +3909,7 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 1]; // UVs for baked anti-aliased lines + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dd22954da..944bcf6a4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1185,18 +1185,18 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4& tex_uvs, f { if (screen_thickness <= 2.f) { - // Handle the thickness between [1..2]. The texture scaling in this range will cause visual pop near 1, so we generate super sampled textures in this range. - // There IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX maps 2.0. + // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. The texture scaling in this range will cause slight visual pops, so we generate super sampled textures in this range. + // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH. constexpr float base_width = 1.f; - const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 0.5f), 0, IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX); - const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; + const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.995f), 0, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); + const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. tex_uvs = _Data->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + texture_idx]; } else { // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. - const int texture_idx = ImClamp((int)(screen_thickness + 0.95f), 1, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + const int texture_idx = ImClamp((int)(screen_thickness + 0.995f), 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. tex_uvs = _Data->TexUvLines[texture_idx]; } @@ -5116,7 +5116,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false; if (add_and_draw) { - ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 1); + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1); builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid); } @@ -5170,16 +5170,16 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) { - ImU8 ramp[IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX]; - for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; n++) - ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX) * 255.f); + ImU8 ramp[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]; + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; n++) + ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.f); - for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + 1; n++) + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1; n++) { // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle const int y = IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n; - const int line_width = IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + n; - IM_ASSERT(IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX + line_width + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX <= r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels + const int line_width = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + n; + IM_ASSERT(IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + line_width + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT <= r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels // Write each slice if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) @@ -5187,13 +5187,13 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); int idx = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; i++) + for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; i++) write_ptr[idx++] = ramp[i]; for (int i = 0; i < line_width; i++) write_ptr[idx++] = 0xFF; - for (int i = IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX-1; i >= 0; i--) + for (int i = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT - 1; i >= 0; i--) write_ptr[idx++] = ramp[i]; while (idx < r.w) @@ -5205,13 +5205,13 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) int idx = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX; i++) + for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; i++) write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); for (int i = 0; i < line_width; i++) write_ptr[idx++] = IM_COL32(255, 255, 255, 255); - for (int i = IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX - 1; i >= 0; i--) + for (int i = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT - 1; i >= 0; i--) write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); while (idx < r.w) @@ -5220,7 +5220,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r.x + IM_DRAWLIST_TEX_LINES_SUPERSAMPLE_MAX * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } From ed8ed8bb714c7dc9fbd3e7b4e8d0f0ff053ec299 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 26 May 2026 22:10:25 +0300 Subject: [PATCH 081/245] DrawList: fixed thin lines appearing too bright. - fixed how super sampled line textures are generated (and documented wrong assumption) - switched to more samples and smaller thickness range - tweaked super sampled texture selection to hide the texture changed better --- imgui.h | 4 ++-- imgui_draw.cpp | 19 ++++++++++++++----- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 527147137..bfad43218 100644 --- a/imgui.h +++ b/imgui.h @@ -3208,11 +3208,11 @@ struct ImGuiSelectionExternalStorage #endif #ifndef IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (3) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] #endif #ifndef IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT -#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (2) // How many samples per integer thickness level. +#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (4) // How many samples per integer thickness level. #endif #define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX (IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 944bcf6a4..1e74198da 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1183,15 +1183,15 @@ static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4& tex_uvs, float& fringe) { - if (screen_thickness <= 2.f) + if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) { // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. The texture scaling in this range will cause slight visual pops, so we generate super sampled textures in this range. // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH. constexpr float base_width = 1.f; - const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.995f), 0, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); + const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f), 0, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. - tex_uvs = _Data->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + texture_idx]; + tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; } else { @@ -5176,9 +5176,18 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) for (int n = 0; n < IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1; n++) { - // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle const int y = IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n; - const int line_width = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + n; + // For integer thickness lines the one pixel line texture looks like this: + // [ 0 | 1 | 0 ] + // :...........: + // Since the texture samples are at the center of the texel, we only use range above. + // The result after bilinear filtering is a triangle across the used uv range. + // + // To super 2x sample that signal, we end up with following texture: + // [ 0 | .5 | 1 | .5 | 0 ] + // :.......................: + // One might think that there should be 2 opaque pixels the the middle section, but no singe we're super sampling the triangle signal. + const int line_width = 1 + n; IM_ASSERT(IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + line_width + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT <= r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels // Write each slice From d453a59b9c07d2d848802d854a246c2f128f7312 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 May 2026 21:05:00 +0200 Subject: [PATCH 082/245] DrawList: avoid using output references in _SelectFringeTexture() + misc tweaks, comments. Matching coding style and more consistent for matching with other languages. --- imgui.h | 14 +++++++------- imgui_demo.cpp | 3 ++- imgui_draw.cpp | 29 ++++++++++++++--------------- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/imgui.h b/imgui.h index bfad43218..3d111504d 100644 --- a/imgui.h +++ b/imgui.h @@ -3343,8 +3343,8 @@ enum ImDrawFlags_ // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) - ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline - ImDrawFlags_StrokeCenterAligned = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. + ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) + ImDrawFlags_StrokeCenterAligned = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. Does not animate well! ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly and NoAAEnds flags. ImDrawFlags_StrokeMask_ = 0x07 << 16, @@ -3362,7 +3362,7 @@ enum ImDrawListFlags_ ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. ImDrawListFlags_TextNoPixelSnap = 1 << 4, // Disable automatically snapping AddText() calls to pixel boundaries. - ImDrawListFlags_RoundCornersUseTex = 1 << 5, // Enable using textures instead of strokes to draw rounded corners/circles where possible. + ImDrawListFlags_RoundCornersUseTex = 1 << 5, // Enable using textures instead of strokes to draw rounded corners/circles where possible. Set when `ImFontAtlasFlags_NoBakedRoundCorners` is enabled in the font atlas. }; // Draw command list @@ -3543,11 +3543,11 @@ struct ImDrawList IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); - IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs, float fringe); + IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, const ImVec4& tex_uvs, ImDrawFlags flags); + IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags); + IMGUI_API void _AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); - IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4& tex_uvs, float& fringe); + IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0d7d1df64..89ce2a3be 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10533,7 +10533,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) x += half_sz + spacing; if (!(draw_fill && draw_strokes)) //-V560 - draw_list->AddLine({ x, y }, { x + sz, y + sz }, col, th, flags); x += sz + spacing; // Diagonal line + draw_list->AddLine({ x, y }, { x + sz, y + sz }, col, th, flags); // Diagonal line + x += sz + spacing; // Rotating square for (int n = 0; n < 4; n++) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1e74198da..41eb2abd8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -856,7 +856,7 @@ static float CalculateCenterAlignedOffset(float thickness, float _FringeScale) #define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) #define IM_POLYLINE_MITER_LIMIT (4.0f) -void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, ImVec4 tex_uvs, float fringe) +void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe) { const ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -1181,7 +1181,7 @@ static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } -void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4& tex_uvs, float& fringe) +void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe) { if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) { @@ -1190,15 +1190,15 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4& tex_uvs, f constexpr float base_width = 1.f; const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f), 0, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; - fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. - tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; + *out_fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. + *out_tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; } else { // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. const int texture_idx = ImClamp((int)(screen_thickness + 0.995f), 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. - tex_uvs = _Data->TexUvLines[texture_idx]; + *out_fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. + *out_tex_uvs = _Data->TexUvLines[texture_idx]; } } @@ -1261,8 +1261,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 ImVec4 tex_uvs; float fringe; - _SelectFringeTexture(screen_thickness, tex_uvs, fringe); - + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); _AddPolyline(points, normals, sqr_lengths, points_count, col, thickness, flags, tex_uvs, fringe); } @@ -2234,7 +2233,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th } } -void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, ImVec4 tex_uvs, ImDrawFlags flags) +void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags) { const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); const ImVec2 uv_tr(tex_uvs.z, tex_uvs.y); @@ -2368,7 +2367,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImVec4 tex_uvs; float fringe; - _SelectFringeTexture(screen_thickness, tex_uvs, fringe); + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(rounding), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; @@ -2383,7 +2382,8 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; static const ImDrawFlags corner_flags[4] = { ImDrawFlags_RoundCornersTopLeft, ImDrawFlags_RoundCornersTopRight, ImDrawFlags_RoundCornersBottomRight, ImDrawFlags_RoundCornersBottomLeft }; const float half_fringe = fringe * 0.5f; - const ImVec2 corner_pos[4] = { + const ImVec2 corner_pos[4] = + { ImVec2(p_min.x - half_fringe, p_min.y - half_fringe), ImVec2(p_max.x + half_fringe, p_min.y - half_fringe), ImVec2(p_max.x + half_fringe, p_max.y + half_fringe), @@ -2450,7 +2450,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, { for (int i = 0; i < arc_point_count - 1; i++) IM_APPEND_TRI(stem_idx, arc_idx + i, arc_idx + i + 1); - } + } // (keep braces because of macro above) // Connect with previous IM_APPEND_TRI(base_idx + 0, arc_idx, stem_idx); @@ -2582,9 +2582,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { // Pixel aligned rect with round corners rendered using baked textures. - IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); const int size = ImMax(s_rounding, s_thickness); // This is matching the baking calculations. const int idx = (s_thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + s_rounding - 1; + IM_ASSERT_PARANOID((_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners) == 0); IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); const ImVec4 tex_uvs = _Data->TexUvCorners[idx]; _AddRectBaked(outer_min, outer_max, col, (float)size * _FringeScale, (float)thickness, tex_uvs, flags); @@ -2621,7 +2621,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); } -void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, ImVec4 tex_uvs, ImDrawFlags flags) +void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, const ImVec4& tex_uvs, ImDrawFlags flags) { // 9-slice with corner mirroring const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); @@ -2637,7 +2637,6 @@ void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, I const float r_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? r : 0.0f; ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p_min.x, p_min.y, uv_tl, col); IM_APPEND_VTX(p_min.x + r_tl, p_min.y, uv_tr, col); IM_APPEND_VTX(p_max.x - r_tr, p_min.y, uv_tr, col); From 68b5bf4466192a0f4a91b99ae18b3b824862336f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 26 May 2026 21:15:55 +0200 Subject: [PATCH 083/245] DrawList: use straight floats when possible in _AddRectTinyRounding(). --- imgui_draw.cpp | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 41eb2abd8..3b23930b0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2392,7 +2392,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, thickness += fringe; rounding += half_fringe; - // We need to stem offset to be atleast fringe scale away, to maintain the fringe size. + // We need to stem offset to be at least fringe scale away, to maintain the fringe size. const float stem_offset = thickness - ImMax(thickness - rounding, _FringeScale); const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; @@ -2411,39 +2411,37 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, IM_APPEND_VTX(0, 0, stem_uv, col); IM_APPEND_VTX(0, 0, outer_uv, col); - ImVec2 outer, stem, inner, center; - for (int corner = 0; corner < 4; corner++) { - outer = corner_pos[corner]; - stem.x = corner_pos[corner].x + corner_offset[corner].x * stem_offset; - stem.y = corner_pos[corner].y + corner_offset[corner].y * stem_offset; - inner.x = corner_pos[corner].x + corner_offset[corner].x * thickness; - inner.y = corner_pos[corner].y + corner_offset[corner].y * thickness; - - const bool is_rounded = flags & corner_flags[corner]; + const float outer_x = corner_pos[corner].x; + const float outer_y = corner_pos[corner].y; + const float stem_x = outer_x + corner_offset[corner].x * stem_offset; + const float stem_y = outer_y + corner_offset[corner].y * stem_offset; + const float inner_x = outer_x + corner_offset[corner].x * thickness; + const float inner_y = outer_y + corner_offset[corner].y * thickness; + const bool is_rounded = (flags & corner_flags[corner]); const int arc_idx = (int)_VtxCurrentIdx; if (is_rounded) { - center.x = outer.x + corner_offset[corner].x * rounding; - center.y = outer.y + corner_offset[corner].y * rounding; + const float center_x = outer_x + corner_offset[corner].x * rounding; + const float center_y = outer_y + corner_offset[corner].y * rounding; int a = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) * corner; for (int i = 0; i < arc_point_count; i++) { - IM_APPEND_VTX(center.x - _Data->ArcFastVtx[a].x * rounding, center.y - _Data->ArcFastVtx[a].y * rounding, inner_uv, col); + IM_APPEND_VTX(center_x - _Data->ArcFastVtx[a].x * rounding, center_y - _Data->ArcFastVtx[a].y * rounding, inner_uv, col); a = (a + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; } } else { - IM_APPEND_VTX(outer.x, outer.y, inner_uv, col); + IM_APPEND_VTX(outer_x, outer_y, inner_uv, col); } const int stem_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(stem.x, stem.y, stem_uv, col); + IM_APPEND_VTX(stem_x, stem_y, stem_uv, col); const int inner_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(inner.x, inner.y, outer_uv, col); + IM_APPEND_VTX(inner_x, inner_y, outer_uv, col); // Arc if (is_rounded) From 20110d751d8cf5c9c4b6926a3d20aca545596fe9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 19 May 2026 16:07:47 +0200 Subject: [PATCH 084/245] Docs: update changelog. --- docs/CHANGELOG.txt | 116 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 12c9de64c..bbc7e9c98 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,122 @@ HOW TO UPDATE? VERSION 1.93.0 WIP (In Progress) ----------------------------------------------------------------------- +- In 1.93, the ImDrawList rendering has been improved to be more robust and more consistent over + the whole range of shapes. The rendering now matches much closer to common vector drawing APIs, + like html canvas. Improvements, like anti-aliased line endings and stroke position were added, + and the coordinates passed to the API are now consistent. + Some details are now rendered slightly differently (even if generally more consistent). + The difference in rendering is in the range of half a pixel, but that can lead to issues like + some lines now look blurrier or more transparent. + The rendering of common shapes was optimized when the shapes fall on integer coordinates + (which is most of the UI). This includes skipping anti-aliasing when not needed, or using + textures instead of tessellated geometry to draw round corners. +- Most of the work courtesy of @memononen, with bits from @ocornut, @thedmd, @potocpav. +- Refer to our full guides: + - ImDrawList Vector Rendering Reference + https://github.com/ocornut/imgui/wiki/Draw-List + - Pixel Perfect Anti-aliased Rendering + https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering + - How Anti-aliased Polyline Rendering is Implemented + https://github.com/ocornut/imgui/wiki/Polyline-Rendering +- (Breaking) AddLine: removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates. + - This fixes inconsistencies in the API and matches the PathXXX API. + - By default, stroke thickness extends on both side of the given segment. + e.g for a "pixel-perfect" looking line with thickness=1.0f, coords should be passed as center of each ends of the line. + - Use `ImDrawFlags_StrokeLegacy` to use old offset if required. But you might as well apply the offset manually! + - Generally better to use to newly introduced `AddLineH()`, `AddLineV()` functions. + READ IF YOU ARE MINDFUL OF PIXEL-PERFECTNESS IN YOUR CUSTOM RENDERING/WIDGETS: + Transition guide for axis-aligned lines: + - When switching from legacy `AddLine()` values to `AddLineV()`, `AddLineH()` you can keep same inputs coordinates as before. + - Old `AddLine({x, y1}, {x, y2}, col)` --> `AddLineV(x, y1, y2, col);` // Vertical line. + - Old `AddLine({x1, y}, {x2, y}, col)` --> `AddLineH(x1, x2, y, col);` // Horizontal line. + - This will be equivalent and faster for thickness=1.0f lines. + - Since `AddLine()` use default stroke pos Center and `AddLineV()`, `AddLineH()` use Inside, thickness>1.0f strokes will differ. + Using `ImDrawFlags_StrokeCenter` will match old result more closely (aka look centered), but is more likely + to look blurry as it already did before. Read table below about StrokePos if you care about pixel-perfect lines. + Transition guide for diagonal lines: + - Your lines will appear offset by -0.5f pixels on each axis. + Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. + It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. + - Old AddLine({x1, y1}, {x2, y2}, col) == AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy); // Offset by +0.5f + disable AA ends. + == AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col, thickness, ImDrawFlags_NoAAEnds); // Same + This reapplies the old offset, and should get you exactly the same result you previously got for thickness=1.0f lines. + But said result was sometimes ambiguous and renderer dependent. (#3116, #3258, #2441) + - Old AddLine() did not have anti-aliased ends, which could create gaps when rendering shapes out + of multiple contiguous lines instead of using AddPolyline(). There is a possibility that you could + have added fudge offsets here and there which are not necessary anymore or may be simplified. +- AddPolyline(), PathStroke(), AddTriangle(): the algorithm to render lines got overhauled. (#2183, #2964, #7972) + - Generally fixed rendering of thick strokes/paths. + - The new stroke expansion now uses corner miter calculation, which keeps thickness along the line segments + consistent. If the corner becomes too sharp, it will be bevelled to avoid long spikes at corners. + - There are also some robustness measures for the case where the line thickness is larger than the + features being drawn. + - Rendering artifacts are still possible when the path features are smaller than line thickness, + but the artifacts should be more localized. The new implementation attempted to favor simple + implementation and robustness over the corner case accuracy. + - Added anti-aliasing ends, most noticeable for thick lines. + - Added `ImDrawFlags_NoAAEnds` flag to disable anti-aliased line ends (slightly faster + and reduce vertex/index data). + - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner (closer to legacy + rendering, slightly faster, but corners sharpers than 90 degrees may expand far out). + Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() etc functions + since we know that the input path does not contains sharper corners. + - Added `ImDrawFlags_SquareCap` flag to use extend lines ends using square caps. +- AddConvexPolyFilled()/PathFillConvex(): improved to handle input geometry more robustly. + The rendering of sharp corners was improved. Earlier there were issues with sharp corners + either creating long spikes, or messing up the adjacent edge’s anti-aliasing. Now the + anti-aliasing fringe calculation is more consistent, and sharp corners get bevelled to + avoid spikes. There might still be issues when the smallest extent of a long thin polygon + is less than a pixel. Also supports `ImDrawFlags_MiterOnly`, to facilitate matching + a stroke using the same flag. +- AddRect(), AddRectFilled(): various optimization for rounded rectangles. (#1962) + - Integer-aligned coordinates and thicknesses will automatically use baked textures, + saving on both CPU and vertex/index data. + - Added `ImFontAtlasFlags_NoBakedRoundCorners` to disable baking round corners in font atlas. + - Added `ImDrawListFlags_RoundCornersUseTex` to disable using round corners. +- AddRectFilled(): non-integer coordinates will now display anti-aliased edges. (#6971) +- Improved minor mismatches when overlapping strokes and filled shapes, e.g. when using inside strokes, + - `AddRect()` and `AddRectFilled()` with rounding now overlap better. (#3656) + - `AddCircle()` and `AddCircleFilled()` now overlap better. +- Added flags to specify stroke position in all ImDrawList stroking functions: + - `ImDrawFlags_StrokeInside` (default for closed primitives and AddLineH, AddLineV) + - `ImDrawFlags_StrokeCenter` (default for paths, bezier and AddLine) + - `ImDrawFlags_StrokeCenterAligned` + - `ImDrawFlags_StrokeOutside` + - `ImDrawFlags_StrokeLegacy` + - Legacy code was generally applying +0.50f offset which meant that, + - with thickness=1.0f: the stroke would appear inside. + - with thickness>1.0f: the stroke would start expanding on both sides but starting from that slightly initial offset. + - with thickness>1.0f for even integer values, the stroke would look blurry. + - TL;DR; the logic didn't make much sense for thickness>1.0f. + - Defaulting to Inside for closed shapes ensure that rectangles and lines are never blurry, + regardless of thickness, as long as input coordinates/sizes are integers. (#9359) + - Recap: + ------------------------------------------------------------------------ + Legacy Inside Outside Center CenterAligned + -------------------------------------------------------------------------------- + Thickness=1.0f sharp sharp sharp blurry sharp + Thickness=2.0f blurry sharp sharp sharp sharp + Thickness=3.0f sharp sharp sharp blurry sharp + ------------------------------------------------------------------------ +- (Breaking) AddRect, AddCircle, AddNgon, AddEllipse: defaulting to "inside" stroke. + - All closed shapes with thickness=1.0f will appear identical. + - The difference for thickness>1.0f shapes may be minimal since very large strokes + were not well supported for widgets, but stroke will default inside widgets. +- Tweaked line rendering in various locations to avoid blurryness: + - Windows: title-bar and menu-bar border (when thickness>1.0f). + - Tables: borders (when thickness>1.0f). + - SeparatorText: border (when thickness>1.0f). + - Tree: hierarchy lines (when thickness>1.0f). + - TabBar: selected overline border ((when thickness>1.0f). + - Demo: Custom Rendering: canvas lines. +- (Breaking) Removed support for non-aliased shapes. + - Clearing `ImDrawListFlags_AntiAliasedLines` / `ImDrawListFlags_AntiAliasedFill` will have no effect. +- Demo: Custom Rendering: exposed new flags; Showcasing overlapping strokes and + filled shapes; Added an option to animation thickness; Added new shapes to + showcase new rendering features that previously hit limitations. + + Breaking Changes: - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in From 5410a04db462219a10ae5ca6508c8e6a18a29e9d Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 28 May 2026 10:44:37 +0300 Subject: [PATCH 085/245] DrawList: fixed out of bounds access of baked corner based on thickness --- imgui_draw.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3b23930b0..b1e167cb7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2577,9 +2577,10 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness <= IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { // Pixel aligned rect with round corners rendered using baked textures. + IM_ASSERT_PARANOID(s_thickness > 0 && s_rounding > 0); const int size = ImMax(s_rounding, s_thickness); // This is matching the baking calculations. const int idx = (s_thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + s_rounding - 1; IM_ASSERT_PARANOID((_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners) == 0); From 3fca7ef414aec775be8f9269e92e3d8424e6817c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 28 May 2026 15:26:32 +0200 Subject: [PATCH 086/245] DrawList: skip PathLineTo/PathStroke calls for common AddLine() functions. (#4091) Rough numbers Debug x64, 100k lines: 91.5->80 ms, 87->75.5 ms (NoAAEnds), 87->76 ms (Legacy) Release x64, 300 lines: 25.2->25 ms, 22.2->18.3 ms (NoAAEnds), 22.2->19.3 ms (Legacy) --- imgui_draw.cpp | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b1e167cb7..bc331ad6d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2143,7 +2143,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness, stroke_pos); + AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); return; } @@ -2177,9 +2177,8 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // For generic case use line, since it needs less triangles than AA rectangle. - PathLineTo(ImVec2(min_x, y)); - PathLineTo(ImVec2(max_x, y)); - PathStroke(col, thickness, flags); + const ImVec2 points[2] = { ImVec2(min_x, y), ImVec2(max_x, y) }; + AddPolyline(points, 2, col, thickness, flags); } } @@ -2191,8 +2190,8 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { - const ImVec2 points[2] = { ImVec2(x + 0.5f, max_y + 0.5f), ImVec2(x + 0.5f, min_y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness, stroke_pos); + const ImVec2 points[2] = { ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f) }; // Same as AddLine() above. + AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); return; } @@ -2227,9 +2226,8 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th // For generic case use line, since it needs less triangles than AA rectangle. // Drawing for bottom to top, so that the inside stroke pos expands to right. - PathLineTo(ImVec2(x, max_y)); - PathLineTo(ImVec2(x, min_y)); - PathStroke(col, thickness, flags); + const ImVec2 points[2] = { ImVec2(x, max_y), ImVec2(x, min_y) }; + AddPolyline(points, 2, col, thickness, flags); } } @@ -2494,9 +2492,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { if (Flags & ImDrawListFlags_AntiAliasedLines) - PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); + PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.50f, p_max.y - 0.50f), rounding, flags); else - PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. + PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.49f, p_max.y - 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeCenter); return; } @@ -2593,10 +2591,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { - PathLineTo(outer_min); - PathLineTo(ImVec2(outer_max.x, outer_min.y)); - PathLineTo(outer_max); - PathLineTo(ImVec2(outer_min.x, outer_max.y)); + const ImVec2 points[4] = { outer_min, ImVec2(outer_max.x, outer_min.y), outer_max, ImVec2(outer_min.x, outer_max.y) }; + AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); } else { @@ -2615,9 +2611,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathArcToFast(ImVec2(outer_max.x - rounding_tr, outer_min.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(outer_max.x - rounding_br, outer_max.y - rounding_br), rounding_br, 0, 3); PathArcToFast(ImVec2(outer_min.x + rounding_bl, outer_max.y - rounding_bl), rounding_bl, 3, 6); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); } - - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); } void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, const ImVec4& tex_uvs, ImDrawFlags flags) @@ -2951,9 +2946,7 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) - { stroke_pos = ImDrawFlags_StrokeCenter; - } ImVec2 rad = radius; rad.x = ImMax(0.01f, rad.x); From e9246e6ad3a8a0589becd14b44bff52b79769537 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 29 May 2026 16:08:49 +0300 Subject: [PATCH 087/245] DrawList: Fixed vertex count calculation in_AddRectTinyRounding() --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bc331ad6d..6031a782e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2370,7 +2370,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(rounding), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; - int vtx_count = (4 + arc_point_count) * 3 + 3; + int vtx_count = (2 + arc_point_count) * 4 + 3; int idx_count = (4 + arc_point_count - 1) * 4 * 3; PrimReserve(idx_count, vtx_count); From c59367efcbf22ba04fc980315cbd9588bc9865b6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jun 2026 17:20:17 +0200 Subject: [PATCH 088/245] DrawList: renamed ImDrawFlags_StrokeCenterAligned to ImDrawFlags_StrokeCenterBiased. --- imgui.h | 2 +- imgui_demo.cpp | 2 +- imgui_draw.cpp | 28 ++++++++++++++-------------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/imgui.h b/imgui.h index 3d111504d..3cb10c746 100644 --- a/imgui.h +++ b/imgui.h @@ -3344,7 +3344,7 @@ enum ImDrawFlags_ // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) - ImDrawFlags_StrokeCenterAligned = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. Does not animate well! + ImDrawFlags_StrokeCenterBiased = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. Does not animate well! ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly and NoAAEnds flags. ImDrawFlags_StrokeMask_ = 0x07 << 16, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 89ce2a3be..c4b0939b0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10425,7 +10425,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::RadioButton("Default", &stroke_flags, ImDrawFlags_None); ImGui::SameLine(); ImGui::RadioButton("Inside", &stroke_flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); ImGui::RadioButton("Center", &stroke_flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); - ImGui::RadioButton("CenterAligned", &stroke_flags, ImDrawFlags_StrokeCenterAligned); ImGui::SameLine(); + ImGui::RadioButton("CenterBiased", &stroke_flags, ImDrawFlags_StrokeCenterBiased); ImGui::SameLine(); ImGui::RadioButton("Outside", &stroke_flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); ImGui::RadioButton("Legacy", &stroke_flags, ImDrawFlags_StrokeLegacy); ImGui::CheckboxFlags("MiterOnly", &other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6031a782e..32ebdb6f7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -813,12 +813,12 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c } -static float CalculateCenterAlignedOffset(float thickness, float _FringeScale) +static float CalculateCenterBiasedOffset(float thickness, float _FringeScale) { // Old jumpy one. // return IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; - // Calculate outside offset for stroke position CenterAligned + // Calculate outside offset for stroke position ImDrawFlags_StrokeCenterBiased // so that one side the of the line is always at pixel boundary. // On integer thickness both sides of the line are on pixel boundary. const float screen_thickness = thickness / _FringeScale; @@ -871,8 +871,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) if (stroke_pos == ImDrawFlags_StrokeOutside) thickness0 = thickness + fringe * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) - thickness0 = CalculateCenterAlignedOffset(thickness, _FringeScale) + fringe * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + thickness0 = CalculateCenterBiasedOffset(thickness, _FringeScale) + fringe * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeInside) thickness0 = fringe * 0.5f; float thickness1 = (thickness + fringe) - thickness0; @@ -2150,8 +2150,8 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th float top_y = y; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) top_y -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) - top_y -= CalculateCenterAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + top_y -= CalculateCenterBiasedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) top_y -= thickness; @@ -2198,8 +2198,8 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th float left_x = x; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) left_x -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) - left_x -= CalculateCenterAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + left_x -= CalculateCenterBiasedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) left_x -= thickness; @@ -2509,8 +2509,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl float offset = 0.0f; // Inside if (stroke_pos == ImDrawFlags_StrokeCenter) offset = thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) - offset = CalculateCenterAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + offset = CalculateCenterBiasedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeOutside) offset = thickness; outer_min.x -= offset; @@ -2810,8 +2810,8 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) - outer_radius = radius + CalculateCenterAlignedOffset(thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + outer_radius = radius + CalculateCenterBiasedOffset(thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2897,8 +2897,8 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + miter_thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterAligned) - outer_radius = radius + CalculateCenterAlignedOffset(miter_thickness, _FringeScale); + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + outer_radius = radius + CalculateCenterBiasedOffset(miter_thickness, _FringeScale); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) From e8c8a10a2d9af65acc24f6260f9a1d83455d9bc1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 1 Jun 2026 17:20:34 +0200 Subject: [PATCH 089/245] DrawList: amends/review legacy stroke paths + minor tweaks. --- imgui.cpp | 15 +++++---------- imgui_draw.cpp | 36 ++++++++++++++++++------------------ imgui_widgets.cpp | 25 ++++++++++++++----------- 3 files changed, 37 insertions(+), 39 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b6cef8d0c..b9a700608 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7312,16 +7312,11 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) } if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) { - if (g_LEGACY_STROKES) - { float y = window->Pos.y + window->TitleBarHeight - 1; + if (g_LEGACY_STROKES) window->DrawList->AddLineH(window->Pos.x + border_size * 0.5f, window->Pos.x + window->Size.x - border_size * 0.5f, y, border_col, g.Style.FrameBorderSize); - } else - { - float y = window->Pos.y + window->TitleBarHeight - g.Style.FrameBorderSize; - window->DrawList->AddLineH(window->Pos.x + border_size, window->Pos.x + window->Size.x - border_size, y, border_col, g.Style.FrameBorderSize); - } + window->DrawList->AddLineH(window->Pos.x + border_size, window->Pos.x + window->Size.x - border_size, y, border_col, g.Style.FrameBorderSize, ImDrawFlags_StrokeCenterBiased); } } @@ -7393,7 +7388,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar if (g_LEGACY_STROKES) window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5f, menu_bar_rect.Max.x - window_border_size * 0.5f, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize); else - window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size, menu_bar_rect.Max.x - window_border_size, menu_bar_rect.Max.y - style.FrameBorderSize, GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size, menu_bar_rect.Max.x - window_border_size, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize, ImDrawFlags_StrokeCenterBiased); } } @@ -18340,12 +18335,12 @@ void ImGui::DebugDrawLineExtents(ImU32 col) float curr_x = window->DC.CursorPos.x; float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y); float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y); - window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y1, col, 1.0f); + window->DrawList->AddLineH(curr_x - 4.0f, curr_x + 5.0f, line_y1, col, 1.0f); if (g_LEGACY_STROKES) window->DrawList->AddLineV(curr_x - 0.5f, line_y1, line_y2, col, 1.0f); else window->DrawList->AddLineV(curr_x, line_y1, line_y2, col, 1.0f); - window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y2, col, 1.0f); + window->DrawList->AddLineH(curr_x - 4.0f, curr_x + 5.0f, line_y2, col, 1.0f); } // Draw last item rect in ForegroundDrawList (so it is always visible) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 32ebdb6f7..a8696841d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1187,7 +1187,7 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv { // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. The texture scaling in this range will cause slight visual pops, so we generate super sampled textures in this range. // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH. - constexpr float base_width = 1.f; + constexpr float base_width = 1.0f; const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f), 0, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; *out_fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. @@ -2158,12 +2158,12 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if (_FringeScaleIsInteger && ImIsTruncated4(min_x, max_x, top_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) { float screen_thickness = thickness / _FringeScale; - if (screen_thickness < 1.f / 255.f) + if (screen_thickness < 1.0f / 255.0f) return; - if (screen_thickness < 1.f) + if (screen_thickness < 1.0f) { col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.f; + screen_thickness = 1.0f; thickness = _FringeScale; } @@ -2206,12 +2206,12 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if (_FringeScaleIsInteger && ImIsTruncated4(left_x, min_y, max_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) { float screen_thickness = thickness / _FringeScale; - if (screen_thickness < 1.f / 255.f) + if (screen_thickness < 1.0f / 255.0f) return; - if (screen_thickness < 1.f) + if (screen_thickness < 1.0f) { col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.f; + screen_thickness = 1.0f; thickness = _FringeScale; } @@ -2673,18 +2673,18 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c const float width = b_max.x - b_min.x; const float height = b_max.y - b_min.y; - const float inv_fringe_scale = 1.f / _FringeScale; + const float inv_fringe_scale = 1.0f / _FringeScale; const float screen_width = width * inv_fringe_scale; const float screen_height = height * inv_fringe_scale; - if (ImMin(screen_width, screen_height) < 1.f / 255.f) + if (ImMin(screen_width, screen_height) < 1.0f / 255.0f) return; - if (screen_width < 1.f) + if (screen_width < 1.0f) { col = ImAlphaMultiply(col, screen_width); b_max.x = b_min.x + _FringeScale; } - if (screen_height < 1.f) + if (screen_height < 1.0f) { col = ImAlphaMultiply(col, screen_height); b_max.y = b_min.y + _FringeScale; @@ -2970,18 +2970,18 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im ImVec2 rad = radius; - const float inv_fringe_scale = 1.f / _FringeScale; - float screen_diameter_x = rad.x* 2.f * inv_fringe_scale; - float screen_diameter_y = rad.y * 2.f * inv_fringe_scale; - if (screen_diameter_x < 1.f / 255.f || screen_diameter_y < 1.f / 255.f) + const float inv_fringe_scale = 1.0f / _FringeScale; + float screen_diameter_x = rad.x * 2.0f * inv_fringe_scale; + float screen_diameter_y = rad.y * 2.0f * inv_fringe_scale; + if (screen_diameter_x < 1.0f / 255.0f || screen_diameter_y < 1.0f / 255.0f) return; - if (screen_diameter_x < 1.f) + if (screen_diameter_x < 1.0f) { col = ImAlphaMultiply(col, screen_diameter_x); rad.x = _FringeScale * 0.5f; } - if (screen_diameter_y < 1.f) + if (screen_diameter_y < 1.0f) { col = ImAlphaMultiply(col, screen_diameter_y); rad.y = _FringeScale * 0.5f; @@ -5163,7 +5163,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImU8 ramp[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]; for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; n++) - ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.f); + ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.0f); for (int n = 0; n < IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1; n++) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8413344a8..d5d3facbd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1763,7 +1763,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end if (g_LEGACY_STROKES) seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.999f); else - seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + (-separator_thickness * 0.5f + 1.0f) + 0.999f); // Align hline vertically, and snap to pixels. + seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f) + 1.0f; const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f); const ImVec2 label_pos(pos.x + padding.x + ImMax(0.0f, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y); // FIXME-ALIGN @@ -1777,9 +1777,9 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end const float sep1_x2 = label_pos.x - style.ItemSpacing.x; const float sep2_x1 = label_pos.x + label_size.x + extra_w + style.ItemSpacing.x; if (sep1_x2 > sep1_x1 && separator_thickness > 0.0f) - window->DrawList->AddLineH(sep1_x1, sep1_x2, seps_y, separator_col, separator_thickness); + window->DrawList->AddLineH(sep1_x1, sep1_x2, seps_y, separator_col, separator_thickness, ImDrawFlags_StrokeCenterBiased); if (sep2_x2 > sep2_x1 && separator_thickness > 0.0f) - window->DrawList->AddLineH(sep2_x1, sep2_x2, seps_y, separator_col, separator_thickness); + window->DrawList->AddLineH(sep2_x1, sep2_x2, seps_y, separator_col, separator_thickness, ImDrawFlags_StrokeCenterBiased); if (g.LogEnabled) LogSetNextTextDecoration("---", NULL); RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size); @@ -1789,7 +1789,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end if (g.LogEnabled) LogText("---"); if (separator_thickness > 0.0f) - window->DrawList->AddLineH(sep1_x1, sep2_x2, seps_y, separator_col, separator_thickness); + window->DrawList->AddLineH(sep1_x1, sep2_x2, seps_y, separator_col, separator_thickness, ImDrawFlags_StrokeCenterBiased); } } @@ -5771,7 +5771,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 1.0f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.0f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) - draw_window->DrawList->AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, GetColorU32(ImGuiCol_InputTextCursor), style.InputTextCursorSize); + draw_window->DrawList->AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, GetColorU32(ImGuiCol_InputTextCursor), style.InputTextCursorSize, ImDrawFlags_StrokeInside); // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) // This is required for some backends (SDL3) to start emitting character/text inputs. @@ -7318,23 +7318,25 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) if ((window->DC.TreeHasStackDataDepthMask & TREE_NODE_GET_DEPTH_MASK(window->DC.TreeDepth - 1)) == 0) return; + // FIXME: Could this be simplified using new stroke flags? ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; + const float half_size = g.Style.TreeLinesSize * 0.5f; float x1; if (g_LEGACY_STROKES) x1 = ImTrunc(parent_data->DrawLinesX1); else - x1 = ImTrunc(parent_data->DrawLinesX1 - g.Style.TreeLinesSize * 0.5f) + g.Style.TreeLinesSize * 0.5f; // Draw line centered at X1, but snap to pixels boundary. + x1 = ImTrunc(parent_data->DrawLinesX1 - half_size) + half_size; // Draw line centered at X1, but snap to pixels boundary. float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); float y; if (g_LEGACY_STROKES) y = ImTrunc(target_pos.y); else - y = ImTrunc(target_pos.y) + g.Style.TreeLinesSize * 0.5f; + y = ImTrunc(target_pos.y - half_size) + half_size; float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f; parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding); if (x1 >= x2) return; - if (rounding > 0.0f) + if (rounding > 0.0f && rounding > half_size) { if (g_LEGACY_STROKES) x1 += 0.5f + rounding; @@ -7348,9 +7350,9 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) else { // We use AddLine() instead of AddLineH() as we provide coordinates for line center, - // in order to make the code use same coordinates for both rounded and non-rounded version. + // in order to make the code use same coordinates for both rounded and non-rounded version. (FIXME-OPT) if (!g_LEGACY_STROKES) - x1 += g.Style.TreeLinesSize * 0.5f; // Avoid overdraw + x1 += half_size; // Avoid overdraw window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } } @@ -7381,7 +7383,8 @@ void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) x = ImTrunc(data->DrawLinesX1 - g.Style.TreeLinesSize * 0.5f) + g.Style.TreeLinesSize * 0.5f; // Draw line centered at X1, but snap to pixels boundary. if (data->DrawLinesTableColumn != -1) TablePushColumnChannel(data->DrawLinesTableColumn); - // We use AddLine() instead of AddLineV() as we provide coordinates for line center, + + // We use AddLine() instead of AddLineV() as we provide coordinates for line center (FIXME-OPT) window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); if (data->DrawLinesTableColumn != -1) TablePopColumnChannel(); From 7ec1bc17fd0b27cb0c5f1471fb7fef0fb02ed1fe Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 1 Jun 2026 20:35:16 +0300 Subject: [PATCH 090/245] DrawList: debug build optimizations. - changed truncated tests to use macro, and inline the computation in debug builds (~15% was spent on calling the functions) - inlined the common rectangle cases in AddRect() for debug build speed up --- imgui_demo.cpp | 2 +- imgui_draw.cpp | 55 +++++++++++++++++++++++++++++++++++++------------- 2 files changed, 42 insertions(+), 15 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c4b0939b0..e7d8473a9 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10400,7 +10400,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); - const float thickness_anim_period = 5.f; + const float thickness_anim_period = 5.0f; const float thickness_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), thickness_anim_period) * (2.0f / thickness_anim_period) - 1.0f); const float thickness = animate_thickness ? thickness_wave * base_thickness : base_thickness; ImGui::DragFloat("Thickness", &base_thickness, 0.02f, 0.0f, 30.0f, "%.02f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a8696841d..03e51358f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -854,7 +854,16 @@ static float CalculateCenterBiasedOffset(float thickness, float _FringeScale) } (void)0 #define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) -#define IM_POLYLINE_MITER_LIMIT (4.0f) +#define IM_POLYLINE_MITER_LIMIT (4.0f) // ~29 deg + +// In debug builds the functions are likely not inlined, so inlined check is cheaper. +#if defined(DEBUG) || defined(_DEBUG) +#define IM_IS_TRUNCATED4(a, b, c, d) ((float)(int)(a) == (a)) && ((float)(int)(b) == (b)) && ((float)(int)(c) == (c)) && ((float)(int)(d) == (d)) +#define IM_IS_TRUNCATED(a) ((float)(int)(a) == (a)) +#else +#define IM_IS_TRUNCATED4(a, b, c, d) ImIsTruncated4(a, b, c, d) +#define IM_IS_TRUNCATED(a) ImIsTruncated(a) +#endif void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe) { @@ -2155,7 +2164,8 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th else if (stroke_pos == ImDrawFlags_StrokeOutside) top_y -= thickness; - if (_FringeScaleIsInteger && ImIsTruncated4(min_x, max_x, top_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) + const bool is_truncated = IM_IS_TRUNCATED4(min_x, max_x, top_y, thickness); + if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_SquareCap) == 0) { float screen_thickness = thickness / _FringeScale; if (screen_thickness < 1.0f / 255.0f) @@ -2203,7 +2213,8 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th else if (stroke_pos == ImDrawFlags_StrokeOutside) left_x -= thickness; - if (_FringeScaleIsInteger && ImIsTruncated4(left_x, min_y, max_y, thickness) && (flags & ImDrawFlags_SquareCap) == 0) + const bool is_truncated = IM_IS_TRUNCATED4(left_x, min_y, max_y, thickness); + if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_SquareCap) == 0) { float screen_thickness = thickness / _FringeScale; if (screen_thickness < 1.0f / 255.0f) @@ -2537,7 +2548,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); } - if (_FringeScaleIsInteger && ImIsTruncated4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && ImIsTruncated4(outer_rounding, thickness, 0.0f, 0.0f)) + const bool is_truncated = IM_IS_TRUNCATED4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && IM_IS_TRUNCATED4(outer_rounding, thickness, 0.0f, 0.0f); + if (_FringeScaleIsInteger && is_truncated) { int s_rounding = (int)(outer_rounding / _FringeScale); int s_thickness = (int)(thickness / _FringeScale); @@ -2690,11 +2702,12 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c b_max.y = b_min.y + _FringeScale; } - if (ImIsTruncated4(p_min.x, p_min.y, p_max.x, p_max.y) && ImIsTruncated(rounding)) - { - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags |= ImDrawFlags_RoundCornersAll; + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; + const bool is_truncated = IM_IS_TRUNCATED4(p_min.x, p_min.y, p_max.x, p_max.y) && IM_IS_TRUNCATED(rounding); + if (_FringeScaleIsInteger && is_truncated) + { rounding = ImMin(rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); rounding = ImMin(rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); @@ -2702,7 +2715,18 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { PrimReserve(6, 4); - PrimRect(p_min, p_max, col); + + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; + const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + IM_APPEND_VTX(p_min.x, p_min.y, opaque_uv, col); + IM_APPEND_VTX(p_max.x, p_min.y, opaque_uv, col); + IM_APPEND_VTX(p_max.x, p_max.y, opaque_uv, col); + IM_APPEND_VTX(p_min.x, p_max.y, opaque_uv, col); + + IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); + IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); + + return; } else if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { @@ -2712,12 +2736,15 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); ImVec4 tex_uvs = _Data->TexUvCorners[idx]; _AddRectFilledBaked(p_min, p_max, col, (float)size * _FringeScale, tex_uvs, flags); + return; } - else - { - PathRect(p_min, p_max, (float)s_rounding, flags); - PathFillConvex(col); - } + } + + const bool has_rounding = (rounding >= _FringeScale * 0.5f); + if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + { + const ImVec2 points[4] = { p_min, ImVec2(p_max.x, p_min.y), p_max, ImVec2(p_min.x, p_max.y) }; + AddConvexPolyFilled(points, 4, col, ImDrawFlags_MiterOnly); } else { From b484a908465ed0dcf29eeb8abb7006939ef87fb1 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 2 Jun 2026 09:52:26 +0300 Subject: [PATCH 091/245] DrawList: minor render optimizations. - Use inline array + AddPolyline/AddConvexPolyFilled for triangle and quad - do less computation for detecting small shape rendering - add IM_UNLIKELY for very unlikely branches --- imgui_draw.cpp | 128 ++++++++++++++++++++++++------------------------- 1 file changed, 62 insertions(+), 66 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 03e51358f..8837d14cf 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2500,7 +2500,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { if (Flags & ImDrawListFlags_AntiAliasedLines) PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.50f, p_max.y - 0.50f), rounding, flags); @@ -2532,7 +2532,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl const float width = outer_max.x - outer_min.x; const float height = outer_max.y - outer_min.y; - if (ImMin(width, height) < (thickness + _FringeScale) * 2.0f) + if (ImMin(width, height) < (thickness + _FringeScale) * 2.0f) IM_UNLIKELY { // Rectangle has collapsed into filled rectangle. AddRectFilled(outer_min, outer_max, col, outer_rounding, flags); @@ -2680,26 +2680,28 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if ((col & IM_COL32_A_MASK) == 0) return; - ImVec2 b_min = p_min; - ImVec2 b_max = p_max; - const float width = b_max.x - b_min.x; - const float height = b_max.y - b_min.y; + float width = p_max.x - p_min.x; + float height = p_max.y - p_min.y; + const float min_dim = ImMin(width, height); - const float inv_fringe_scale = 1.0f / _FringeScale; - const float screen_width = width * inv_fringe_scale; - const float screen_height = height * inv_fringe_scale; - - if (ImMin(screen_width, screen_height) < 1.0f / 255.0f) + // The rect is smaller than pixel in one dimension. + if (min_dim < _FringeScale) IM_UNLIKELY + { + if (min_dim < (1.0f / 255.0f) * _FringeScale) + return; + if (width < _FringeScale) + { + col = ImAlphaMultiply(col, width / _FringeScale); + width = _FringeScale; + } + if (height < _FringeScale) + { + col = ImAlphaMultiply(col, height / _FringeScale); + height = _FringeScale; + } + const ImVec2 points[4] = { p_min, ImVec2(p_min.x + width, p_min.y), ImVec2(p_min.x + width, p_min.y + height), ImVec2(p_min.x, p_max.y + height) }; + AddConvexPolyFilled(points, 4, col, ImDrawFlags_MiterOnly); return; - if (screen_width < 1.0f) - { - col = ImAlphaMultiply(col, screen_width); - b_max.x = b_min.x + _FringeScale; - } - if (screen_height < 1.0f) - { - col = ImAlphaMultiply(col, screen_height); - b_max.y = b_min.y + _FringeScale; } if ((flags & ImDrawFlags_RoundCornersMask_) == 0) @@ -2777,11 +2779,8 @@ void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, c ImDrawFlags stroke_pos = g_LEGACY_STROKES ? ImDrawFlags_StrokeLegacy : _GetStrokePos(flags, ImDrawFlags_StrokeInside); flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; - PathLineTo(p1); - PathLineTo(p2); - PathLineTo(p3); - PathLineTo(p4); - PathStroke(col, thickness, flags | ImDrawFlags_Closed); + const ImVec2 points[4] = { p1, p2, p3, p4 }; + AddPolyline(points, 4, col, thickness, flags | ImDrawFlags_Closed); } void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col) @@ -2789,11 +2788,8 @@ void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& if ((col & IM_COL32_A_MASK) == 0) return; - PathLineTo(p1); - PathLineTo(p2); - PathLineTo(p3); - PathLineTo(p4); - PathFillConvex(col); + const ImVec2 points[4] = { p1, p2, p3, p4 }; + AddConvexPolyFilled(points, 4, col); } void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, ImDrawFlags flags) @@ -2803,10 +2799,9 @@ void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p ImDrawFlags stroke_pos = g_LEGACY_STROKES ? ImDrawFlags_StrokeLegacy : _GetStrokePos(flags, ImDrawFlags_StrokeInside); flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; - PathLineTo(p1); - PathLineTo(p2); - PathLineTo(p3); - PathStroke(col, thickness, flags | ImDrawFlags_Closed); + + const ImVec2 points[3] = { p1, p2, p3 }; + AddPolyline(points, 3, col, thickness, flags | ImDrawFlags_Closed); } void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col) @@ -2814,10 +2809,8 @@ void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImV if ((col & IM_COL32_A_MASK) == 0) return; - PathLineTo(p1); - PathLineTo(p2); - PathLineTo(p3); - PathFillConvex(col); + const ImVec2 points[3] = { p1, p2, p3 }; + AddConvexPolyFilled(points, 3, col); } void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) @@ -2826,7 +2819,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu return; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { radius -= 0.5f; stroke_pos = ImDrawFlags_StrokeCenter; @@ -2843,7 +2836,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) outer_radius = radius + thickness; - if (outer_radius < (thickness + _FringeScale)) + if (outer_radius < (thickness + _FringeScale)) IM_UNLIKELY { // The circle has collapsed into a filled circle. AddCircleFilled(center, outer_radius, col, num_segments); @@ -2875,12 +2868,12 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, if ((col & IM_COL32_A_MASK) == 0) return; - float screen_diameter = radius * 2.0f / _FringeScale; - if (screen_diameter < 1.0f / 255.0f) - return; - if (screen_diameter < 1.0f) + const float diameter = radius * 2.0f; + if (diameter < _FringeScale) IM_UNLIKELY { - col = ImAlphaMultiply(col, screen_diameter); + if (diameter < (1.0f / 255.0f) * _FringeScale) + return; + col = ImAlphaMultiply(col, diameter / _FringeScale); radius = _FringeScale * 0.5f; } @@ -2910,7 +2903,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ return; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { radius -= 0.5f; stroke_pos = ImDrawFlags_StrokeCenter; @@ -2930,7 +2923,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) outer_radius = radius + miter_thickness; - if (outer_radius < (miter_thickness + _FringeScale)) + if (outer_radius < (miter_thickness + _FringeScale)) IM_UNLIKELY { // The polygon has collapsed into a filled polygon. AddNgonFilled(center, outer_radius, col, num_segments); @@ -2949,12 +2942,12 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; - float screen_diameter = radius * 2.0f / _FringeScale; - if (screen_diameter < 1.0f / 255.0f) - return; - if (screen_diameter < 1.0f) + const float diameter = radius * 2.0f; + if (diameter < _FringeScale) IM_UNLIKELY { - col = ImAlphaMultiply(col, screen_diameter); + if (diameter < (1.0f / 255.0f) * _FringeScale) + return; + col = ImAlphaMultiply(col, diameter / _FringeScale); radius = _FringeScale * 0.5f; } @@ -2996,22 +2989,25 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im return; ImVec2 rad = radius; + float diameter_x = rad.x * 2.0f; + float diameter_y = rad.y * 2.0f; + const float min_dim = ImMin(diameter_x, diameter_y); - const float inv_fringe_scale = 1.0f / _FringeScale; - float screen_diameter_x = rad.x * 2.0f * inv_fringe_scale; - float screen_diameter_y = rad.y * 2.0f * inv_fringe_scale; - if (screen_diameter_x < 1.0f / 255.0f || screen_diameter_y < 1.0f / 255.0f) - return; - - if (screen_diameter_x < 1.0f) + // The ellipse is smaller than pixel in one dimension. + if (min_dim < _FringeScale) IM_UNLIKELY { - col = ImAlphaMultiply(col, screen_diameter_x); - rad.x = _FringeScale * 0.5f; - } - if (screen_diameter_y < 1.0f) - { - col = ImAlphaMultiply(col, screen_diameter_y); - rad.y = _FringeScale * 0.5f; + if (min_dim < (1.0f / 255.0f) * _FringeScale) + return; + if (diameter_x < _FringeScale) + { + col = ImAlphaMultiply(col, diameter_x / _FringeScale); + rad.x = _FringeScale * 0.5f; + } + if (diameter_y < _FringeScale) + { + col = ImAlphaMultiply(col, diameter_y / _FringeScale); + rad.y = _FringeScale * 0.5f; + } } if (num_segments <= 0) From 6856b3e06bb96b48261df3ee4f8f5846110ca261 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 2 Jun 2026 10:05:54 +0300 Subject: [PATCH 092/245] DrawList: added _InvFringeScale to use in cases of 1/_FringeScale. --- imgui.h | 4 +++- imgui_draw.cpp | 58 +++++++++++++++++++++++--------------------------- 2 files changed, 30 insertions(+), 32 deletions(-) diff --git a/imgui.h b/imgui.h index 3cb10c746..cf7f079b3 100644 --- a/imgui.h +++ b/imgui.h @@ -3393,7 +3393,7 @@ struct ImDrawList ImVector _ClipRectStack; // [Internal] ImVector _TextureStack; // [Internal] ImVector _CallbacksDataBuf; // [Internal] - float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content. + float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content float _InvFringeScale; // [internal] 1.0 / _FringeScale // FIXME: Consider renaming to _PixelDensity. bool _FringeScaleIsInteger; // [Internal] true if 1/_FringeScale is a whole number, used to select fast path for rendering const char* _OwnerName; // Pointer to owner window's name for debugging @@ -3548,6 +3548,8 @@ struct ImDrawList IMGUI_API void _AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe); + IMGUI_API float _CalculateCenterBiasedOffset(float thickness); + }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8837d14cf..3d1dbf533 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -813,7 +813,7 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c } -static float CalculateCenterBiasedOffset(float thickness, float _FringeScale) +float ImDrawList::_CalculateCenterBiasedOffset(float thickness) { // Old jumpy one. // return IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; @@ -821,7 +821,7 @@ static float CalculateCenterBiasedOffset(float thickness, float _FringeScale) // Calculate outside offset for stroke position ImDrawFlags_StrokeCenterBiased // so that one side the of the line is always at pixel boundary. // On integer thickness both sides of the line are on pixel boundary. - const float screen_thickness = thickness / _FringeScale; + const float screen_thickness = thickness * _InvFringeScale; const int s_thickness = (int)screen_thickness; return ((float)(s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; } @@ -881,7 +881,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ if (stroke_pos == ImDrawFlags_StrokeOutside) thickness0 = thickness + fringe * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - thickness0 = CalculateCenterBiasedOffset(thickness, _FringeScale) + fringe * 0.5f; + thickness0 = _CalculateCenterBiasedOffset(thickness) + fringe * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeInside) thickness0 = fringe * 0.5f; float thickness1 = (thickness + fringe) - thickness0; @@ -1224,7 +1224,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) return; - float screen_thickness = thickness / _FringeScale; + float screen_thickness = thickness * _InvFringeScale; if (screen_thickness < 1.0f / 255.0f) return; if (screen_thickness < 1.0f) @@ -2160,20 +2160,18 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if (stroke_pos == ImDrawFlags_StrokeCenter) top_y -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - top_y -= CalculateCenterBiasedOffset(thickness, _FringeScale); + top_y -= _CalculateCenterBiasedOffset(thickness); else if (stroke_pos == ImDrawFlags_StrokeOutside) top_y -= thickness; const bool is_truncated = IM_IS_TRUNCATED4(min_x, max_x, top_y, thickness); if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_SquareCap) == 0) { - float screen_thickness = thickness / _FringeScale; - if (screen_thickness < 1.0f / 255.0f) - return; - if (screen_thickness < 1.0f) + if (thickness < _FringeScale) IM_UNLIKELY { - col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.0f; + if (thickness < (1.0f / 255.0f) * _FringeScale) + return; + col = ImAlphaMultiply(col, thickness * _InvFringeScale); thickness = _FringeScale; } @@ -2209,20 +2207,18 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if (stroke_pos == ImDrawFlags_StrokeCenter) left_x -= thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - left_x -= CalculateCenterBiasedOffset(thickness, _FringeScale); + left_x -= _CalculateCenterBiasedOffset(thickness); else if (stroke_pos == ImDrawFlags_StrokeOutside) left_x -= thickness; const bool is_truncated = IM_IS_TRUNCATED4(left_x, min_y, max_y, thickness); if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_SquareCap) == 0) { - float screen_thickness = thickness / _FringeScale; - if (screen_thickness < 1.0f / 255.0f) - return; - if (screen_thickness < 1.0f) + if (thickness < _FringeScale) IM_UNLIKELY { - col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.0f; + if (thickness < (1.0f / 255.0f) * _FringeScale) + return; + col = ImAlphaMultiply(col, thickness * _InvFringeScale); thickness = _FringeScale; } @@ -2364,7 +2360,7 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c // The stroke is positioned inside the rectangle. void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { - float screen_thickness = thickness / _FringeScale; + float screen_thickness = thickness * _InvFringeScale; if (screen_thickness < 1.0f / 255.0f) return; if (screen_thickness < 1.0f) @@ -2521,7 +2517,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (stroke_pos == ImDrawFlags_StrokeCenter) offset = thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - offset = CalculateCenterBiasedOffset(thickness, _FringeScale); + offset = _CalculateCenterBiasedOffset(thickness); else if (stroke_pos == ImDrawFlags_StrokeOutside) offset = thickness; outer_min.x -= offset; @@ -2551,8 +2547,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl const bool is_truncated = IM_IS_TRUNCATED4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && IM_IS_TRUNCATED4(outer_rounding, thickness, 0.0f, 0.0f); if (_FringeScaleIsInteger && is_truncated) { - int s_rounding = (int)(outer_rounding / _FringeScale); - int s_thickness = (int)(thickness / _FringeScale); + int s_rounding = (int)(outer_rounding * _InvFringeScale); + int s_thickness = (int)(thickness * _InvFringeScale); if (s_thickness <= 0) return; @@ -2691,12 +2687,12 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c return; if (width < _FringeScale) { - col = ImAlphaMultiply(col, width / _FringeScale); + col = ImAlphaMultiply(col, width * _InvFringeScale); width = _FringeScale; } if (height < _FringeScale) { - col = ImAlphaMultiply(col, height / _FringeScale); + col = ImAlphaMultiply(col, height * _InvFringeScale); height = _FringeScale; } const ImVec2 points[4] = { p_min, ImVec2(p_min.x + width, p_min.y), ImVec2(p_min.x + width, p_min.y + height), ImVec2(p_min.x, p_max.y + height) }; @@ -2713,7 +2709,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c rounding = ImMin(rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); rounding = ImMin(rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); - const int s_rounding = (int)(rounding / _FringeScale); + const int s_rounding = (int)(rounding * _InvFringeScale); if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { PrimReserve(6, 4); @@ -2831,7 +2827,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - outer_radius = radius + CalculateCenterBiasedOffset(thickness, _FringeScale); + outer_radius = radius + _CalculateCenterBiasedOffset(thickness); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2873,7 +2869,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, { if (diameter < (1.0f / 255.0f) * _FringeScale) return; - col = ImAlphaMultiply(col, diameter / _FringeScale); + col = ImAlphaMultiply(col, diameter * _InvFringeScale); radius = _FringeScale * 0.5f; } @@ -2918,7 +2914,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ if (stroke_pos == ImDrawFlags_StrokeCenter) outer_radius = radius + miter_thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - outer_radius = radius + CalculateCenterBiasedOffset(miter_thickness, _FringeScale); + outer_radius = radius + _CalculateCenterBiasedOffset(miter_thickness); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2947,7 +2943,7 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in { if (diameter < (1.0f / 255.0f) * _FringeScale) return; - col = ImAlphaMultiply(col, diameter / _FringeScale); + col = ImAlphaMultiply(col, diameter * _InvFringeScale); radius = _FringeScale * 0.5f; } @@ -3000,12 +2996,12 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im return; if (diameter_x < _FringeScale) { - col = ImAlphaMultiply(col, diameter_x / _FringeScale); + col = ImAlphaMultiply(col, diameter_x * _InvFringeScale); rad.x = _FringeScale * 0.5f; } if (diameter_y < _FringeScale) { - col = ImAlphaMultiply(col, diameter_y / _FringeScale); + col = ImAlphaMultiply(col, diameter_y * _InvFringeScale); rad.y = _FringeScale * 0.5f; } } From 130be3be429ce3e985a5c264f226326696b432b1 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 2 Jun 2026 11:11:28 +0300 Subject: [PATCH 093/245] DrawList: Optimization: added specialized 2 point polyline _AddLine(). --- imgui.h | 1 + imgui_draw.cpp | 170 +++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 157 insertions(+), 14 deletions(-) diff --git a/imgui.h b/imgui.h index cf7f079b3..357915cd8 100644 --- a/imgui.h +++ b/imgui.h @@ -3546,6 +3546,7 @@ struct ImDrawList IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, const ImVec4& tex_uvs, ImDrawFlags flags); IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags); IMGUI_API void _AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe); + IMGUI_API void _AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe); IMGUI_API float _CalculateCenterBiasedOffset(float thickness); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3d1dbf533..f4925568f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1197,7 +1197,9 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. The texture scaling in this range will cause slight visual pops, so we generate super sampled textures in this range. // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH. constexpr float base_width = 1.0f; - const int texture_idx = ImClamp((int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f), 0, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); + int texture_idx = (int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f); + texture_idx = ImMax(texture_idx, 0); + texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; *out_fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. *out_tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; @@ -1205,7 +1207,9 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv else { // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. - const int texture_idx = ImClamp((int)(screen_thickness + 0.995f), 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + int texture_idx = (int)(screen_thickness + 0.995f); + texture_idx = ImMax(texture_idx, 2); + texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); *out_fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. *out_tex_uvs = _Data->TexUvLines[texture_idx]; } @@ -2126,6 +2130,150 @@ ImDrawFlags ImDrawList::_GetStrokePos(ImDrawFlags flags, ImDrawFlags default_str return _Data->OverrideStrokePos ? _Data->OverrideStrokePos : default_stroke_pos; } +void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) +{ + if (g_LEGACY_STROKES) IM_UNLIKELY + { + ImVec2 points[2] = { p1, p2 }; + AddPolylineLegacy(points, 2, col, thickness, flags); + return; + } + + if ((col & IM_COL32_A_MASK) == 0) IM_UNLIKELY + return; + + float screen_thickness = thickness * _InvFringeScale; + if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY + return; + if (screen_thickness < 1.0f) IM_UNLIKELY + { + col = ImAlphaMultiply(col, screen_thickness); + screen_thickness = 1.0f; + thickness = _FringeScale; + } + + ImVec4 tex_uvs; + float fringe; + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + + float dir_x = p2.x - p1.x; + float dir_y = p2.y - p1.y; + const float d2 = dir_x * dir_x + dir_y * dir_y; + const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; + dir_x *= inv_len; + dir_y *= inv_len; + const float norm_x = -dir_y; + const float norm_y = dir_x; + + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + + const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); + if (stroke_pos == ImDrawFlags_StrokeLegacy) + flags |= ImDrawFlags_MiterOnly | ImDrawFlags_NoAAEnds; + + float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) + if (stroke_pos == ImDrawFlags_StrokeOutside) + thickness0 = thickness + fringe * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + thickness0 = _CalculateCenterBiasedOffset(thickness) + fringe * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeInside) + thickness0 = fringe * 0.5f; + float thickness1 = (thickness + fringe) - thickness0; + + + const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; + const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. + ImVec2 uv0, uv1, uv2; + uv0.x = tex_uvs.x + half_texel; + uv0.y = tex_uvs.y; + uv1.x = tex_uvs.z - half_texel; + uv1.y = tex_uvs.y; + uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; + uv2.y = tex_uvs.y; + + const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. + const float half_thickness = thickness * 0.5f; + + if (flags & ImDrawFlags_NoAAEnds) + PrimReserve(2*3, 4); + else + PrimReserve(6*3, 8); + + int base_idx = (int)_VtxCurrentIdx; + + float p1_x = p1.x; + float p1_y = p1.y; + float p2_x = p2.x; + float p2_y = p2.y; + + if (flags & ImDrawFlags_SquareCap) + { + p1_x -= dir_x * half_thickness; + p1_y -= dir_y * half_thickness; + p2_x += dir_x * half_thickness; + p2_y += dir_y * half_thickness; + } + + // Start cap + if (flags & ImDrawFlags_NoAAEnds) + { + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(p1_x - norm_x * thickness0, p1_y - norm_y * thickness0, uv0, col); + IM_APPEND_VTX(p1_x + norm_x * thickness1, p1_y + norm_y * thickness1, uv1, col); + + IM_APPEND_VTX(p2_x - norm_x * thickness0, p2_y - norm_y * thickness0, uv0, col); + IM_APPEND_VTX(p2_x + norm_x * thickness1, p2_y + norm_y * thickness1, uv1, col); + + // Connect + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + } + else + { + // Start + float pa_x = p1_x - dir_x * half_aa; + float pa_y = p1_y - dir_y * half_aa; + float pb_x = p1_x + dir_x * half_aa; + float pb_y = p1_y + dir_y * half_aa; + + base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa_x - norm_x * thickness0, pa_y - norm_y * thickness0, uv0, col_trans); + IM_APPEND_VTX(pa_x + norm_x * thickness1, pa_y + norm_y * thickness1, uv1, col_trans); + + int next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pb_x - norm_x * thickness0, pb_y - norm_y * thickness0, uv0, col); + IM_APPEND_VTX(pb_x + norm_x * thickness1, pb_y + norm_y * thickness1, uv1, col); + + // AA cap + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + base_idx = next_base_idx; + + // End + pa_x = p2_x - dir_x * half_aa; + pa_y = p2_y - dir_y * half_aa; + pb_x = p2_x + dir_x * half_aa; + pb_y = p2_y + dir_y * half_aa; + + next_base_idx = (int)_VtxCurrentIdx; + IM_APPEND_VTX(pa_x - norm_x * thickness0, pa_y - norm_y * thickness0, uv0, col); + IM_APPEND_VTX(pa_x + norm_x * thickness1, pa_y + norm_y * thickness1, uv1, col); + + IM_APPEND_VTX(pb_x - norm_x * thickness0, pb_y - norm_y * thickness0, uv0, col_trans); + IM_APPEND_VTX(pb_x + norm_x * thickness1, pb_y + norm_y * thickness1, uv1, col_trans); + + // Connect + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + base_idx = next_base_idx; + + // AA cap + IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); + IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + + } +} + void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) @@ -2134,13 +2282,11 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { - const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; - AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); + _AddLine(ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f), col, thickness, flags); return; } - const ImVec2 points[2] = { p1, p2 }; - AddPolyline(points, 2, col, thickness, flags); + _AddLine(p1, p2, col, thickness, flags); } void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness, ImDrawFlags flags) @@ -2151,8 +2297,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { - const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); + _AddLine(ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f), col, thickness, flags); return; } @@ -2185,8 +2330,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // For generic case use line, since it needs less triangles than AA rectangle. - const ImVec2 points[2] = { ImVec2(min_x, y), ImVec2(max_x, y) }; - AddPolyline(points, 2, col, thickness, flags); + _AddLine(ImVec2(min_x, y), ImVec2(max_x, y), col, thickness, flags); } } @@ -2198,8 +2342,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { - const ImVec2 points[2] = { ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f) }; // Same as AddLine() above. - AddPolyline(points, 2, col, thickness, ImDrawFlags_StrokeLegacy); + _AddLine(ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f), col, thickness, flags); return; } @@ -2233,8 +2376,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th // For generic case use line, since it needs less triangles than AA rectangle. // Drawing for bottom to top, so that the inside stroke pos expands to right. - const ImVec2 points[2] = { ImVec2(x, max_y), ImVec2(x, min_y) }; - AddPolyline(points, 2, col, thickness, flags); + _AddLine(ImVec2(x, max_y), ImVec2(x, min_y), col, thickness, flags); } } From fc8f5e66d48521d6b78ea0b3502247747f367bc0 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 2 Jun 2026 12:27:39 +0300 Subject: [PATCH 094/245] DrawList: fixed indices when AllowVtxOffset is on - fix shape closing indices for AddPolyline and _AddRectTinyRounding --- imgui_draw.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f4925568f..c65bd7423 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1171,8 +1171,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ else { // Connect the path. - start_vtx_ptr[0] = VtxBuffer.Data[base_idx+0]; - start_vtx_ptr[1] = VtxBuffer.Data[base_idx+1]; + start_vtx_ptr[0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+0]; + start_vtx_ptr[1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+1]; } // Restore unused memory @@ -2494,6 +2494,7 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); + IM_ASSERT_PARANOID(idx_used <= idx_allocated && vtx_used <= vtx_allocated); if (idx_used < idx_allocated || vtx_used < vtx_allocated) PrimUnreserve(idx_allocated - idx_used, vtx_allocated - vtx_used); } @@ -2607,13 +2608,13 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, } // Close - start_vtx_ptr[0] = VtxBuffer.Data[base_idx + 0]; - start_vtx_ptr[1] = VtxBuffer.Data[base_idx + 1]; - start_vtx_ptr[2] = VtxBuffer.Data[base_idx + 2]; + start_vtx_ptr[0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 0]; + start_vtx_ptr[1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 1]; + start_vtx_ptr[2] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 2]; const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); - IM_ASSERT(idx_used <= idx_count && vtx_used <= vtx_count); + IM_ASSERT_PARANOID(idx_used <= idx_count && vtx_used <= vtx_count); if (idx_used < idx_count || vtx_used < vtx_count) PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); From a5a4bed3cafe74a330ff143b7374a17c9ee9e435 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 2 Jun 2026 14:41:58 +0300 Subject: [PATCH 095/245] DrawList: improved worst case vertex count for AddConvexPolyFilled, convex polys can have only 2 bevels verts. --- imgui_draw.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c65bd7423..d6a2bc5c4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -855,6 +855,7 @@ float ImDrawList::_CalculateCenterBiasedOffset(float thickness) #define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) #define IM_POLYLINE_MITER_LIMIT (4.0f) // ~29 deg +#define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // (int)(360/floor(180-29)) // In debug builds the functions are likely not inlined, so inlined check is cheaper. #if defined(DEBUG) || defined(_DEBUG) @@ -1068,7 +1069,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ if (sin_theta < 0.0f) { IM_APPEND_VTX(p1.x - (bn_x + sd_x) * thickness0, p1.y - (bn_y + sd_y) * thickness0, uv0, col); // 2 - // TODO: calc uv2 correctly. IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - (bn_x - sd_x) * thickness0, p1.y - (bn_y - sd_y) * thickness0, uv0, col); // 4 @@ -1086,7 +1086,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ else { IM_APPEND_VTX(p1.x + (bn_x + sd_x) * thickness1, p1.y + (bn_y + sd_y) * thickness1, uv1, col); // 2 - // TODO: calc uv2 correctly. IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 4 @@ -1559,8 +1558,8 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; - const int idx_count = ((points_count - 2) + points_count * 3) * 3; - const int vtx_count = (points_count * 3); + const int idx_count = ((points_count - 2) + points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) * 3; + const int vtx_count = points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS; PrimReserve(idx_count, vtx_count); ImDrawVert* start_vtx_ptr = _VtxWritePtr; ImDrawIdx* start_idx_ptr = _IdxWritePtr; @@ -1634,6 +1633,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun } else { + int bevel_count = 0; for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { // Average normals @@ -1679,8 +1679,12 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun unsigned int outer_idx = _VtxCurrentIdx; // Outer - if (bevel) + if (bevel && bevel_count < IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) IM_UNLIKELY { + // Because the polygon is convex, we know the maximum number of bevel corners we can hit (which is very small number). + // We keep track of them just in case the calculations disagree. + bevel_count++; + IM_APPEND_VTX(p1.x + n0.x * half_aa, p1.y + n0.y * half_aa, uv, col_trans); IM_APPEND_VTX(p1.x + n1.x * half_aa, p1.y + n1.y * half_aa, uv, col_trans); // Connect with previous From ea638a4a11395bbbe09cf18e1f2a92dde514d98c Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Tue, 2 Jun 2026 16:37:36 +0200 Subject: [PATCH 096/245] DrawList: added vertex offset 16-bit ImDrawIdx support for _AddPolyline --- imgui_draw.cpp | 80 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 67 insertions(+), 13 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d6a2bc5c4..c63ceba6d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -853,8 +853,8 @@ float ImDrawList::_CalculateCenterBiasedOffset(float thickness) _IdxWritePtr += 3; \ } (void)0 -#define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) -#define IM_POLYLINE_MITER_LIMIT (4.0f) // ~29 deg +#define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) +#define IM_POLYLINE_MITER_LIMIT (4.0f) // ~29 deg #define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // (int)(360/floor(180-29)) // In debug builds the functions are likely not inlined, so inlined check is cheaper. @@ -866,6 +866,41 @@ float ImDrawList::_CalculateCenterBiasedOffset(float thickness) #define IM_IS_TRUNCATED(a) ImIsTruncated(a) #endif +// Called when the current vertex count for a polyline call would overflow the index range. +// Commit the vertices so far, reserve new buffers, reset index, and duplicate the base vertices so that they can be accessed by the new indices. +static void SplitPolyline(ImDrawList* draw_list, int& start_idx_offset, int& start_vtx_offset, int& base_idx) +{ + // Make copy of current base points. + ImDrawVert base0 = draw_list->VtxBuffer.Data[draw_list->_CmdHeader.VtxOffset + base_idx + 0]; + ImDrawVert base1 = draw_list->VtxBuffer.Data[draw_list->_CmdHeader.VtxOffset + base_idx + 1]; + + // Release unused verts and indices. + const int cur_idx_offset = (int)(draw_list->_IdxWritePtr - draw_list->IdxBuffer.Data); + const int cur_vtx_offset = (int)(draw_list->_VtxWritePtr - draw_list->VtxBuffer.Data); + const int remaining_idx_count = draw_list->IdxBuffer.Size - cur_idx_offset; + const int remaining_vtx_count = draw_list->VtxBuffer.Size - cur_vtx_offset; + + IM_ASSERT(remaining_vtx_count >= 0 && remaining_idx_count >= 0); + draw_list->PrimUnreserve(remaining_idx_count, remaining_vtx_count); + + // Reserve remaining verts and indices. + draw_list->PrimReserve(remaining_idx_count, remaining_vtx_count + 2); // +2 for the duplicated base points. + + start_idx_offset = cur_idx_offset; + start_vtx_offset = cur_vtx_offset; + base_idx = (int)draw_list->_VtxCurrentIdx; + + // Duplicate base points + draw_list->_VtxWritePtr[0] = base0; + draw_list->_VtxWritePtr[1] = base1; + draw_list->_VtxWritePtr += 2; + draw_list->_VtxCurrentIdx += 2; +} + +#define IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(new_verts) \ + if (sizeof(ImDrawIdx) == 2 && (Flags & ImDrawListFlags_AllowVtxOffset) && _VtxCurrentIdx + (new_verts) > (1 << 16)) IM_UNLIKELY \ + SplitPolyline(this, start_idx_offset, start_vtx_offset, base_idx) + void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe) { const ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -918,9 +953,10 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ PrimReserve(idx_count, vtx_count); - ImDrawVert* start_vtx_ptr = _VtxWritePtr; - ImDrawIdx* start_idx_ptr = _IdxWritePtr; - + // These offsets change if we need to create new draw command mid shape. + const int first_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); + int start_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); + int start_idx_offset = (int)(_IdxWritePtr - IdxBuffer.Data); int base_idx = (int)_VtxCurrentIdx; ImVec2 pa, pb, dir; @@ -950,6 +986,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ if (flags & ImDrawFlags_NoAAEnds) { + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); + base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); @@ -961,6 +999,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ pb.x = p1.x + dir.x * half_aa; pb.y = p1.y + dir.y * half_aa; + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); + base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col_trans); IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col_trans); @@ -983,6 +1023,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ len_sqr1 = sqr_lengths[points_count-1]; // This will be filled later, allocate space. + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); + base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(0, 0, uv0, col); IM_APPEND_VTX(0, 0, uv1, col); @@ -1006,6 +1048,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; // Miter + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); + const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 3 @@ -1068,6 +1112,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ // Bevel if (sin_theta < 0.0f) { + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); + IM_APPEND_VTX(p1.x - (bn_x + sd_x) * thickness0, p1.y - (bn_y + sd_y) * thickness0, uv0, col); // 2 IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1085,6 +1131,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ } else { + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); + IM_APPEND_VTX(p1.x + (bn_x + sd_x) * thickness1, p1.y + (bn_y + sd_y) * thickness1, uv1, col); // 2 IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1103,6 +1151,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ } else { + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); + // Miter const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 @@ -1136,6 +1186,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ if (flags & ImDrawFlags_NoAAEnds) { + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); + IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); @@ -1150,6 +1202,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ pb.x = p1.x + dir.x * half_aa; pb.y = p1.y + dir.y * half_aa; + IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); + int next_base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col); @@ -1170,15 +1224,17 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ else { // Connect the path. - start_vtx_ptr[0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+0]; - start_vtx_ptr[1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+1]; + VtxBuffer.Data[first_vtx_offset + 0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+0]; + VtxBuffer.Data[first_vtx_offset + 1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+1]; } // Restore unused memory - const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); - const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); - IM_ASSERT(vtx_used <= vtx_count && idx_used <= idx_count); - PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); + const int cur_idx_offset = (int)(_IdxWritePtr - IdxBuffer.Data); + const int cur_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); + const int remaining_idx_count = IdxBuffer.Size - cur_idx_offset; + const int remaining_vtx_count = VtxBuffer.Size - cur_vtx_offset; + IM_ASSERT_PARANOID(remaining_idx_count >= 0 && remaining_vtx_count >= 0); + PrimUnreserve(remaining_idx_count, remaining_vtx_count); } static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) @@ -1237,8 +1293,6 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 thickness = _FringeScale; } - // TODO: support splitting very long lines to multiple draw calls. - // Allocate data for temp buffers _Data->TempBuffer.reserve_discard(points_count * 2); ImVec2* normals = _Data->TempBuffer.Data; From 16860367b34b52006724845ad9286133e4bb3293 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jun 2026 15:58:50 +0200 Subject: [PATCH 097/245] DrawList: Debug build optimizations: disable over zealous stack checks in PrimReserve, PrimUnreserve, PrimRect, PrimRectUV, PrimQuadUV, _CalculateCenterBiasedOffset, ImAlphaMultiply, _SelectFringeTexture + Undo inlined PrimRect() in AddRectFilled(). --- imgui_draw.cpp | 57 ++++++++++++++++++++++---------------------------- 1 file changed, 25 insertions(+), 32 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c63ceba6d..ebf0682d6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -728,6 +728,7 @@ void ImDrawList::_SetPixelDensity(float pixel_density) _FringeScaleIsInteger = ImIsTruncated(_InvFringeScale); } +IM_MSVC_RUNTIME_CHECKS_OFF // Reserve space for a number of vertices and indices. // You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or // submit the intermediate results. PrimUnreserve() can be used to release unused allocations. @@ -767,6 +768,26 @@ void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) IdxBuffer.shrink(IdxBuffer.Size - idx_count); } +// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. +// We avoid using the 'do { } while (false)` idiom in those macros as they typically have overhead in debug builds. +#define IM_APPEND_VTX(PX, PY, UV, COL) \ + { \ + _VtxWritePtr->pos.x = PX; \ + _VtxWritePtr->pos.y = PY; \ + _VtxWritePtr->uv = UV; \ + _VtxWritePtr->col = COL; \ + _VtxWritePtr++; \ + _VtxCurrentIdx++; \ + } (void)0 + +#define IM_APPEND_TRI(a, b, c) \ + { \ + _IdxWritePtr[0] = (ImDrawIdx)(a); \ + _IdxWritePtr[1] = (ImDrawIdx)(b); \ + _IdxWritePtr[2] = (ImDrawIdx)(c); \ + _IdxWritePtr += 3; \ + } (void)0 + // Fully unrolled with inline call to keep our debug builds decently fast. void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) { @@ -812,7 +833,6 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c _IdxWritePtr += 6; } - float ImDrawList::_CalculateCenterBiasedOffset(float thickness) { // Old jumpy one. @@ -825,6 +845,7 @@ float ImDrawList::_CalculateCenterBiasedOffset(float thickness) const int s_thickness = (int)screen_thickness; return ((float)(s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; } +IM_MSVC_RUNTIME_CHECKS_RESTORE // On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. // - Those macros expects l-values and need to be used as their own statement. @@ -833,26 +854,6 @@ float ImDrawList::_CalculateCenterBiasedOffset(float thickness) #define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) #define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0 -// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. -// We avoid using the 'do { } while (false)` idiom in those macros as they typically have overhead in debug builds. -#define IM_APPEND_VTX(PX, PY, UV, COL) \ - { \ - _VtxWritePtr->pos.x = PX; \ - _VtxWritePtr->pos.y = PY; \ - _VtxWritePtr->uv = UV; \ - _VtxWritePtr->col = COL; \ - _VtxWritePtr++; \ - _VtxCurrentIdx++; \ - } (void)0 - -#define IM_APPEND_TRI(a, b, c) \ - { \ - _IdxWritePtr[0] = (ImDrawIdx)(a); \ - _IdxWritePtr[1] = (ImDrawIdx)(b); \ - _IdxWritePtr[2] = (ImDrawIdx)(c); \ - _IdxWritePtr += 3; \ - } (void)0 - #define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) #define IM_POLYLINE_MITER_LIMIT (4.0f) // ~29 deg #define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // (int)(360/floor(180-29)) @@ -1237,6 +1238,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ PrimUnreserve(remaining_idx_count, remaining_vtx_count); } +IM_MSVC_RUNTIME_CHECKS_OFF static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) { IM_ASSERT_PARANOID(a >= 0.0f && a < 1.0f); // We don't clamp! @@ -1269,6 +1271,7 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv *out_tex_uvs = _Data->TexUvLines[texture_idx]; } } +IM_MSVC_RUNTIME_CHECKS_RESTORE extern bool g_LEGACY_STROKES; @@ -2914,17 +2917,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { PrimReserve(6, 4); - - const ImVec2 opaque_uv = _Data->TexUvWhitePixel; - const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p_min.x, p_min.y, opaque_uv, col); - IM_APPEND_VTX(p_max.x, p_min.y, opaque_uv, col); - IM_APPEND_VTX(p_max.x, p_max.y, opaque_uv, col); - IM_APPEND_VTX(p_min.x, p_max.y, opaque_uv, col); - - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - + PrimRect(p_min, p_max, col); return; } else if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) From c6e5d8c85f64a3dfb451cb2dd0d458b6820704a4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jun 2026 16:54:44 +0200 Subject: [PATCH 098/245] DrawList: Debug build optimizations: add non-template ImMin/ImMax/ImClamp for int/float to avoid missing out on IM_MSVC_RUNTIME_CHECKS_OFF. --- imgui_internal.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index d632533f3..28251df79 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -512,11 +512,17 @@ inline float ImRsqrtPrecise(float x) { const float r = _mm_cvtss_f32(_mm_rsq inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } inline float ImRsqrtPrecise(float x) { return 1.0f / sqrtf(x); } #endif -inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } +inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } #endif // - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double -// (Exceptionally using templates here but we could also redefine them for those types) +// (Specialized version ensure that runtime-check pragmas/macros are applied with caller settings. Template version are less reliable in this regards) +inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } +inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } +inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } +inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } +inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } template T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } template T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } template T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } From f2055fe160e75263cdfc0e70a972e1eb9cc878b6 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Wed, 3 Jun 2026 00:28:23 +0300 Subject: [PATCH 099/245] DrawList: fixed reserve counts in _AddPolyline(). --- imgui_draw.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ebf0682d6..2e474e8c2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -934,8 +934,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ } else { - vtx_count = /*body*/(points_count - 2) * max_verts_per_point + /*caps*/(6 * 2); - idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/4 + /*caps*/(4 * 2)) * 3; + vtx_count = /*body*/(points_count - 2) * max_verts_per_point + /*caps*/(4 * 2); + idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/2 + /*caps*/(2 * 2)) * 3; } From ec510539c7e1f934fa0aa6497154be5f3c2a2da6 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 00:43:36 +0300 Subject: [PATCH 100/245] DrawList: increase detailed line textures from 3px to 4px to better hide the texture change. + amend: align #defines. --- imgui.h | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 357915cd8..a0c51cdda 100644 --- a/imgui.h +++ b/imgui.h @@ -3202,27 +3202,22 @@ struct ImGuiSelectionExternalStorage // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- -// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. #endif - #ifndef IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (3) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] #endif - #ifndef IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT -#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (4) // How many samples per integer thickness level. +#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (4) // How many samples per integer thickness level. #endif - -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX (IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) - #ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX -#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) +#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) #endif #ifndef IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX -#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (4) // 0: fill, 1-3: strokes thickness +#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (4) // 0: fill, 1-3: strokes thickness #endif +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX (IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) // ImDrawIdx: vertex index. [Compile-time configurable type] // - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). From ed50e4790b8c0782b8f841040dae634339629f52 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 00:44:19 +0300 Subject: [PATCH 101/245] Demo: added rounding slider+animate to allow better test range of rounding values. --- imgui_demo.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e7d8473a9..b27736666 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10388,8 +10388,10 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Draw a bunch of primitives ImGui::Text("All primitives"); static float sz = 42.0f; - static bool animate_thickness = false; + static float base_rounding = 8.0f; static float base_thickness = 3.0f; + static bool animate_rounding = false; + static bool animate_thickness = false; static int ngon_segments = 6; static bool circle_segments_override = false; static int circle_segments_override_v = 12; @@ -10400,12 +10402,21 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); + const float rounding_anim_period = 8.0f; + const float rounding_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), rounding_anim_period) * (2.0f / rounding_anim_period) - 1.0f); + const float rounding = animate_rounding ? (float)((int)(rounding_wave * base_rounding * 10.0f)) / 10.0f : base_rounding; + ImGui::DragFloat("Rounding", &base_rounding, 0.02f, 0.0f, 30.0f, "%.02f"); + ImGui::SameLine(); + ImGui::Checkbox("Animate##rounding", &animate_rounding); + ImGui::SameLine(); + ImGui::Text("%.2f", rounding); + const float thickness_anim_period = 5.0f; const float thickness_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), thickness_anim_period) * (2.0f / thickness_anim_period) - 1.0f); const float thickness = animate_thickness ? thickness_wave * base_thickness : base_thickness; ImGui::DragFloat("Thickness", &base_thickness, 0.02f, 0.0f, 30.0f, "%.02f"); ImGui::SameLine(); - ImGui::Checkbox("Animate", &animate_thickness); + ImGui::Checkbox("Animate##thickness", &animate_thickness); ImGui::SameLine(); ImGui::Text("%.2f", thickness); @@ -10438,7 +10449,6 @@ static void ShowExampleAppCustomRendering(bool* p_open) const float pi = 3.141592f; const float spacing = 10.0f; const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; - const float rounding = sz / 5.0f; const float half_sz = sz * 0.5f; const float half_szi = (float)(int)(sz * 0.5f); const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; From 002e2a5f0085bc1e8e70d340e7f5597605a0dd37 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 00:57:20 +0300 Subject: [PATCH 102/245] DrawList: added macro to have consistent check for rounding - use macro to test if rounding value is worthy - changed threshold to be a bit smaller (for smoother handling of small radius), and relative to fringe --- imgui_draw.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2e474e8c2..30cff95bb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -847,6 +847,9 @@ float ImDrawList::_CalculateCenterBiasedOffset(float thickness) } IM_MSVC_RUNTIME_CHECKS_RESTORE +// Check if R is considered to be worthy rounding. Can be only used within ImDrawList due to use of _FringeScale. +#define IM_HAS_ROUNDING(RAD) ((RAD) >= (0.25f * _FringeScale)) + // On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. // - Those macros expects l-values and need to be used as their own statement. // - Those macros are intentionally not surrounded by the 'do {} while (0)' idiom because even that translates to runtime with debug compilers. @@ -1866,7 +1869,7 @@ void ImDrawList::AddConvexPolyFilledLegacy(const ImVec2* points, const int point void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step) { - if (radius < 0.5f) + if (!IM_HAS_ROUNDING(radius)) { _Path.push_back(center); return; @@ -1958,7 +1961,7 @@ void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_ void ImDrawList::_PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) { - if (radius < 0.5f) + if (!IM_HAS_ROUNDING(radius)) { _Path.push_back(center); return; @@ -1977,7 +1980,7 @@ void ImDrawList::_PathArcToN(const ImVec2& center, float radius, float a_min, fl // 0: East, 3: South, 6: West, 9: North, 12: East void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12) { - if (radius < 0.5f) + if (!IM_HAS_ROUNDING(radius)) { _Path.push_back(center); return; @@ -1987,7 +1990,7 @@ void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) { - if (radius < 0.5f) + if (!IM_HAS_ROUNDING(radius)) { _Path.push_back(center); return; @@ -2154,7 +2157,8 @@ void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawFlags flags) { - if (rounding >= 0.5f) + const bool has_rounding = IM_HAS_ROUNDING(rounding); + if (has_rounding) { if ((flags & ImDrawFlags_RoundCornersMask_) == 0) flags |= ImDrawFlags_RoundCornersAll; @@ -2162,7 +2166,7 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); } - if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { PathLineTo(a); PathLineTo(ImVec2(b.x, a.y)); @@ -2710,7 +2714,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - const bool has_rounding = (rounding >= _FringeScale * 0.5f); + const bool has_rounding = IM_HAS_ROUNDING(rounding); // Calculate the outer boundary of the rectangle based on the stroke position. ImVec2 outer_min = p_min; From 2edac09d9fefa631517fb12e9c6020e3b001939b Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 01:11:37 +0300 Subject: [PATCH 103/245] DrawList: fixed baked corners to better match polyline corners - added CalcArcStepAndCount() to calculate the step size consistently - _AddRectTinyRounding: fixed stem placement with thin lines (clamping was needed for an older version of the function) - _AddRectTinyRounding: fixed texture coordinates (uses if inner/outer were reversed) - use polygon instead of circle when calculating baked corner rounds (the circle was more accurate but looked different size comparet to polyline) --- imgui_draw.cpp | 157 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 122 insertions(+), 35 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 30cff95bb..4d4bff835 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1866,6 +1866,16 @@ void ImDrawList::AddConvexPolyFilledLegacy(const ImVec2* points, const int point } } +// Calculates arc step and step count for 90 degree arc. The calculated arc step will complete a 90 degree arc when stepped arc_step_count times. +IM_MSVC_RUNTIME_CHECKS_OFF +static void CalcArcStepAndCount(int segment_count, int& arc_step, int& arc_step_count) +{ + arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / segment_count, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); + arc_step_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step; + if ((arc_step * arc_step_count) != (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4)) // Make sure that the arc step can iterate 90 degree arc. + arc_step = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step_count; +} +IM_MSVC_RUNTIME_CHECKS_RESTORE void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step) { @@ -1877,10 +1887,17 @@ void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_ // Calculate arc auto segment step size if (a_step <= 0) - a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); - - // Make sure we never do steps larger than one quarter of the circle - a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); + { + // Calculate step size using the common function. No need to clamp, the step is already in range. + const int auto_seg_count = _CalcCircleAutoSegmentCount(radius); + int arc_step_count; + CalcArcStepAndCount(auto_seg_count, a_step, arc_step_count); + } + else + { + // Make sure we never do steps larger than one quarter of the circle + a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); + } const int sample_range = ImAbs(a_max_sample - a_min_sample); const int a_next_step = a_step; @@ -2582,8 +2599,10 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, float fringe; _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); - const int arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / this->_CalcCircleAutoSegmentCount(rounding), 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); - const int arc_point_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step + 1; + const int auto_seg_count = _CalcCircleAutoSegmentCount(rounding); + int arc_step, arc_step_count; + CalcArcStepAndCount(auto_seg_count, arc_step, arc_step_count); + const int arc_point_count = arc_step_count + 1; int vtx_count = (2 + arc_point_count) * 4 + 3; int idx_count = (4 + arc_point_count - 1) * 4 * 3; @@ -2605,17 +2624,15 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, thickness += fringe; rounding += half_fringe; - // We need to stem offset to be at least fringe scale away, to maintain the fringe size. - const float stem_offset = thickness - ImMax(thickness - rounding, _FringeScale); - + const float stem_offset = thickness - (thickness - rounding); const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; const float ratio = stem_offset / thickness; ImVec2 inner_uv, outer_uv, stem_uv; - inner_uv.x = tex_uvs.x + half_texel; - inner_uv.y = tex_uvs.y; - outer_uv.x = tex_uvs.z - half_texel; + outer_uv.x = tex_uvs.x + half_texel; outer_uv.y = tex_uvs.y; - stem_uv.x = inner_uv.x + (outer_uv.x - inner_uv.x) * ratio; + inner_uv.x = tex_uvs.z - half_texel; + inner_uv.y = tex_uvs.y; + stem_uv.x = outer_uv.x + (inner_uv.x - outer_uv.x) * ratio; stem_uv.y = tex_uvs.y; // Previous vertices, copied from the last vertices. @@ -2642,19 +2659,19 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, int a = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) * corner; for (int i = 0; i < arc_point_count; i++) { - IM_APPEND_VTX(center_x - _Data->ArcFastVtx[a].x * rounding, center_y - _Data->ArcFastVtx[a].y * rounding, inner_uv, col); + IM_APPEND_VTX(center_x - _Data->ArcFastVtx[a].x * rounding, center_y - _Data->ArcFastVtx[a].y * rounding, outer_uv, col); a = (a + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; } } else { - IM_APPEND_VTX(outer_x, outer_y, inner_uv, col); + IM_APPEND_VTX(outer_x, outer_y, outer_uv, col); } const int stem_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(stem_x, stem_y, stem_uv, col); const int inner_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(inner_x, inner_y, outer_uv, col); + IM_APPEND_VTX(inner_x, inner_y, inner_uv, col); // Arc if (is_rounded) @@ -5140,23 +5157,84 @@ static void ImFontAtlasBuildUpdateTexDataBasic(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); } -static ImU8 SampleCorner(float x, float y, float cx, float cy, float r) + +#define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles + +static int InitCornerGeometry(float cx, float cy, float rounding, float circle_segment_max_error, ImVec2* line_normals, float* line_distances) { - const float dx = ImMin(x, cx) - cx; - const float dy = ImMin(y, cy) - cy; - const float d = ImSqrt(dx*dx + dy*dy); - const float aa_width = 1.0f; - return (ImU8)(ImClamp(1.0f - (d - r + aa_width * 0.5f) / aa_width, 0.0f, 1.0f) * 255.0f); + // This tries to quite faithfully replication how we render the corners using tessellation. + // Older code sampled a circle SDF directly, but it had clearly visible discrepancy between the baked corners + // and tessellated corners due to circle_segment_max_error. + + const int auto_seg_count = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(rounding, circle_segment_max_error); + int arc_step, arc_step_count; + CalcArcStepAndCount(auto_seg_count, arc_step, arc_step_count); + const int arc_point_count = arc_step_count + 1; + + // Build arc of points, with straight segments at each end. + // . [n-2]..[n-1] + // .` + // . + // [1] x (cx,cy) + // : + // [0] + ImVec2 points[IM_DRAWLIST_CORNER_POINTS_MAX]; + int num_points = 0; + + points[num_points++] = ImVec2(cx - rounding, cy + 1.0f); + + float da = ((float)arc_step / (float)IM_DRAWLIST_ARCFAST_TABLE_SIZE) * IM_PI * 2.0f; + float a = IM_PI; + for (int i = 0; i < arc_point_count; i++) + { + float dx = cosf(a); + float dy = sinf(a); + points[num_points++] = ImVec2(cx + dx * rounding, cy + dy * rounding); + a += da; + } + + points[num_points++] = ImVec2(cx + 1.0f, cy - rounding); + + // Turn segments to half spaces. + for (int i = 0; i < num_points - 1; i++) + { + const ImVec2 diff = points[i + 1] - points[i]; + const float d2 = diff.x * diff.x + diff.y * diff.y; + const float inv_d = ImRsqrtPrecise(d2); + line_normals[i].x = diff.y * inv_d; // Normal points outwards + line_normals[i].y = -diff.x * inv_d; + line_distances[i] = -ImDot(points[i], line_normals[i]); + } + + return num_points - 1; } -static ImU8 SampleCornerStroke(float x, float y, float cx, float cy, float outer_r, float inner_r) +// Returns distance to convex shape limited by lines. +static float SampleConvex(float x, float y, const ImVec2* line_normals, const float* line_distances, int num_lines) { - const float dx = ImMin(x, cx) - cx; - const float dy = ImMin(y, cy) - cy; - const float d = ImSqrt(dx*dx + dy*dy); + float result = -FLT_MAX; + for (int i = 0; i < num_lines; i++) + { + const float d = line_normals[i].x * x + line_normals[i].y * y + line_distances[i]; + if (d > result) + result = d; + } + return result; +} + +static ImU8 SampleCorner(float x, float y, const ImVec2* line_normals, const float* line_distances, int num_lines) +{ + const float d = SampleConvex(x, y, line_normals, line_distances, num_lines); const float aa_width = 1.0f; - const float outer = 1.0f - (d - outer_r + aa_width * 0.5f) / aa_width; - const float inner = (d - inner_r + aa_width * 0.5f) / aa_width; + return (ImU8)(ImClamp(1.0f - (d + aa_width * 0.5f) / aa_width, 0.0f, 1.0f) * 255.0f); +} + +static ImU8 SampleCornerStroke(float x, float y, float thickness, const ImVec2* line_normals, const float* line_distances, int num_lines) +{ + const float d = SampleConvex(x, y, line_normals, line_distances, num_lines); + const float aa_width = 1.0f; + const float outer = 1.0f - (d + aa_width * 0.5f) / aa_width; + const float inner = (d + thickness + aa_width * 0.5f) / aa_width; return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.0f); } @@ -5169,6 +5247,11 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) ImTextureData* tex = atlas->TexData; ImFontAtlasBuilder* builder = atlas->Builder; + // FIXME-TEXCORNERS: Ideally we should pick up the max error from the styles, but it does not seem be to set by the time we build the data the first time. + float circle_segment_max_error = 0.30f; // Default matching ImGuiStyle::CircleTessellationMaxError. + // if (atlas->OwnerContext) + // circle_segment_max_error = atlas->OwnerContext->DrawListSharedData.CircleSegmentMaxError; + ImFontAtlasRect r; bool add_and_draw = atlas->GetCustomRect(builder->PackIdCornersTexData, &r) == false; if (add_and_draw) @@ -5207,6 +5290,9 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) int y = r.y; int row_height = 0; + ImVec2 line_normals[IM_DRAWLIST_CORNER_POINTS_MAX]; + float line_distances[IM_DRAWLIST_CORNER_POINTS_MAX]; + // Filled for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) { @@ -5218,9 +5304,10 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Corner circle const float cx = 1.0f + (float)(n+1); const float cy = 1.0f + (float)(n+1); - const float rad = (float)rounding; IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds before we start writing pixels + const int num_lines = InitCornerGeometry(cx, cy, (float)rounding, circle_segment_max_error, line_normals, line_distances); + // Write each slice if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) { @@ -5229,7 +5316,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, rad); + write_ptr[lx] = SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines); write_ptr += pitch; } } @@ -5240,7 +5327,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = IM_COL32(255, 255, 255, SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, rad)); + write_ptr[lx] = IM_COL32(255, 255, 255, SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines)); write_ptr += pitch; } } @@ -5270,11 +5357,11 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Corner circle const float cx = 1.0f + (float)(n + 1); const float cy = 1.0f + (float)(n + 1); - const float outer_rad = (float)rounding; - const float inner_rad = (float)(rounding - thickness); IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds before we start writing pixels + const int num_lines = InitCornerGeometry(cx, cy, (float)rounding, circle_segment_max_error, line_normals, line_distances); + // Write each slice if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) { @@ -5283,7 +5370,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, outer_rad, inner_rad); + write_ptr[lx] = SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines); write_ptr += pitch; } } @@ -5294,7 +5381,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, cx, cy, outer_rad, inner_rad)); + write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines)); write_ptr += pitch; } } From a5d8450a0f7d38d66a34c3890bff40925d33a080 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 10:28:18 +0300 Subject: [PATCH 104/245] DrawList: fixed overdraw of transparent rounded rectangles - transition earlier to _AddRectTinyRounding() to avoid overdraw issues --- imgui_draw.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4d4bff835..04262db88 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2624,7 +2624,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, thickness += fringe; rounding += half_fringe; - const float stem_offset = thickness - (thickness - rounding); + const float stem_offset = ImMin(rounding, thickness); // The function might get called with rounding slightly bigger than thickness, which is ok, but we should keep the stem inside the shape. const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; const float ratio = stem_offset / thickness; ImVec2 inner_uv, outer_uv, stem_uv; @@ -2829,7 +2829,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl } else { - if (thickness > outer_rounding) + // Switch to specialized rendering a bit early to avoid overdraw visible in transparent shapes. + if (thickness + (0.75f * _FringeScale) > outer_rounding) { // Special case rendering to avoid rendering artifacts at the corners. // If rendered using the regular polyline, the stroke will fold and leave artifact on the corner if rendered with transparency. From 478813c359cec417064aa9e0b0fd10d0b4abab63 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 10:30:04 +0300 Subject: [PATCH 105/245] DrawList: restored non-AA rendering mode. - the ImDrawListFlags_AntiAliasedFill and ImDrawListFlags_AntiAliasedLines flags work again - added non-AA rendering for polyline and convex poly filled - do not use corner textures when AA is not used - Add missing no-AA for single line case --- docs/CHANGELOG.txt | 2 - imgui_demo.cpp | 12 ++ imgui_draw.cpp | 355 ++++++++++++++++++++++++++------------------- 3 files changed, 214 insertions(+), 155 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bbc7e9c98..8720d1179 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -148,8 +148,6 @@ HOW TO UPDATE? - Tree: hierarchy lines (when thickness>1.0f). - TabBar: selected overline border ((when thickness>1.0f). - Demo: Custom Rendering: canvas lines. -- (Breaking) Removed support for non-aliased shapes. - - Clearing `ImDrawListFlags_AntiAliasedLines` / `ImDrawListFlags_AntiAliasedFill` will have no effect. - Demo: Custom Rendering: exposed new flags; Showcasing overlapping strokes and filled shapes; Added an option to animation thickness; Added new shapes to showcase new rendering features that previously hit limitations. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b27736666..7e52eaf34 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10445,6 +10445,16 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Spacing(); const ImDrawFlags flags = stroke_flags | other_flags; + // FIXME: Clarify how this is exposed, consider changing Demo code to simply alter Style.s + static ImDrawListFlags draw_list_flags = ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill | ImDrawListFlags_RoundCornersUseTex; + ImGui::Text("DrawList Flags:"); + ImGui::CheckboxFlags("AntiAliasedLines", &draw_list_flags, ImDrawListFlags_AntiAliasedLines); ImGui::SameLine(); + ImGui::CheckboxFlags("AntiAliasedFill", &draw_list_flags, ImDrawListFlags_AntiAliasedFill); ImGui::SameLine(); + ImGui::CheckboxFlags("RoundCornersUseTex", &draw_list_flags, ImDrawListFlags_RoundCornersUseTex); + ImDrawListFlags backup_draw_list_flags = draw_list->Flags; + draw_list->Flags &= ~(ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill | ImDrawListFlags_RoundCornersUseTex); + draw_list->Flags |= draw_list_flags; + ImVec2 start_pos = ImGui::GetCursorScreenPos(); const float pi = 3.141592f; const float spacing = 10.0f; @@ -10577,6 +10587,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::PopItemFlag(); ImGui::PopItemWidth(); ImGui::EndTabItem(); + + draw_list->Flags = backup_draw_list_flags; } if (ImGui::BeginTabItem("Canvas")) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 04262db88..fcd253b74 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1333,7 +1333,18 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 ImVec4 tex_uvs; float fringe; - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + if (Flags & ImDrawListFlags_AntiAliasedLines) + { + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + } + else + { + tex_uvs.x = _Data->TexUvWhitePixel.x; + tex_uvs.y = _Data->TexUvWhitePixel.y; + tex_uvs.z = _Data->TexUvWhitePixel.x; + tex_uvs.w = _Data->TexUvWhitePixel.y; + fringe = 0.0f; + } _AddPolyline(points, normals, sqr_lengths, points_count, col, thickness, flags, tex_uvs, fringe); } @@ -1613,175 +1624,187 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun }*/ const ImVec2 uv = _Data->TexUvWhitePixel; - const float half_aa = _FringeScale * 0.5f; - ImU32 col_trans = col & ~IM_COL32_A_MASK; - const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; - const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; - - const int idx_count = ((points_count - 2) + points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) * 3; - const int vtx_count = points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS; - PrimReserve(idx_count, vtx_count); - ImDrawVert* start_vtx_ptr = _VtxWritePtr; - ImDrawIdx* start_idx_ptr = _IdxWritePtr; - - // Compute normals and segment lengths - _Data->TempBuffer.reserve_discard(points_count * 2); - ImVec2* temp_normals = _Data->TempBuffer.Data; - float* temp_sqr_lengths = (float*)(_Data->TempBuffer.Data + points_count); - for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + if (Flags & ImDrawListFlags_AntiAliasedFill) { - const ImVec2& p0 = points[i0]; - const ImVec2& p1 = points[i1]; - float dx = p1.x - p0.x; - float dy = p1.y - p0.y; - float d2 = dx*dx + dy*dy; - if (d2 > 0.0f) - { - const float inv_len = ImRsqrtPrecise(d2); - dx *= inv_len; - dy *= inv_len; - } - temp_normals[i0].x = dy; - temp_normals[i0].y = -dx; - temp_sqr_lengths[i0] = d2; - } + const float half_aa = _FringeScale * 0.5f; + ImU32 col_trans = col & ~IM_COL32_A_MASK; + const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; + const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; + const int idx_count = ((points_count - 2) + points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) * 3; + const int vtx_count = points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS; + PrimReserve(idx_count, vtx_count); + ImDrawVert* start_vtx_ptr = _VtxWritePtr; + ImDrawIdx* start_idx_ptr = _IdxWritePtr; - unsigned int vtx_inner_idx = _VtxCurrentIdx; - ImDrawVert* inner_vtx_ptr = _VtxWritePtr; - _VtxWritePtr += points_count; - _VtxCurrentIdx += points_count; - - unsigned int prev_outer_idx = 0; // We dont know outer vert could yet, will need to patch once we're done. - - - if (miters_only) - { + // Compute normals and segment lengths + _Data->TempBuffer.reserve_discard(points_count * 2); + ImVec2* temp_normals = _Data->TempBuffer.Data; + float* temp_sqr_lengths = (float*)(_Data->TempBuffer.Data + points_count); for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { - // Average normals - const ImVec2 p1 = points[i1]; - const ImVec2 n0 = temp_normals[i0]; - const ImVec2 n1 = temp_normals[i1]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); - const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor * half_aa; - const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor * half_aa; - - // Inner - inner_vtx_ptr->pos.x = p1.x - miter_offset_x; - inner_vtx_ptr->pos.y = p1.y - miter_offset_y; - inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; - inner_vtx_ptr++; - - const unsigned int prev_inner_idx = vtx_inner_idx + i0; - const unsigned int inner_idx = vtx_inner_idx + i1; - const unsigned int outer_idx = _VtxCurrentIdx; - - // Outer - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv, col_trans); - // Connect with previous - IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); - IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); - - prev_outer_idx = outer_idx; + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + float dx = p1.x - p0.x; + float dy = p1.y - p0.y; + float d2 = dx * dx + dy * dy; + if (d2 > 0.0f) + { + const float inv_len = ImRsqrtPrecise(d2); + dx *= inv_len; + dy *= inv_len; + } + temp_normals[i0].x = dy; + temp_normals[i0].y = -dx; + temp_sqr_lengths[i0] = d2; } - } - else - { - int bevel_count = 0; - for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + + unsigned int vtx_inner_idx = _VtxCurrentIdx; + ImDrawVert* inner_vtx_ptr = _VtxWritePtr; + _VtxWritePtr += points_count; + _VtxCurrentIdx += points_count; + + unsigned int prev_outer_idx = 0; // We don't know outer vert could yet, will need to patch once we're done. + if (miters_only) { - // Average normals - const ImVec2 p1 = points[i1]; - const ImVec2 n0 = temp_normals[i0]; - const ImVec2 n1 = temp_normals[i1]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); - float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; - float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; - - const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - bool bevel = miter_distance_sqr > miter_distance_limit_sqr; - if (bevel) + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { - // Limit inner bevel so that it is does not shoot out outside the polygon. - const float ref_thickness_sqr = half_aa * half_aa; - const float limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); - const float ref_miter_dist_sqr = miter_distance_sqr * ref_thickness_sqr; - if (ref_miter_dist_sqr > limit_sqr) - { - const float scale = ImSqrt(limit_sqr / ref_miter_dist_sqr); - miter_offset_x *= scale; - miter_offset_y *= scale; - } - } + // Average normals + const ImVec2 p1 = points[i1]; + const ImVec2 n0 = temp_normals[i0]; + const ImVec2 n1 = temp_normals[i1]; - miter_offset_x *= half_aa; - miter_offset_y *= half_aa; + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. + const float miter_scale_factor = ImMin(1000.f, 1.0f / (1.0f + cos_theta_clamped)); + const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor * half_aa; + const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor * half_aa; - // Inner - inner_vtx_ptr->pos.x = p1.x - miter_offset_x; - inner_vtx_ptr->pos.y = p1.y - miter_offset_y; - inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; - inner_vtx_ptr++; + // Inner + inner_vtx_ptr->pos.x = p1.x - miter_offset_x; + inner_vtx_ptr->pos.y = p1.y - miter_offset_y; + inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; + inner_vtx_ptr++; - const unsigned int prev_inner_idx = vtx_inner_idx + i0; - const unsigned int inner_idx = vtx_inner_idx + i1; - unsigned int outer_idx = _VtxCurrentIdx; + const unsigned int prev_inner_idx = vtx_inner_idx + i0; + const unsigned int inner_idx = vtx_inner_idx + i1; + const unsigned int outer_idx = _VtxCurrentIdx; - // Outer - if (bevel && bevel_count < IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) IM_UNLIKELY - { - // Because the polygon is convex, we know the maximum number of bevel corners we can hit (which is very small number). - // We keep track of them just in case the calculations disagree. - bevel_count++; - - IM_APPEND_VTX(p1.x + n0.x * half_aa, p1.y + n0.y * half_aa, uv, col_trans); - IM_APPEND_VTX(p1.x + n1.x * half_aa, p1.y + n1.y * half_aa, uv, col_trans); - // Connect with previous - IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); - IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); - // Fill bevel - IM_APPEND_TRI(outer_idx, outer_idx + 1, inner_idx); - outer_idx++; - } - else - { + // Outer IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv, col_trans); // Connect with previous IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); + + prev_outer_idx = outer_idx; } - - prev_outer_idx = outer_idx; } + else + { + int bevel_count = 0; + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2 p1 = points[i1]; + const ImVec2 n0 = temp_normals[i0]; + const ImVec2 n1 = temp_normals[i1]; + + // theta is the angle between two segments + const float cos_theta = n0.x * n1.x + n0.y * n1.y; + // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm + const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. + const float miter_scale_factor = ImMin(1000.f, 1.0f / (1.0f + cos_theta_clamped)); + float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; + float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; + + const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; + bool bevel = miter_distance_sqr > miter_distance_limit_sqr; + if (bevel) + { + // Limit inner bevel so that it is does not shoot out outside the polygon. + const float ref_thickness_sqr = half_aa * half_aa; + const float limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); + const float ref_miter_dist_sqr = miter_distance_sqr * ref_thickness_sqr; + if (ref_miter_dist_sqr > limit_sqr) + { + const float scale = ImSqrt(limit_sqr / ref_miter_dist_sqr); + miter_offset_x *= scale; + miter_offset_y *= scale; + } + } + + miter_offset_x *= half_aa; + miter_offset_y *= half_aa; + + // Inner + inner_vtx_ptr->pos.x = p1.x - miter_offset_x; + inner_vtx_ptr->pos.y = p1.y - miter_offset_y; + inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; + inner_vtx_ptr++; + + const unsigned int prev_inner_idx = vtx_inner_idx + i0; + const unsigned int inner_idx = vtx_inner_idx + i1; + unsigned int outer_idx = _VtxCurrentIdx; + + // Outer + if (bevel && bevel_count < IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) IM_UNLIKELY + { + // Because the polygon is convex, we know the maximum number of bevel corners we can hit (which is very small number). + // We keep track of them just in case the calculations disagree. + bevel_count++; + + IM_APPEND_VTX(p1.x + n0.x * half_aa, p1.y + n0.y * half_aa, uv, col_trans); + IM_APPEND_VTX(p1.x + n1.x * half_aa, p1.y + n1.y * half_aa, uv, col_trans); + // Connect with previous + IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); + IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); + // Fill bevel + IM_APPEND_TRI(outer_idx, outer_idx + 1, inner_idx); + outer_idx++; + } + else + { + IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv, col_trans); + // Connect with previous + IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); + IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); + } + + prev_outer_idx = outer_idx; + } + } + + // Patch first segment to wrap around + start_idx_ptr[0] = (ImDrawIdx)prev_outer_idx; + start_idx_ptr[3] = (ImDrawIdx)prev_outer_idx; + + // Add indices for fill + for (int i = 2; i < points_count; i++) + { + IM_APPEND_TRI(vtx_inner_idx, vtx_inner_idx + i - 1, vtx_inner_idx + i); + } + + const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); + const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); + IM_ASSERT(idx_used <= idx_count && vtx_used <= vtx_count); + + if (idx_used < idx_count || vtx_used < vtx_count) + PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } - - // Patch first segment to wrap around - start_idx_ptr[0] = (ImDrawIdx)prev_outer_idx; - start_idx_ptr[3] = (ImDrawIdx)prev_outer_idx; - - // Add indices for fill - for (int i = 2; i < points_count; i++) + else { - IM_APPEND_TRI(vtx_inner_idx, vtx_inner_idx + i - 1, vtx_inner_idx + i); + // Non Anti-aliased Fill + const int idx_count = (points_count - 2) * 3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + int base_idx = _VtxCurrentIdx; + for (int i = 0; i < vtx_count; i++) + IM_APPEND_VTX(points[i].x, points[i].y, uv, col); + for (int i = 2; i < points_count; i++) + IM_APPEND_TRI(base_idx, base_idx + i - 1, base_idx + i); } - - const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); - const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); - IM_ASSERT(idx_used <= idx_count && vtx_used <= vtx_count); - - if (idx_used < idx_count || vtx_used < vtx_count) - PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } void ImDrawList::AddConvexPolyFilledLegacy(const ImVec2* points, const int points_count, ImU32 col) @@ -2236,7 +2259,18 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t ImVec4 tex_uvs; float fringe; - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + if (Flags & ImDrawListFlags_AntiAliasedLines) + { + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + } + else + { + tex_uvs.x = _Data->TexUvWhitePixel.x; + tex_uvs.y = _Data->TexUvWhitePixel.y; + tex_uvs.z = _Data->TexUvWhitePixel.x; + tex_uvs.w = _Data->TexUvWhitePixel.y; + fringe = 0.0f; + } float dir_x = p2.x - p1.x; float dir_y = p2.y - p1.y; @@ -2597,7 +2631,18 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImVec4 tex_uvs; float fringe; - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + if (Flags & ImDrawListFlags_AntiAliasedLines) + { + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + } + else + { + tex_uvs.x = _Data->TexUvWhitePixel.x; + tex_uvs.y = _Data->TexUvWhitePixel.y; + tex_uvs.z = _Data->TexUvWhitePixel.x; + tex_uvs.w = _Data->TexUvWhitePixel.y; + fringe = 0.0f; + } const int auto_seg_count = _CalcCircleAutoSegmentCount(rounding); int arc_step, arc_step_count; @@ -2808,7 +2853,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + // Textured corners are baked with AA, do not use them if no-AA is requested. + const bool allow_tex_corners = (Flags & (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedLines)) == (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedLines); + if (allow_tex_corners && s_thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { // Pixel aligned rect with round corners rendered using baked textures. IM_ASSERT_PARANOID(s_thickness > 0 && s_rounding > 0); @@ -2942,7 +2989,9 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c PrimRect(p_min, p_max, col); return; } - else if ((Flags & ImDrawListFlags_RoundCornersUseTex) && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + // Textured corners are baked with AA, do not use them if no-AA is requested. + const bool allow_tex_corners = (Flags & (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedFill)) == (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedFill); + if (allow_tex_corners && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); const int size = ImMax(2, s_rounding); // This is matching the baking calculations. From 9be9c998d7488ac705cbfd4921db010dbe61a964 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 11:13:40 +0300 Subject: [PATCH 106/245] DrawList: removed vertex offset overflow (for 16-bit ImDrawIdx support) handling. This seems unnecessary for now. --- imgui_draw.cpp | 56 -------------------------------------------------- 1 file changed, 56 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index fcd253b74..0564ebd91 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -870,41 +870,6 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE #define IM_IS_TRUNCATED(a) ImIsTruncated(a) #endif -// Called when the current vertex count for a polyline call would overflow the index range. -// Commit the vertices so far, reserve new buffers, reset index, and duplicate the base vertices so that they can be accessed by the new indices. -static void SplitPolyline(ImDrawList* draw_list, int& start_idx_offset, int& start_vtx_offset, int& base_idx) -{ - // Make copy of current base points. - ImDrawVert base0 = draw_list->VtxBuffer.Data[draw_list->_CmdHeader.VtxOffset + base_idx + 0]; - ImDrawVert base1 = draw_list->VtxBuffer.Data[draw_list->_CmdHeader.VtxOffset + base_idx + 1]; - - // Release unused verts and indices. - const int cur_idx_offset = (int)(draw_list->_IdxWritePtr - draw_list->IdxBuffer.Data); - const int cur_vtx_offset = (int)(draw_list->_VtxWritePtr - draw_list->VtxBuffer.Data); - const int remaining_idx_count = draw_list->IdxBuffer.Size - cur_idx_offset; - const int remaining_vtx_count = draw_list->VtxBuffer.Size - cur_vtx_offset; - - IM_ASSERT(remaining_vtx_count >= 0 && remaining_idx_count >= 0); - draw_list->PrimUnreserve(remaining_idx_count, remaining_vtx_count); - - // Reserve remaining verts and indices. - draw_list->PrimReserve(remaining_idx_count, remaining_vtx_count + 2); // +2 for the duplicated base points. - - start_idx_offset = cur_idx_offset; - start_vtx_offset = cur_vtx_offset; - base_idx = (int)draw_list->_VtxCurrentIdx; - - // Duplicate base points - draw_list->_VtxWritePtr[0] = base0; - draw_list->_VtxWritePtr[1] = base1; - draw_list->_VtxWritePtr += 2; - draw_list->_VtxCurrentIdx += 2; -} - -#define IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(new_verts) \ - if (sizeof(ImDrawIdx) == 2 && (Flags & ImDrawListFlags_AllowVtxOffset) && _VtxCurrentIdx + (new_verts) > (1 << 16)) IM_UNLIKELY \ - SplitPolyline(this, start_idx_offset, start_vtx_offset, base_idx) - void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe) { const ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -957,10 +922,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ PrimReserve(idx_count, vtx_count); - // These offsets change if we need to create new draw command mid shape. const int first_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); - int start_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); - int start_idx_offset = (int)(_IdxWritePtr - IdxBuffer.Data); int base_idx = (int)_VtxCurrentIdx; ImVec2 pa, pb, dir; @@ -990,8 +952,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ if (flags & ImDrawFlags_NoAAEnds) { - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); - base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); @@ -1003,8 +963,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ pb.x = p1.x + dir.x * half_aa; pb.y = p1.y + dir.y * half_aa; - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); - base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col_trans); IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col_trans); @@ -1027,8 +985,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ len_sqr1 = sqr_lengths[points_count-1]; // This will be filled later, allocate space. - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); - base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(0, 0, uv0, col); IM_APPEND_VTX(0, 0, uv1, col); @@ -1052,8 +1008,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; // Miter - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 3 @@ -1116,8 +1070,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ // Bevel if (sin_theta < 0.0f) { - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); - IM_APPEND_VTX(p1.x - (bn_x + sd_x) * thickness0, p1.y - (bn_y + sd_y) * thickness0, uv0, col); // 2 IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1135,8 +1087,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ } else { - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); - IM_APPEND_VTX(p1.x + (bn_x + sd_x) * thickness1, p1.y + (bn_y + sd_y) * thickness1, uv1, col); // 2 IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; @@ -1155,8 +1105,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ } else { - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); - // Miter const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 @@ -1190,8 +1138,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ if (flags & ImDrawFlags_NoAAEnds) { - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(2); - IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); @@ -1206,8 +1152,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ pb.x = p1.x + dir.x * half_aa; pb.y = p1.y + dir.y * half_aa; - IM_ADD_POLYLINE_HANDLE_VTX_OFFSET_OVERFLOW(4); - int next_base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col); From f272141a4d9ee4548b4e1898c1c0c3dc4acd51ab Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 11:17:16 +0300 Subject: [PATCH 107/245] DrawList: merged _AddPolyline back into AddPolyline. - AddPolyline used to call different versions of _AddPolyline, the separation is not needed anymore, one less function call in debug mode --- imgui.h | 1 - imgui_draw.cpp | 242 ++++++++++++++++++++++++------------------------- 2 files changed, 118 insertions(+), 125 deletions(-) diff --git a/imgui.h b/imgui.h index a0c51cdda..d38f58e48 100644 --- a/imgui.h +++ b/imgui.h @@ -3540,7 +3540,6 @@ struct ImDrawList IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, const ImVec4& tex_uvs, ImDrawFlags flags); IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe); IMGUI_API void _AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0564ebd91..e31a08874 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -870,8 +870,111 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE #define IM_IS_TRUNCATED(a) ImIsTruncated(a) #endif -void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_lengths, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, const ImVec4& tex_uvs, float fringe) +IM_MSVC_RUNTIME_CHECKS_OFF +static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) { + IM_ASSERT_PARANOID(a >= 0.0f && a < 1.0f); // We don't clamp! + ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; + a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range. + return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); +} + +void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe) +{ + if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) + { + // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. The texture scaling in this range will cause slight visual pops, so we generate super sampled textures in this range. + // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH. + constexpr float base_width = 1.0f; + int texture_idx = (int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f); + texture_idx = ImMax(texture_idx, 0); + texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); + const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; + *out_fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. + *out_tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; + } + else + { + // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. + int texture_idx = (int)(screen_thickness + 0.995f); + texture_idx = ImMax(texture_idx, 2); + texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + *out_fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. + *out_tex_uvs = _Data->TexUvLines[texture_idx]; + } +} +IM_MSVC_RUNTIME_CHECKS_RESTORE + +extern bool g_LEGACY_STROKES; + +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) +{ + if (g_LEGACY_STROKES) + { + AddPolylineLegacy(points, points_count, col, thickness, flags); + return; + } + + if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) + return; + + float screen_thickness = thickness * _InvFringeScale; + if (screen_thickness < 1.0f / 255.0f) + return; + if (screen_thickness < 1.0f) + { + col = ImAlphaMultiply(col, screen_thickness); + screen_thickness = 1.0f; + thickness = _FringeScale; + } + + // Allocate data for temp buffers + _Data->TempBuffer.reserve_discard(points_count * 2); + ImVec2* normals = _Data->TempBuffer.Data; + float* sqr_lengths = (float*)(normals + points_count); + + // Calculate normals for each line segment + for (int i = 0; i < points_count - 1; i++) + { + float dx = points[i + 1].x - points[i].x; + float dy = points[i + 1].y - points[i].y; + const float d2 = dx * dx + dy * dy; + const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; + normals[i].x = -dy * inv_len; + normals[i].y = dx * inv_len; + sqr_lengths[i] = d2; + } + if ((flags & ImDrawFlags_Closed) != 0) + { + const float dx = points[0].x - points[points_count - 1].x; + const float dy = points[0].y - points[points_count - 1].y; + const float d2 = dx * dx + dy * dy; + const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; + normals[points_count - 1].x = -dy * inv_len; + normals[points_count - 1].y = dx * inv_len; + sqr_lengths[points_count - 1] = d2; + } + else + { + normals[points_count - 1] = normals[points_count - 2]; + sqr_lengths[points_count - 1] = 0.0f; + } + + ImVec4 tex_uvs; + float fringe; + if (Flags & ImDrawListFlags_AntiAliasedLines) + { + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); + } + else + { + tex_uvs.x = _Data->TexUvWhitePixel.x; + tex_uvs.y = _Data->TexUvWhitePixel.y; + tex_uvs.z = _Data->TexUvWhitePixel.x; + tex_uvs.w = _Data->TexUvWhitePixel.y; + fringe = 0.0f; + } + const ImU32 col_trans = col & ~IM_COL32_A_MASK; const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); @@ -883,12 +986,12 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) - if (stroke_pos == ImDrawFlags_StrokeOutside) - thickness0 = thickness + fringe * 0.5f; + if (stroke_pos == ImDrawFlags_StrokeOutside) + thickness0 = thickness + fringe * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) thickness0 = _CalculateCenterBiasedOffset(thickness) + fringe * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeInside) - thickness0 = fringe * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeInside) + thickness0 = fringe * 0.5f; float thickness1 = (thickness + fringe) - thickness0; int idx_count = 0; @@ -905,7 +1008,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ vtx_count = /*body*/(points_count - 2) * max_verts_per_point + /*caps*/(4 * 2); idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/2 + /*caps*/(2 * 2)) * 3; } - + PrimReserve(idx_count, vtx_count); const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. @@ -920,8 +1023,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; - PrimReserve(idx_count, vtx_count); - const int first_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); int base_idx = (int)_VtxCurrentIdx; @@ -980,9 +1081,9 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ else { // Wrap around segment - p1 = points[points_count-1]; - n1 = normals[points_count-1]; - len_sqr1 = sqr_lengths[points_count-1]; + p1 = points[points_count - 1]; + n1 = normals[points_count - 1]; + len_sqr1 = sqr_lengths[points_count - 1]; // This will be filled later, allocate space. base_idx = (int)_VtxCurrentIdx; @@ -1124,8 +1225,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ // End cap if (!closed) { - p1 = points[points_count-1]; - n1 = normals[points_count-1]; + p1 = points[points_count - 1]; + n1 = normals[points_count - 1]; // End cap dir.x = n1.y; @@ -1172,8 +1273,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ else { // Connect the path. - VtxBuffer.Data[first_vtx_offset + 0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+0]; - VtxBuffer.Data[first_vtx_offset + 1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx+1]; + VtxBuffer.Data[first_vtx_offset + 0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 0]; + VtxBuffer.Data[first_vtx_offset + 1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 1]; } // Restore unused memory @@ -1185,113 +1286,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, ImVec2* normals, float* sqr_ PrimUnreserve(remaining_idx_count, remaining_vtx_count); } -IM_MSVC_RUNTIME_CHECKS_OFF -static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) -{ - IM_ASSERT_PARANOID(a >= 0.0f && a < 1.0f); // We don't clamp! - ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; - a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range. - return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); -} - -void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe) -{ - if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) - { - // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. The texture scaling in this range will cause slight visual pops, so we generate super sampled textures in this range. - // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH. - constexpr float base_width = 1.0f; - int texture_idx = (int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f); - texture_idx = ImMax(texture_idx, 0); - texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); - const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; - *out_fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. - *out_tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; - } - else - { - // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. - int texture_idx = (int)(screen_thickness + 0.995f); - texture_idx = ImMax(texture_idx, 2); - texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - *out_fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. - *out_tex_uvs = _Data->TexUvLines[texture_idx]; - } -} -IM_MSVC_RUNTIME_CHECKS_RESTORE - -extern bool g_LEGACY_STROKES; - -void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) -{ - if (g_LEGACY_STROKES) - { - AddPolylineLegacy(points, points_count, col, thickness, flags); - return; - } - - if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) - return; - - float screen_thickness = thickness * _InvFringeScale; - if (screen_thickness < 1.0f / 255.0f) - return; - if (screen_thickness < 1.0f) - { - col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.0f; - thickness = _FringeScale; - } - - // Allocate data for temp buffers - _Data->TempBuffer.reserve_discard(points_count * 2); - ImVec2* normals = _Data->TempBuffer.Data; - float* sqr_lengths = (float*)(normals + points_count); - - // Calculate normals for each line segment - for (int i = 0; i < points_count - 1; i++) - { - float dx = points[i + 1].x - points[i].x; - float dy = points[i + 1].y - points[i].y; - const float d2 = dx * dx + dy * dy; - const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; - normals[i].x = -dy * inv_len; - normals[i].y = dx * inv_len; - sqr_lengths[i] = d2; - } - if ((flags & ImDrawFlags_Closed) != 0) - { - const float dx = points[0].x - points[points_count - 1].x; - const float dy = points[0].y - points[points_count - 1].y; - const float d2 = dx * dx + dy * dy; - const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; - normals[points_count - 1].x = -dy * inv_len; - normals[points_count - 1].y = dx * inv_len; - sqr_lengths[points_count - 1] = d2; - } - else - { - normals[points_count - 1] = normals[points_count - 2]; - sqr_lengths[points_count - 1] = 0.0f; - } - - ImVec4 tex_uvs; - float fringe; - if (Flags & ImDrawListFlags_AntiAliasedLines) - { - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); - } - else - { - tex_uvs.x = _Data->TexUvWhitePixel.x; - tex_uvs.y = _Data->TexUvWhitePixel.y; - tex_uvs.z = _Data->TexUvWhitePixel.x; - tex_uvs.w = _Data->TexUvWhitePixel.y; - fringe = 0.0f; - } - _AddPolyline(points, normals, sqr_lengths, points_count, col, thickness, flags, tex_uvs, fringe); -} - void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) @@ -1622,7 +1616,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun const float cos_theta = n0.x * n1.x + n0.y * n1.y; // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.f, 1.0f / (1.0f + cos_theta_clamped)); + const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor * half_aa; const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor * half_aa; @@ -1659,7 +1653,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun const float cos_theta = n0.x * n1.x + n0.y * n1.y; // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.f, 1.0f / (1.0f + cos_theta_clamped)); + const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; From d24d23fb408fc04c03558246a6e337bcd24ba72a Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 4 Jun 2026 15:57:43 +0300 Subject: [PATCH 108/245] DrawList: No AA ends when line AA is disabled --- imgui_draw.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e31a08874..d8402b10a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -973,6 +973,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 tex_uvs.z = _Data->TexUvWhitePixel.x; tex_uvs.w = _Data->TexUvWhitePixel.y; fringe = 0.0f; + flags |= ImDrawFlags_NoAAEnds; } const ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -2208,6 +2209,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t tex_uvs.z = _Data->TexUvWhitePixel.x; tex_uvs.w = _Data->TexUvWhitePixel.y; fringe = 0.0f; + flags |= ImDrawFlags_NoAAEnds; } float dir_x = p2.x - p1.x; From b181739cead7d251dd53a5554ad5eb6b67a941c4 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 5 Jun 2026 09:19:33 +0300 Subject: [PATCH 109/245] DrawList: Revert texture selection to simple round() in _SelectFringeTexture - revert texture selection to use just (inlined) round() - the values were tuned to hide texture selection pops on small thickness - since we're using super sampling for the problematic range, the tweaks are not necessayr anymore --- imgui_draw.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d8402b10a..65fc3eb3f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -883,10 +883,11 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv { if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) { - // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. The texture scaling in this range will cause slight visual pops, so we generate super sampled textures in this range. - // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH. + // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. + // We use super sampled textures in this range to make texture changes less noticeable. + // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). constexpr float base_width = 1.0f; - int texture_idx = (int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.1f); + int texture_idx = (int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f); texture_idx = ImMax(texture_idx, 0); texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; @@ -895,8 +896,7 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv } else { - // Bias the texture selection towards higher resolution to avoid visual pops when the texture change. - int texture_idx = (int)(screen_thickness + 0.995f); + int texture_idx = (int)(screen_thickness + 0.5f); texture_idx = ImMax(texture_idx, 2); texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); *out_fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. From efb5c0e1da14ae8c062f33017ab5ffc292b0f1a2 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 5 Jun 2026 09:58:47 +0300 Subject: [PATCH 110/245] DrawList: Added some comments and amended existing ones --- imgui_draw.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 65fc3eb3f..c8a4c4328 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -857,9 +857,9 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE #define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) #define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0 -#define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // cos(179.5) -#define IM_POLYLINE_MITER_LIMIT (4.0f) // ~29 deg -#define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // (int)(360/floor(180-29)) +#define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // Safeguard for miter corner calculation to avoid div by zero. cos(179.5) +#define IM_POLYLINE_MITER_LIMIT (4.0f) // How much the miter can be scaled before we turn it into a bevel instead. (equals ~29 deg corner) +#define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // How many bevels there can be in a convex polygon. (int)(360/floor(180-29)) // In debug builds the functions are likely not inlined, so inlined check is cheaper. #if defined(DEBUG) || defined(_DEBUG) @@ -968,6 +968,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { + // For no anti-alias we use fully opaque texture, and no fringe expansion. tex_uvs.x = _Data->TexUvWhitePixel.x; tex_uvs.y = _Data->TexUvWhitePixel.y; tex_uvs.z = _Data->TexUvWhitePixel.x; @@ -1012,7 +1013,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 PrimReserve(idx_count, vtx_count); const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; - const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. + const float ratio = thickness0 / (thickness0 + thickness1); // The points that use uv2 are placed directly on the path (offset = 0), calculate the texture position from stroke offsets. ImVec2 uv0, uv1, uv2; uv0.x = tex_uvs.x + half_texel; uv0.y = tex_uvs.y; @@ -1603,12 +1604,11 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun _VtxWritePtr += points_count; _VtxCurrentIdx += points_count; - unsigned int prev_outer_idx = 0; // We don't know outer vert could yet, will need to patch once we're done. + unsigned int prev_outer_idx = 0; // This should be the index of the last vertex, but we don't know it yet. Will need to patch once we're done. if (miters_only) { for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { - // Average normals const ImVec2 p1 = points[i1]; const ImVec2 n0 = temp_normals[i0]; const ImVec2 n1 = temp_normals[i1]; @@ -1645,7 +1645,6 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun int bevel_count = 0; for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { - // Average normals const ImVec2 p1 = points[i1]; const ImVec2 n0 = temp_normals[i0]; const ImVec2 n1 = temp_normals[i1]; @@ -2204,6 +2203,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t } else { + // For no anti-alias we use fully opaque texture, and no fringe expansion. tex_uvs.x = _Data->TexUvWhitePixel.x; tex_uvs.y = _Data->TexUvWhitePixel.y; tex_uvs.z = _Data->TexUvWhitePixel.x; @@ -2555,7 +2555,7 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c PrimUnreserve(idx_allocated - idx_used, vtx_allocated - vtx_used); } -// Draws rounded rectangle where thickness/2 > rounding. If rendered using the regular polyline, the stroke will fold and leave artefact on the corner if rendered with transparency. +// Draws rounded rectangle where thickness > rounding. If rendered using the regular polyline, the stroke will fold and leave artifacts on the corners if rendered with transparency. // The stroke is positioned inside the rectangle. void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { @@ -2577,6 +2577,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, } else { + // For no anti-alias we use fully opaque texture, and no fringe expansion. tex_uvs.x = _Data->TexUvWhitePixel.x; tex_uvs.y = _Data->TexUvWhitePixel.y; tex_uvs.z = _Data->TexUvWhitePixel.x; @@ -2820,7 +2821,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (thickness + (0.75f * _FringeScale) > outer_rounding) { // Special case rendering to avoid rendering artifacts at the corners. - // If rendered using the regular polyline, the stroke will fold and leave artifact on the corner if rendered with transparency. + // If rendered using the regular polyline, the stroke will fold and leave artifacts on the corners if rendered with transparency. _AddRectTinyRounding(outer_min, outer_max, col, outer_rounding, thickness, flags); return; } From 230249ad58def4695aa94166cff62a730d8b5c12 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Jun 2026 16:40:11 +0200 Subject: [PATCH 111/245] ImFontAtlas: moved TexUv buffers and configurable defines to internals. --- imgui.h | 21 +-------------------- imgui_draw.cpp | 12 ++++++------ imgui_internal.h | 31 ++++++++++++++++++++++++++----- 3 files changed, 33 insertions(+), 31 deletions(-) diff --git a/imgui.h b/imgui.h index d38f58e48..2e372f373 100644 --- a/imgui.h +++ b/imgui.h @@ -3202,23 +3202,6 @@ struct ImGuiSelectionExternalStorage // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- -#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. -#endif -#ifndef IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] -#endif -#ifndef IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT -#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (4) // How many samples per integer thickness level. -#endif -#ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX -#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) -#endif -#ifndef IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX -#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (4) // 0: fill, 1-3: strokes thickness -#endif -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX (IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) - // ImDrawIdx: vertex index. [Compile-time configurable type] // - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). // - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. @@ -3339,7 +3322,7 @@ enum ImDrawFlags_ // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) - ImDrawFlags_StrokeCenterBiased = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness (rounded down) will be outside, and rest inside the shape outline. Does not animate well! + ImDrawFlags_StrokeCenterBiased = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly and NoAAEnds flags. ImDrawFlags_StrokeMask_ = 0x07 << 16, @@ -3906,8 +3889,6 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines - ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c8a4c4328..582d2f727 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -5326,7 +5326,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; - atlas->TexUvCorners[n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + builder->TexUvCorners[n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); x += w; row_height = ImMax(row_height, h); @@ -5380,7 +5380,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; - atlas->TexUvCorners[thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + builder->TexUvCorners[thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); x += w; row_height = ImMax(row_height, h); @@ -5450,7 +5450,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + builder->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } @@ -5517,7 +5517,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y + y)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(r.x + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - atlas->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + builder->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } } @@ -5892,8 +5892,8 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) if (shared_data->FontAtlas == atlas) { shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; - shared_data->TexUvLines = atlas->TexUvLines; - shared_data->TexUvCorners = atlas->TexUvCorners; + shared_data->TexUvLines = atlas->Builder->TexUvLines; + shared_data->TexUvCorners = atlas->Builder->TexUvCorners; } } diff --git a/imgui_internal.h b/imgui_internal.h index 28251df79..38e475087 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -917,11 +917,28 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N,_MAXERROR) ((_MAXERROR) / (1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI)))) #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N,_RAD) ((1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))) / (_RAD)) -// ImDrawList: Lookup table size for adaptive arc drawing, cover full circle. +// ImDrawList: Lookup tables #ifndef IM_DRAWLIST_ARCFAST_TABLE_SIZE -#define IM_DRAWLIST_ARCFAST_TABLE_SIZE 48 // Number of samples in lookup table. +#define IM_DRAWLIST_ARCFAST_TABLE_SIZE (48) // Number of samples in adaptive arc drawing lookup table. #endif -#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. +#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. + +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#endif +#ifndef IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] +#endif +#ifndef IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT +#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (4) // How many samples per integer thickness level. +#endif +#ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX +#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) +#endif +#ifndef IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX +#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (4) // 0: fill, 1-3: strokes thickness +#endif +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX (IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) // Data shared between all ImDrawList instances // Conceptually this could have been called e.g. ImDrawListSharedContext @@ -930,8 +947,8 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) - const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) - const ImVec4* TexUvCorners; // UV of rounded corner (== FontAtlas->TexUvCorners) + const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) + const ImVec4* TexUvCorners; // UV of rounded corner (== FontAtlas->Builder->TexUvCorners) ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current font (used for simplified AddText overload) float FontSize; // Current font size (used for simplified AddText overload) @@ -4070,6 +4087,10 @@ struct ImFontAtlasBuilder ImFontAtlasRectId PackIdLineFractTexData; ImFontAtlasRectId PackIdCornersTexData; + // Cached UV coordinates + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) + ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } }; From d9378b71c55eb30190d08b9f2a0e38d7180106cf Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Jun 2026 18:37:52 +0200 Subject: [PATCH 112/245] DrawList: surround _GetStrokePos() in IM_MSVC_RUNTIME_CHECKS_OFF macro. --- imgui_draw.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 582d2f727..ee7bc62c9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2166,12 +2166,14 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr // We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. // The earlier should use verbatim legacy code but will be removed before release once we confirm that both matches. +IM_MSVC_RUNTIME_CHECKS_OFF ImDrawFlags ImDrawList::_GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos) { if (flags & ImDrawFlags_StrokeMask_) return (flags & ImDrawFlags_StrokeMask_); return _Data->OverrideStrokePos ? _Data->OverrideStrokePos : default_stroke_pos; } +IM_MSVC_RUNTIME_CHECKS_RESTORE void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) { From c5c76dcda5ae201630ee1f84f8996dbf58123108 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 15 Jun 2026 21:00:20 +0300 Subject: [PATCH 113/245] DrawList: Optimize _SelectFringeTexture() - store inverse line thickness in the spare texture uv component (same v was stord twice) to avoid division in _SelectFringeTexture --- imgui_draw.cpp | 89 ++++++++++++++++++++++++++------------------------ 1 file changed, 47 insertions(+), 42 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ee7bc62c9..d9246462f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -879,29 +879,30 @@ static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } +// Select texture and adjust fringe size for specified line thickness. void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe) { - if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) + // We assume that the screen_thickness has been clamped to 1.0 by the caller. + IM_ASSERT_PARANOID(screen_thickness >= 1.0f); + + ImVec4 tex_uvs; + if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) IM_LIKELY { - // Handle the thickness between [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. + // Handle the thickness between 1.0 - IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. // We use super sampled textures in this range to make texture changes less noticeable. // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). - constexpr float base_width = 1.0f; - int texture_idx = (int)((screen_thickness - base_width) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f); - texture_idx = ImMax(texture_idx, 0); - texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX); - const float tex_width = base_width + (float)texture_idx / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; - *out_fringe = _FringeScale * (screen_thickness / tex_width); // Scale the fringe to cover the discrepancy between the texture and requested size. - *out_tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; + int texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f); + tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; } else { - int texture_idx = (int)(screen_thickness + 0.5f); - texture_idx = ImMax(texture_idx, 2); - texture_idx = ImMin(texture_idx, IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - *out_fringe = _FringeScale * (screen_thickness / (float)texture_idx); // Scale the fringe to cover the discrepancy between the texture and requested size. - *out_tex_uvs = _Data->TexUvLines[texture_idx]; + const int texture_idx = ImMin((int)(screen_thickness + 0.5f), IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + tex_uvs = _Data->TexUvLines[texture_idx]; } + + *out_tex_uvs = tex_uvs; + // Scale the fringe so that the texture matches the line thickness. + *out_fringe = _FringeScale * screen_thickness * tex_uvs.w; // tex_uvs.w = 1 / thickness } IM_MSVC_RUNTIME_CHECKS_RESTORE @@ -969,10 +970,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 else { // For no anti-alias we use fully opaque texture, and no fringe expansion. - tex_uvs.x = _Data->TexUvWhitePixel.x; - tex_uvs.y = _Data->TexUvWhitePixel.y; - tex_uvs.z = _Data->TexUvWhitePixel.x; - tex_uvs.w = _Data->TexUvWhitePixel.y; + tex_uvs.x = _Data->TexUvWhitePixel.x; // u0 + tex_uvs.y = _Data->TexUvWhitePixel.x; // u1 + tex_uvs.z = _Data->TexUvWhitePixel.y; // v + tex_uvs.w = 0.0f; // 1/thickness, unused. fringe = 0.0f; flags |= ImDrawFlags_NoAAEnds; } @@ -1016,11 +1017,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float ratio = thickness0 / (thickness0 + thickness1); // The points that use uv2 are placed directly on the path (offset = 0), calculate the texture position from stroke offsets. ImVec2 uv0, uv1, uv2; uv0.x = tex_uvs.x + half_texel; - uv0.y = tex_uvs.y; - uv1.x = tex_uvs.z - half_texel; - uv1.y = tex_uvs.y; + uv0.y = tex_uvs.z; + uv1.x = tex_uvs.y - half_texel; + uv1.y = tex_uvs.z; uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; - uv2.y = tex_uvs.y; + uv2.y = tex_uvs.z; const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; @@ -1424,8 +1425,8 @@ void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; }*/ - ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y); - ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w); + ImVec2 tex_uv0(tex_uvs.x, tex_uvs.z); + ImVec2 tex_uv1(tex_uvs.y, tex_uvs.z); for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge @@ -2206,10 +2207,10 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t else { // For no anti-alias we use fully opaque texture, and no fringe expansion. - tex_uvs.x = _Data->TexUvWhitePixel.x; - tex_uvs.y = _Data->TexUvWhitePixel.y; - tex_uvs.z = _Data->TexUvWhitePixel.x; - tex_uvs.w = _Data->TexUvWhitePixel.y; + tex_uvs.x = _Data->TexUvWhitePixel.x; // u0 + tex_uvs.y = _Data->TexUvWhitePixel.x; // u1 + tex_uvs.z = _Data->TexUvWhitePixel.y; // v + tex_uvs.w = 0.0f; // 1/thickness, unused. fringe = 0.0f; flags |= ImDrawFlags_NoAAEnds; } @@ -2243,11 +2244,11 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. ImVec2 uv0, uv1, uv2; uv0.x = tex_uvs.x + half_texel; - uv0.y = tex_uvs.y; - uv1.x = tex_uvs.z - half_texel; - uv1.y = tex_uvs.y; + uv0.y = tex_uvs.z; + uv1.x = tex_uvs.y - half_texel; + uv1.y = tex_uvs.z; uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; - uv2.y = tex_uvs.y; + uv2.y = tex_uvs.z; const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; @@ -2580,10 +2581,10 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, else { // For no anti-alias we use fully opaque texture, and no fringe expansion. - tex_uvs.x = _Data->TexUvWhitePixel.x; - tex_uvs.y = _Data->TexUvWhitePixel.y; - tex_uvs.z = _Data->TexUvWhitePixel.x; - tex_uvs.w = _Data->TexUvWhitePixel.y; + tex_uvs.x = _Data->TexUvWhitePixel.x; // u0 + tex_uvs.y = _Data->TexUvWhitePixel.x; // u1 + tex_uvs.z = _Data->TexUvWhitePixel.y; // v + tex_uvs.w = 0.0f; // 1/thickness, unused. fringe = 0.0f; } @@ -2617,11 +2618,11 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, const float ratio = stem_offset / thickness; ImVec2 inner_uv, outer_uv, stem_uv; outer_uv.x = tex_uvs.x + half_texel; - outer_uv.y = tex_uvs.y; - inner_uv.x = tex_uvs.z - half_texel; - inner_uv.y = tex_uvs.y; + outer_uv.y = tex_uvs.z; + inner_uv.x = tex_uvs.y - half_texel; + inner_uv.y = tex_uvs.z; stem_uv.x = outer_uv.x + (inner_uv.x - outer_uv.x) * ratio; - stem_uv.y = tex_uvs.y; + stem_uv.y = tex_uvs.z; // Previous vertices, copied from the last vertices. int base_idx = (int)_VtxCurrentIdx; @@ -5452,7 +5453,9 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - builder->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + // Store inverse of the line-width (thickness) to the w component so that we can avoid division when selecting texture. + float inv_line_width = line_width > 0.f ? 1.0f / line_width : 0.f; + builder->TexUvLines[n] = ImVec4(uv0.x, uv1.x, half_v, inv_line_width); } } @@ -5519,7 +5522,9 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y + y)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(r.x + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - builder->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + // Store inverse of the line-width (thickness) to the w component so that we can avoid division when selecting texture. + float inv_line_width = 1.0f / (1.0f + (float)n / (float)IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT); + builder->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n] = ImVec4(uv0.x, uv1.x, half_v, inv_line_width); } } } From 145b838818b2282213ba20312d9ca0c08c536137 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 15 Jun 2026 21:07:08 +0300 Subject: [PATCH 114/245] DrawList: Optimize AddRectFilled() - detect and draw non-rounded non-AA rect with less branches and calculations - improves new AddRectFilled() overhead from 30% to 5-10% --- imgui_draw.cpp | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d9246462f..af60ae5bb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2917,17 +2917,27 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c return; } - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags |= ImDrawFlags_RoundCornersAll; - + const bool has_rounding = (flags & ImDrawFlags_RoundCornersMask_) != ImDrawFlags_RoundCornersNone && IM_HAS_ROUNDING(rounding); const bool is_truncated = IM_IS_TRUNCATED4(p_min.x, p_min.y, p_max.x, p_max.y) && IM_IS_TRUNCATED(rounding); + if (_FringeScaleIsInteger && is_truncated) { + // Fast path for the non-AA non-rounded rect. + if (!has_rounding) + { + PrimReserve(6, 4); + PrimRect(p_min, p_max, col); + return; + } + + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; + rounding = ImMin(rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); rounding = ImMin(rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); const int s_rounding = (int)(rounding * _InvFringeScale); - if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + if (s_rounding <= 0) { PrimReserve(6, 4); PrimRect(p_min, p_max, col); @@ -2947,8 +2957,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c } } - const bool has_rounding = (rounding >= _FringeScale * 0.5f); - if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + if (!has_rounding) { const ImVec2 points[4] = { p_min, ImVec2(p_max.x, p_min.y), p_max, ImVec2(p_min.x, p_max.y) }; AddConvexPolyFilled(points, 4, col, ImDrawFlags_MiterOnly); From 10aa5d92e6ce4f317ff6659b685260fe64db2715 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Mon, 15 Jun 2026 22:23:38 +0300 Subject: [PATCH 115/245] DrawList: Optimize AddNgon() - test overestimate before testing more expensive details when testing if stroked ngon is actualy filled - Note: not a common function, but the test harness is using this to draw a triangle, which makes it show up in profiling --- imgui_draw.cpp | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index af60ae5bb..ab0292ed2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3125,23 +3125,27 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ radius = ImMax(0.01f, radius); - const float unit_apothem = ImCos(IM_PI / (float)num_segments); - const float miter_thickness = thickness / unit_apothem; - - float outer_radius = radius; - if (stroke_pos == ImDrawFlags_StrokeCenter) - outer_radius = radius + miter_thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - outer_radius = radius + _CalculateCenterBiasedOffset(miter_thickness); - else if (stroke_pos == ImDrawFlags_StrokeInside) - outer_radius = radius; - else if (stroke_pos == ImDrawFlags_StrokeOutside) - outer_radius = radius + miter_thickness; - if (outer_radius < (miter_thickness + _FringeScale)) IM_UNLIKELY + // Check overestimate first before testing details. + if (radius < (thickness * 2.f + 1.f)) { - // The polygon has collapsed into a filled polygon. - AddNgonFilled(center, outer_radius, col, num_segments); - return; + const float unit_apothem = ImCos(IM_PI / (float)num_segments); + const float miter_thickness = thickness / unit_apothem; + + float outer_radius = radius; + if (stroke_pos == ImDrawFlags_StrokeCenter) + outer_radius = radius + miter_thickness * 0.5f; + else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) + outer_radius = radius + _CalculateCenterBiasedOffset(miter_thickness); + else if (stroke_pos == ImDrawFlags_StrokeInside) + outer_radius = radius; + else if (stroke_pos == ImDrawFlags_StrokeOutside) + outer_radius = radius + miter_thickness; + if (outer_radius < (miter_thickness + _FringeScale)) IM_UNLIKELY + { + // The polygon has collapsed into a filled polygon. + AddNgonFilled(center, outer_radius, col, num_segments); + return; + } } // Because we are filling a closed shape we remove 1 from the count of segments/points From 9b608ba0798c10dffbdc540e77affc07081725af Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jul 2026 19:35:30 +0200 Subject: [PATCH 116/245] DrawList: fixed warnings, added macro to facilitate visualizing rounded corner texture usage. --- imgui_draw.cpp | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ab0292ed2..5c56995c5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2758,7 +2758,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); } - const bool is_truncated = IM_IS_TRUNCATED4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && IM_IS_TRUNCATED4(outer_rounding, thickness, 0.0f, 0.0f); + const bool is_truncated = IM_IS_TRUNCATED4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && IM_IS_TRUNCATED4(outer_rounding, thickness, 0.0f, 0.0f); //-V501 if (_FringeScaleIsInteger && is_truncated) { int s_rounding = (int)(outer_rounding * _InvFringeScale); @@ -3126,7 +3126,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ radius = ImMax(0.01f, radius); // Check overestimate first before testing details. - if (radius < (thickness * 2.f + 1.f)) + if (radius < (thickness * 2.0f + 1.0f)) { const float unit_apothem = ImCos(IM_PI / (float)num_segments); const float miter_thickness = thickness / unit_apothem; @@ -5245,6 +5245,14 @@ static ImU8 SampleCornerStroke(float x, float y, float thickness, const ImVec2* return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.0f); } +#if 0 // Set to 1 to visualize coverage of textured corners +#define DEBUG_TEX_CORNER_U8(_LX, _H) ((_LX & 1) ? 255 : 0) +#define DEBUG_TEX_CORNER_U32(_LX, _H) IM_COL32((_LX & 1) ? 255: 0, 0, 0, (_LX & 1) ? 200 : 0) +#else +#define DEBUG_TEX_CORNER_U8(_LX, _H) 0xFF +#define DEBUG_TEX_CORNER_U32(_LX, _H) 0xFFFFFFFF +#endif + static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) { if (atlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners) @@ -5323,7 +5331,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines); + write_ptr[lx] = SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines) & DEBUG_TEX_CORNER_U8(lx, h); write_ptr += pitch; } } @@ -5334,7 +5342,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = IM_COL32(255, 255, 255, SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines)); + write_ptr[lx] = IM_COL32(255, 255, 255, SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines)) & DEBUG_TEX_CORNER_U32(lx, h); write_ptr += pitch; } } @@ -5377,7 +5385,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines); + write_ptr[lx] = SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines) & DEBUG_TEX_CORNER_U8(lx, h); write_ptr += pitch; } } @@ -5388,7 +5396,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) for (int ly = 0; ly < h; ly++) { for (int lx = 0; lx < h; lx++) - write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines)); + write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines)) & DEBUG_TEX_CORNER_U32(lx, h); write_ptr += pitch; } } @@ -5467,7 +5475,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts // Store inverse of the line-width (thickness) to the w component so that we can avoid division when selecting texture. - float inv_line_width = line_width > 0.f ? 1.0f / line_width : 0.f; + float inv_line_width = (line_width > 0) ? (1.0f / (float)line_width) : 0.0f; builder->TexUvLines[n] = ImVec4(uv0.x, uv1.x, half_v, inv_line_width); } } From eb75c8056edec6cb3deb0c66286e5ef63126abf0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jul 2026 19:57:03 +0200 Subject: [PATCH 117/245] DrawList: inverted ImDrawFlags_NoAAEnds into ImDrawFlags_AAEnds. --- docs/CHANGELOG.txt | 6 +++--- imgui.h | 4 ++-- imgui_demo.cpp | 4 ++-- imgui_draw.cpp | 16 ++++++++-------- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8720d1179..f7eae62f1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,7 +77,7 @@ HOW TO UPDATE? Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. - Old AddLine({x1, y1}, {x2, y2}, col) == AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy); // Offset by +0.5f + disable AA ends. - == AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col, thickness, ImDrawFlags_NoAAEnds); // Same + == AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col, thickness); // Same This reapplies the old offset, and should get you exactly the same result you previously got for thickness=1.0f lines. But said result was sometimes ambiguous and renderer dependent. (#3116, #3258, #2441) - Old AddLine() did not have anti-aliased ends, which could create gaps when rendering shapes out @@ -93,8 +93,8 @@ HOW TO UPDATE? but the artifacts should be more localized. The new implementation attempted to favor simple implementation and robustness over the corner case accuracy. - Added anti-aliasing ends, most noticeable for thick lines. - - Added `ImDrawFlags_NoAAEnds` flag to disable anti-aliased line ends (slightly faster - and reduce vertex/index data). + - Added `ImDrawFlags_AAEnds` flag to enable anti-aliased line ends. Enabling AA Ends by + default would be more "correct", but it is slower and increase vertex/index data. - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner (closer to legacy rendering, slightly faster, but corners sharpers than 90 degrees may expand far out). Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() etc functions diff --git a/imgui.h b/imgui.h index 2e372f373..83768b8fe 100644 --- a/imgui.h +++ b/imgui.h @@ -3317,14 +3317,14 @@ enum ImDrawFlags_ ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. ImDrawFlags_MiterOnly = 1 << 10, // PathStroke(), AddPolyline(): use miter corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. ImDrawFlags_SquareCap = 1 << 11, // PathStroke(), AddPolyline(): use square cap line ends. - ImDrawFlags_NoAAEnds = 1 << 12, // PathStroke(), AddPolyline(): do not generate anti-aliased line ends. This can speed up single line rendering. + ImDrawFlags_AAEnds = 1 << 12, // PathStroke(), AddPolyline(): generate anti-aliased line ends. // Stroke position relative to the shape outline ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) ImDrawFlags_StrokeCenterBiased = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline - ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly and NoAAEnds flags. + ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly, disable AAEnds flags. ImDrawFlags_StrokeMask_ = 0x07 << 16, ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7e52eaf34..f698984a6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10430,7 +10430,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::ColorEdit4("Stroke Color", &colf_stroke.x); ImGui::ColorEdit4("Fill Color", &colf_fill.x); - static ImDrawFlags stroke_flags = ImDrawFlags_None; + static ImDrawFlags stroke_flags = ImDrawFlags_AAEnds; static ImDrawFlags other_flags = ImDrawFlags_None; ImGui::Text("Stroke Flags:"); ImGui::RadioButton("Default", &stroke_flags, ImDrawFlags_None); ImGui::SameLine(); @@ -10441,7 +10441,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::RadioButton("Legacy", &stroke_flags, ImDrawFlags_StrokeLegacy); ImGui::CheckboxFlags("MiterOnly", &other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); ImGui::CheckboxFlags("SquareCap", &other_flags, ImDrawFlags_SquareCap); ImGui::SameLine(); - ImGui::CheckboxFlags("NoAAEnds", &other_flags, ImDrawFlags_NoAAEnds); + ImGui::CheckboxFlags("AAEnds", &other_flags, ImDrawFlags_AAEnds); ImGui::Spacing(); const ImDrawFlags flags = stroke_flags | other_flags; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5c56995c5..72cd27d54 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -975,14 +975,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 tex_uvs.z = _Data->TexUvWhitePixel.y; // v tex_uvs.w = 0.0f; // 1/thickness, unused. fringe = 0.0f; - flags |= ImDrawFlags_NoAAEnds; + flags &= ~ImDrawFlags_AAEnds; } const ImU32 col_trans = col & ~IM_COL32_A_MASK; const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags |= ImDrawFlags_MiterOnly | ImDrawFlags_NoAAEnds; + flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AAEnds; const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; @@ -1054,7 +1054,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 p1.y -= dir.y * half_thickness; } - if (flags & ImDrawFlags_NoAAEnds) + if ((flags & ImDrawFlags_AAEnds) == 0) { base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); @@ -1240,7 +1240,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 p1.y += dir.y * half_thickness; } - if (flags & ImDrawFlags_NoAAEnds) + if ((flags & ImDrawFlags_AAEnds) == 0) { IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); @@ -2212,7 +2212,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t tex_uvs.z = _Data->TexUvWhitePixel.y; // v tex_uvs.w = 0.0f; // 1/thickness, unused. fringe = 0.0f; - flags |= ImDrawFlags_NoAAEnds; + flags &= ~ImDrawFlags_AAEnds; } float dir_x = p2.x - p1.x; @@ -2228,7 +2228,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags |= ImDrawFlags_MiterOnly | ImDrawFlags_NoAAEnds; + flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AAEnds; float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2253,7 +2253,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; - if (flags & ImDrawFlags_NoAAEnds) + if ((flags & ImDrawFlags_AAEnds) == 0) PrimReserve(2*3, 4); else PrimReserve(6*3, 8); @@ -2274,7 +2274,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t } // Start cap - if (flags & ImDrawFlags_NoAAEnds) + if ((flags & ImDrawFlags_AAEnds) == 0) { base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1_x - norm_x * thickness0, p1_y - norm_y * thickness0, uv0, col); From cf85b48e55f7d1d8a705779f069a0a8de3161e18 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 5 Jun 2026 19:09:14 +0200 Subject: [PATCH 118/245] DrawList: new ImDrawFlags API (yet unused in this commit) --- imgui.h | 86 +++++++++++++++++++++++++++++++++----------------- imgui_demo.cpp | 4 +-- imgui_draw.cpp | 16 +++++----- 3 files changed, 67 insertions(+), 39 deletions(-) diff --git a/imgui.h b/imgui.h index 83768b8fe..bbd576900 100644 --- a/imgui.h +++ b/imgui.h @@ -3295,39 +3295,67 @@ struct ImDrawListSplitter // Flags for ImDrawList functions enum ImDrawFlags_ { - ImDrawFlags_None = 0, - //ImDrawFlags_Closed = 1, // -> FLAG MOVED BELOW. Prior to 1.92.8 (May 2026): ImDrawFlags_Closed was guaranteed to be == (1<<0) == 1, for legacy compatibility reason. Hardcoded use of 1 or true should be replaced with 'ImDrawFlags_Closed'. + ImDrawFlags_None = 0, + //ImDrawFlags_Closed = 1, // -> FLAG MOVED BELOW. Prior to 1.92.8 (May 2026): ImDrawFlags_Closed was guaranteed to be == (1<<0) == 1, for legacy compatibility reason. Hardcoded use of 1 or true should be replaced with 'ImDrawFlags_Closed'. - // Rounding for AddRect(), AddRectFilled(), PathRect() - // - When not specified, we defaults to ImDrawFlags_RoundCornersAll! So you only need to use those flags if you want another configuration. - ImDrawFlags_RoundCornersTopLeft = 1 << 4, // Round top-left corner only (when rounding > 0.0f, we default to all corners). - ImDrawFlags_RoundCornersTopRight = 1 << 5, // Round top-right corner only (when rounding > 0.0f, we default to all corners). - ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // Round bottom-left corner only (when rounding > 0.0f, we default to all corners). - ImDrawFlags_RoundCornersBottomRight = 1 << 7, // Round bottom-right corner only (when rounding > 0.0f, we default to all corners). - ImDrawFlags_RoundCornersNone = 1 << 8, // Disable rounding even if `float rounding > 0.0f`. This is NOT zero, NOT an implicit flag! - ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, // (Default!!) - ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified! - ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, - ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, - ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, - ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, - ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, + // About usage of flags: + // - "Prim" column: 'OK' = flag can be used to configure an individual AddXXX() call. + // - "Scope" column: 'OK' = initialized by ImGui based on Style options (e.g. whether anti-aliased is enabled). + // OK(0)/OK(1) indicates whether this flag is set in the default ImGui Style settings. + // (flag will be possible to alter in a scope using PushDrawFlags()). - // Stroke options - ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. - ImDrawFlags_MiterOnly = 1 << 10, // PathStroke(), AddPolyline(): use miter corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. - ImDrawFlags_SquareCap = 1 << 11, // PathStroke(), AddPolyline(): use square cap line ends. - ImDrawFlags_AAEnds = 1 << 12, // PathStroke(), AddPolyline(): generate anti-aliased line ends. + // - Rounding default to ImDrawFlags_RoundCornersAll when 'rounding > 0'. + // - So you only need to use the _RoundCorners flags if you want a special configuration (e.g. a rectangle with one rounded corner). + // Rounding for AddRectXXX(), PathRect() ------ // Prim/Scope? + ImDrawFlags_RoundCornersTopLeft = 1 << 4, // OK -- // Round top-left corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundCornersTopRight = 1 << 5, // OK -- // Round top-right corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // OK -- // Round bottom-left corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundCornersBottomRight = 1 << 7, // OK -- // Round bottom-right corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundCornersNone = 1 << 8, // OK -- // Disable rounding even when 'rounding > 0.0f'. This value is NOT zero, it is NOT an implicit flag! + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, // (Default!!) + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, - // Stroke position relative to the shape outline - ImDrawFlags_StrokeInside = 1 << 16, // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) - ImDrawFlags_StrokeCenter = 2 << 16, // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) - ImDrawFlags_StrokeCenterBiased = 3 << 16, // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! - ImDrawFlags_StrokeOutside = 4 << 16, // Draw stroke outside of the shape outline - ImDrawFlags_StrokeLegacy = 5 << 16, // Use legacy positioning + enable MiterOnly, disable AAEnds flags. - ImDrawFlags_StrokeMask_ = 0x07 << 16, + // Stroke Options ----------------------------- // Prim/Scope? + ImDrawFlags_Closed = 1 << 9, // OK -- // PathStroke(), AddPolyline(): specify that shape should be closed. + ImDrawFlags_MiterOnly = 1 << 10, // OK -- // PathStroke(), AddPolyline(): use miter corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. + ImDrawFlags_SquareCap = 1 << 11, // OK -- // PathStroke(), AddPolyline(): use square cap line ends. - ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, + // About Stroke Ends: + // - Rendering is optimized for fast pixel-perfect UI, so line ends are not anti-aliased by default. It cheaper (we can emit less vertices). + // - For more free-form drawings, light graphs and markers, or when using thick strokes: you can turn them on using the ImDrawFlags_AALineEnds flag. + // - See 'Demo->Examples->Custom Rendering' to interactively toy with those flags. + // - 'OK*' indicates using this at the AddXXX() call site is unlikely: it would only makes sense if (1) the option is disabled in style/scope and (2) you want to forcefully enable it for a single primitives. Possible but unlikely! Only supported for functions taking flags inputs. + // Stroke/Fill Anti-aliasing ------------------ // Prim/Scope? + ImDrawFlags_AAFill = 1 << 12, // OK* OK(1) // Enable anti-aliasing for Filled shapes. + ImDrawFlags_AALines = 1 << 13, // OK* OK(1) // Enable anti-aliasing for Strokes (lines, borders). + ImDrawFlags_AALineEnds = 1 << 14, // OK OK(0) // Enable anti-aliasing for Strokes Ends. Useful on thick strokes or for precise continuity of multiple lines. A little more costly. + //ImDrawFlags_NoAA = 1 << 15, // OK -- // Disable anti-aliasing for a given primitive. + //ImDrawFlags_NoAALineEnds = 1 << 16, // OK -- // Disable anti-aliasing ends for a given primitive. + + // About Stroke Position: + // - Read https://github.com/ocornut/imgui/wiki/Draw-List + // - Read https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering + // Stroke Position relative to shape outline -- // Prim/Scope? + ImDrawFlags_StrokeInside = 1 << 17, // OK -- // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) + ImDrawFlags_StrokeCenter = 2 << 17, // OK -- // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) + ImDrawFlags_StrokeCenterBiased = 3 << 17, // OK -- // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! + ImDrawFlags_StrokeOutside = 4 << 17, // OK -- // Draw stroke outside of the shape outline + ImDrawFlags_StrokeLegacy = 7 << 17, // OK OK(0) // Use legacy positioning + enable MiterOnly + disable AALineEnds. Must be all bits set. + + // Other Options ------------------------------ // Prim/Scope? + ImDrawFlags_TextNoPixelSnap = 1 << 20, // OK OK(0) // Disable automatically snapping AddText() calls to pixel boundaries. + ImDrawFlags_UseTexForRoundCorners = 1 << 21, // -- OK(1) // Enable using textures instead of strokes to draw rounded corners/circles where possible (faster). Used by default unless 'ImFontAtlasFlags_NoBakedRoundCorners' is enabled in the font atlas. + ImDrawFlags_UseTexForStrokeLegacy = 1 << 22, // -- OK(1) // Enable anti-aliased lines/borders using textures when using legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). Used by default unless 'ImFontAtlasFlags_NoBakedLines' is set in the font atlas. + ImDrawFlags_UseVtxOffset = 1 << 23, // -- OK(1) // Can emit 'VtxOffset > 0' to allow large meshes with 16-bit ImDrawIdx. Used by default when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled by the backend. + + // [Internal] + ImDrawFlags_AllowedInScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset, // [Internal] Values allowed in scope e.g. incoming PushDrawFlags() stack. + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, // [Internal] + ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] + ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. }; // Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f698984a6..e7a326463 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10430,7 +10430,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::ColorEdit4("Stroke Color", &colf_stroke.x); ImGui::ColorEdit4("Fill Color", &colf_fill.x); - static ImDrawFlags stroke_flags = ImDrawFlags_AAEnds; + static ImDrawFlags stroke_flags = ImDrawFlags_AALineEnds; static ImDrawFlags other_flags = ImDrawFlags_None; ImGui::Text("Stroke Flags:"); ImGui::RadioButton("Default", &stroke_flags, ImDrawFlags_None); ImGui::SameLine(); @@ -10441,7 +10441,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::RadioButton("Legacy", &stroke_flags, ImDrawFlags_StrokeLegacy); ImGui::CheckboxFlags("MiterOnly", &other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); ImGui::CheckboxFlags("SquareCap", &other_flags, ImDrawFlags_SquareCap); ImGui::SameLine(); - ImGui::CheckboxFlags("AAEnds", &other_flags, ImDrawFlags_AAEnds); + ImGui::CheckboxFlags("AALineEnds", &other_flags, ImDrawFlags_AALineEnds); ImGui::Spacing(); const ImDrawFlags flags = stroke_flags | other_flags; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 72cd27d54..811bdd3d2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -975,14 +975,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 tex_uvs.z = _Data->TexUvWhitePixel.y; // v tex_uvs.w = 0.0f; // 1/thickness, unused. fringe = 0.0f; - flags &= ~ImDrawFlags_AAEnds; + flags &= ~ImDrawFlags_AALineEnds; } const ImU32 col_trans = col & ~IM_COL32_A_MASK; const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AAEnds; + flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AALineEnds; const bool closed = (flags & ImDrawFlags_Closed) != 0; const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; @@ -1054,7 +1054,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 p1.y -= dir.y * half_thickness; } - if ((flags & ImDrawFlags_AAEnds) == 0) + if ((flags & ImDrawFlags_AALineEnds) == 0) { base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); @@ -1240,7 +1240,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 p1.y += dir.y * half_thickness; } - if ((flags & ImDrawFlags_AAEnds) == 0) + if ((flags & ImDrawFlags_AALineEnds) == 0) { IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); @@ -2212,7 +2212,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t tex_uvs.z = _Data->TexUvWhitePixel.y; // v tex_uvs.w = 0.0f; // 1/thickness, unused. fringe = 0.0f; - flags &= ~ImDrawFlags_AAEnds; + flags &= ~ImDrawFlags_AALineEnds; } float dir_x = p2.x - p1.x; @@ -2228,7 +2228,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AAEnds; + flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AALineEnds; float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -2253,7 +2253,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; - if ((flags & ImDrawFlags_AAEnds) == 0) + if ((flags & ImDrawFlags_AALineEnds) == 0) PrimReserve(2*3, 4); else PrimReserve(6*3, 8); @@ -2274,7 +2274,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t } // Start cap - if ((flags & ImDrawFlags_AAEnds) == 0) + if ((flags & ImDrawFlags_AALineEnds) == 0) { base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1_x - norm_x * thickness0, p1_y - norm_y * thickness0, uv0, col); From 02adb46a9f357f04dba6aa965dc0768b92b35c18 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2026 12:48:52 +0200 Subject: [PATCH 119/245] (Breaking) DrawList: removed ImDrawListFlags_in favor of using ImDrawFlags. # Conflicts: # imgui.cpp --- docs/CHANGELOG.txt | 13 ++++++++++--- imgui.cpp | 33 ++++++++++++++++++++------------- imgui.h | 33 ++++++++++++++++----------------- imgui_demo.cpp | 20 +++++++++++--------- imgui_draw.cpp | 37 +++++++++++++++++++------------------ imgui_internal.h | 2 +- 6 files changed, 77 insertions(+), 61 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f7eae62f1..fb7af7591 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,8 +93,8 @@ HOW TO UPDATE? but the artifacts should be more localized. The new implementation attempted to favor simple implementation and robustness over the corner case accuracy. - Added anti-aliasing ends, most noticeable for thick lines. - - Added `ImDrawFlags_AAEnds` flag to enable anti-aliased line ends. Enabling AA Ends by - default would be more "correct", but it is slower and increase vertex/index data. + - Added `ImDrawFlags_AALineEnds` flag to enable anti-aliased line ends. Enabling AA Ends + by default would be more "correct", but it is slower and increase vertex/index data. - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner (closer to legacy rendering, slightly faster, but corners sharpers than 90 degrees may expand far out). Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() etc functions @@ -141,6 +141,14 @@ HOW TO UPDATE? - All closed shapes with thickness=1.0f will appear identical. - The difference for thickness>1.0f shapes may be minimal since very large strokes were not well supported for widgets, but stroke will default inside widgets. +- (Breaking) Merged `ImDrawListFlags` into `ImDrawFlags`. + `ImDrawListFlags` was very rarely used directly. Keep inline redirection (will obsolete). + - `ImDrawListFlags_AntiAliasedLines` -> `ImDrawFlags_AALines` + - `ImDrawListFlags_AntiAliasedFill` -> `ImDrawFlags_AAFill` + - `ImDrawListFlags_AntiAliasedLinesUseTex` -> `ImDrawFlags_UseTexForStrokeLegacy` + - `ImDrawListFlags_AllowVtxOffset` -> `ImDrawFlags_UseVtxOffset` + - `ImDrawListFlags_TextNoPixelSnap` -> `ImDrawFlags_TextNoPixelSnap` + Unifying them allows easily using them for both per-primitives and scope alterations. - Tweaked line rendering in various locations to avoid blurryness: - Windows: title-bar and menu-bar border (when thickness>1.0f). - Tables: borders (when thickness>1.0f). @@ -152,7 +160,6 @@ HOW TO UPDATE? filled shapes; Added an option to animation thickness; Added new shapes to showcase new rendering features that previously hit limitations. - Breaking Changes: - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in diff --git a/imgui.cpp b/imgui.cpp index b9a700608..15bde3e93 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -395,6 +395,13 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + 2026/10/07 (1.93.0) - merged ImDrawListFlags into ImDrawFlags. obsoleted ImDrawListFlags (which were rarely used directly): + - ImDrawListFlags_AntiAliasedLines -> ImDrawFlags_AALines, + - ImDrawListFlags_AntiAliasedFill -> ImDrawFlags_AAFill, + - ImDrawListFlags_AntiAliasedLinesUseTex -> ImDrawFlags_UseTexForStrokeLegacy + - ImDrawListFlags_AllowVtxOffset -> ImDrawFlags_UseVtxOffset, + - ImDrawListFlags_TextNoPixelSnap -> ImDrawFlags_TextNoPixelSnap, + unifying them allows easily using them for both per-primitives alterations and scope alterations. - 2026/09/30 (1.93.0) - ImFont: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). (#609, #5748) - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. @@ -5619,17 +5626,17 @@ static void SetupDrawListSharedData() g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4(); g.DrawListSharedData.CurveTessellationMaxError = g.Style.CurveTessellationMaxError; g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError); - g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; - if (g.Style.AntiAliasedLines) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; - if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines)) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; - if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_RoundCornersUseTex; + g.DrawListSharedData.InitialDrawFlags = ImDrawFlags_None; if (g.Style.AntiAliasedFill) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AAFill; + if (g.Style.AntiAliasedLines) + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALines; + if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines)) + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForStrokeLegacy; + if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForRoundCorners; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseVtxOffset; } void ImGui::NewFrame() @@ -17680,8 +17687,8 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con Selectable(buf, false); if (fg_draw_list && IsItemHovered()) { - ImDrawListFlags backup_flags = fg_draw_list->Flags; - fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + ImDrawFlags backup_flags = fg_draw_list->Flags; + fg_draw_list->Flags &= ~ImDrawFlags_AALines; // Disable AA on triangle outlines is more readable for very large and thin triangles. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), 1.0f, ImDrawFlags_Closed); fg_draw_list->Flags = backup_flags; } @@ -17699,8 +17706,8 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co // Draw wire-frame version of all triangles ImRect clip_rect = draw_cmd->ClipRect; ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); - ImDrawListFlags backup_flags = out_draw_list->Flags; - out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + ImDrawFlags backup_flags = out_draw_list->Flags; + out_draw_list->Flags &= ~ImDrawFlags_AALines; // Disable AA on triangle outlines is more readable for very large and thin triangles. for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; ) { ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list diff --git a/imgui.h b/imgui.h index bbd576900..09f8b5cc7 100644 --- a/imgui.h +++ b/imgui.h @@ -49,7 +49,7 @@ Index of this file: // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) -// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) +// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) // [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -246,7 +246,6 @@ typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A // - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. // - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions -typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Internal, do not use! typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas @@ -3198,7 +3197,7 @@ struct ImGuiSelectionExternalStorage }; //----------------------------------------------------------------------------- -// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) +// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- @@ -3358,19 +3357,6 @@ enum ImDrawFlags_ ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. }; -// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. -// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. -enum ImDrawListFlags_ -{ - ImDrawListFlags_None = 0, - ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) - ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). - ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. - ImDrawListFlags_TextNoPixelSnap = 1 << 4, // Disable automatically snapping AddText() calls to pixel boundaries. - ImDrawListFlags_RoundCornersUseTex = 1 << 5, // Enable using textures instead of strokes to draw rounded corners/circles where possible. Set when `ImFontAtlasFlags_NoBakedRoundCorners` is enabled in the font atlas. -}; - // Draw command list // This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame, // all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. @@ -3386,7 +3372,7 @@ struct ImDrawList ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector VtxBuffer; // Vertex buffer. - ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. + ImDrawFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. // [Internal, used while building lists] unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. @@ -4294,6 +4280,19 @@ namespace ImGui #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) // OBSOLETED in 1.92.8: Use ImGui::GetPlatformIO().DrawCallback_ResetRenderState + +// -- RENAMED in 1.93.0: Merged ImDrawListFlags into ImDrawFlags. +typedef ImDrawFlags ImDrawListFlags; +enum ImDrawListFlags_ +{ + ImDrawListFlags_None = ImDrawFlags_None, + ImDrawListFlags_AntiAliasedFill = ImDrawFlags_AAFill, + ImDrawListFlags_AntiAliasedLines = ImDrawFlags_AALines, + ImDrawListFlags_AntiAliasedLinesUseTex = ImDrawFlags_UseTexForStrokeLegacy,// Only apply to StrokeLegacy mode! + ImDrawListFlags_AllowVtxOffset = ImDrawFlags_UseVtxOffset, + ImDrawListFlags_TextNoPixelSnap = ImDrawFlags_TextNoPixelSnap, +}; + //-- OBSOLETED in 1.92.0: ImFontAtlasCustomRect becomes ImTextureRect // - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y // - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e7a326463..d1188a348 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10443,17 +10443,19 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::CheckboxFlags("SquareCap", &other_flags, ImDrawFlags_SquareCap); ImGui::SameLine(); ImGui::CheckboxFlags("AALineEnds", &other_flags, ImDrawFlags_AALineEnds); ImGui::Spacing(); - const ImDrawFlags flags = stroke_flags | other_flags; // FIXME: Clarify how this is exposed, consider changing Demo code to simply alter Style.s - static ImDrawListFlags draw_list_flags = ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill | ImDrawListFlags_RoundCornersUseTex; - ImGui::Text("DrawList Flags:"); - ImGui::CheckboxFlags("AntiAliasedLines", &draw_list_flags, ImDrawListFlags_AntiAliasedLines); ImGui::SameLine(); - ImGui::CheckboxFlags("AntiAliasedFill", &draw_list_flags, ImDrawListFlags_AntiAliasedFill); ImGui::SameLine(); - ImGui::CheckboxFlags("RoundCornersUseTex", &draw_list_flags, ImDrawListFlags_RoundCornersUseTex); - ImDrawListFlags backup_draw_list_flags = draw_list->Flags; - draw_list->Flags &= ~(ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill | ImDrawListFlags_RoundCornersUseTex); - draw_list->Flags |= draw_list_flags; + const ImDrawFlags scope_flags_mask = ImDrawFlags_AllowedInScope_; + static ImDrawFlags scope_flags = scope_flags_mask; // All + ImGui::Text("AA Flags:"); + ImGui::CheckboxFlags("AAFill", &scope_flags, ImDrawFlags_AAFill); ImGui::SameLine(); + ImGui::CheckboxFlags("AALines", &scope_flags, ImDrawFlags_AALines); ImGui::SameLine(); + ImGui::CheckboxFlags("AALineEnds", &scope_flags, ImDrawFlags_AALineEnds); + ImGui::CheckboxFlags("UseTexForRoundCorners", &scope_flags, ImDrawFlags_UseTexForRoundCorners); + ImGui::CheckboxFlags("UseTexForStrokeLegacy", &scope_flags, ImDrawFlags_UseTexForStrokeLegacy); ImGui::SameLine(); + ImDrawFlags backup_draw_list_flags = draw_list->Flags; + draw_list->Flags = (draw_list->Flags & ~scope_flags_mask) | scope_flags; + const ImDrawFlags flags = stroke_flags | other_flags; ImVec2 start_pos = ImGui::GetCursorScreenPos(); const float pi = 3.141592f; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 811bdd3d2..1f16f5a2d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -461,7 +461,8 @@ void ImDrawList::_ResetForNewFrame() CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); - Flags = _Data->InitialFlags; + Flags = _Data->InitialDrawFlags; + IM_ASSERT((Flags & ~ImDrawFlags_AllowedInScope_) == 0); memset(&_CmdHeader, 0, sizeof(_CmdHeader)); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; @@ -480,7 +481,7 @@ void ImDrawList::_ClearFreeMemory() CmdBuffer.clear(); IdxBuffer.clear(); VtxBuffer.clear(); - Flags = ImDrawListFlags_None; + Flags = ImDrawFlags_None; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -736,7 +737,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) { // Large mesh support (when enabled) IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); - if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) + if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawFlags_UseVtxOffset)) { // FIXME: In theory we should be testing that vtx_count <64k here. // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us @@ -963,7 +964,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 ImVec4 tex_uvs; float fringe; - if (Flags & ImDrawListFlags_AntiAliasedLines) + if (Flags & ImDrawFlags_AALines) { _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); } @@ -1305,7 +1306,7 @@ void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, // Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); - if (Flags & ImDrawListFlags_AntiAliasedLines) + if (Flags & ImDrawFlags_AALines) { // Anti-aliased stroke const float AA_SIZE = _FringeScale; @@ -1319,9 +1320,9 @@ void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, // Do we want to draw this line using a texture? // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. // - If AA_SIZE is not 1.0f we cannot use the texture path. - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); + const bool use_texture = (Flags & ImDrawFlags_UseTexForStrokeLegacy) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); - // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off + // We should never hit this, because NewFrame() doesn't set ImDrawFlags_UseTexForStrokeLegacy unless ImFontAtlasFlags_NoBakedLines is off IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); @@ -1565,7 +1566,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun }*/ const ImVec2 uv = _Data->TexUvWhitePixel; - if (Flags & ImDrawListFlags_AntiAliasedFill) + if (Flags & ImDrawFlags_AAFill) { const float half_aa = _FringeScale * 0.5f; ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -1753,7 +1754,7 @@ void ImDrawList::AddConvexPolyFilledLegacy(const ImVec2* points, const int point const ImVec2 uv = _Data->TexUvWhitePixel; - if (Flags & ImDrawListFlags_AntiAliasedFill) + if (Flags & ImDrawFlags_AAFill) { // Anti-aliased Fill const float AA_SIZE = _FringeScale; @@ -2200,7 +2201,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t ImVec4 tex_uvs; float fringe; - if (Flags & ImDrawListFlags_AntiAliasedLines) + if (Flags & ImDrawFlags_AALines) { _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); } @@ -2574,7 +2575,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImVec4 tex_uvs; float fringe; - if (Flags & ImDrawListFlags_AntiAliasedLines) + if (Flags & ImDrawFlags_AALines) { _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); } @@ -2712,7 +2713,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { - if (Flags & ImDrawListFlags_AntiAliasedLines) + if (Flags & ImDrawFlags_AALines) PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.50f, p_max.y - 0.50f), rounding, flags); else PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.49f, p_max.y - 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. @@ -2798,7 +2799,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (Flags & (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedLines)) == (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedLines); + const bool allow_tex_corners = (Flags & (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners); if (allow_tex_corners && s_thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { // Pixel aligned rect with round corners rendered using baked textures. @@ -2944,7 +2945,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c return; } // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (Flags & (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedFill)) == (ImDrawListFlags_RoundCornersUseTex | ImDrawListFlags_AntiAliasedFill); + const bool allow_tex_corners = (Flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); if (allow_tex_corners && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); @@ -3581,7 +3582,7 @@ void ImDrawList::AddConcavePolyFilled(const ImVec2* points, const int points_cou const ImVec2 uv = _Data->TexUvWhitePixel; ImTriangulator triangulator; unsigned int triangle[3]; - if (Flags & ImDrawListFlags_AntiAliasedFill) + if (Flags & ImDrawFlags_AAFill) { // Anti-aliased Fill const float AA_SIZE = _FringeScale; @@ -3838,7 +3839,7 @@ void ImGui::AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector // May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); - if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset)) + if (!(draw_list->Flags & ImDrawFlags_UseVtxOffset)) IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) @@ -7681,7 +7682,7 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, Im float scale = (size >= 0.0f) ? (size / baked->Size) : 1.0f; float x = pos.x; float y = pos.y; - if ((draw_list->Flags & ImDrawListFlags_TextNoPixelSnap) == 0) + if ((draw_list->Flags & ImDrawFlags_TextNoPixelSnap) == 0) { x = IM_TRUNC(x); y = IM_TRUNC(y); @@ -7723,7 +7724,7 @@ begin: float y = pos.y; if (y > clip_rect.w) return; - if ((draw_list->Flags & ImDrawListFlags_TextNoPixelSnap) == 0) + if ((draw_list->Flags & ImDrawFlags_TextNoPixelSnap) == 0) { x = IM_TRUNC(x); y = IM_TRUNC(y); diff --git a/imgui_internal.h b/imgui_internal.h index 38e475087..8466c2030 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -956,7 +956,7 @@ struct IMGUI_API ImDrawListSharedData ImDrawFlags OverrideStrokePos; // Override default StrokePos when not specified by an individual primitive. == 0 or ImDrawFlags_StrokeLegacy only. float CurveTessellationMaxError; // Tessellation tolerance when using PathBezierCurveTo() float CircleTessellationMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc - ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) + ImDrawFlags InitialDrawFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() ImVector TempBuffer; // Temporary write buffer ImVector DrawLists; // All draw lists associated to this ImDrawListSharedData From 7ccc8348bc202a9ed619dab92b72fa48f0615e7d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jul 2026 21:41:18 +0200 Subject: [PATCH 120/245] (Breaking) Obsoleted style.AntiAliasedLinesUseTex which now only makes sense for legacy strokes. Added style.AntiAliasedLineEnds. # Conflicts: # imgui.cpp --- imgui.cpp | 12 +++++++++--- imgui.h | 9 +++++---- imgui_demo.cpp | 6 ++++++ 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 15bde3e93..aa636181b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -402,6 +402,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ImDrawListFlags_AllowVtxOffset -> ImDrawFlags_UseVtxOffset, - ImDrawListFlags_TextNoPixelSnap -> ImDrawFlags_TextNoPixelSnap, unifying them allows easily using them for both per-primitives alterations and scope alterations. + - obsoleted style.AntiAliasedLinesUseTex which now only makes sense for legacy strokes. - 2026/09/30 (1.93.0) - ImFont: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). (#609, #5748) - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. @@ -1585,9 +1586,9 @@ ImGuiStyle::ImGuiStyle() MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. // Rendering & Tessellation - AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). - AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). + AntiAliasedLines = true; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. + AntiAliasedLineEnds = false; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. + AntiAliasedFill = true; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawFlags_AAFill in all draw-lists. CurveTessellationMaxError = 1.12f; // Maximum error (in pixels) when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1603,6 +1604,7 @@ ImGuiStyle::ImGuiStyle() _NextFrameFontSizeBase = 0.0f; #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS CurveTessellationTol = 0.0f; // Old CurveTessellationTol = CurveTessellationMaxError*CurveTessellationMaxError. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures for legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). #endif // Default theme @@ -5631,8 +5633,12 @@ static void SetupDrawListSharedData() g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AAFill; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALines; + if (g.Style.AntiAliasedLineEnds) + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALineEnds; +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines)) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForStrokeLegacy; +#endif if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForRoundCorners; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) diff --git a/imgui.h b/imgui.h index 09f8b5cc7..27fc13213 100644 --- a/imgui.h +++ b/imgui.h @@ -2395,9 +2395,9 @@ struct ImGuiStyle float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. // Rendering & Tessellation - bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). - bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). - bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). bool AntiAliasedLines; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. + bool AntiAliasedLineEnds; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawFlags_AAFill in all draw-lists. float CurveTessellationMaxError; // Maximum error (in pixels) when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -2422,6 +2422,7 @@ struct ImGuiStyle // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + bool AntiAliasedLinesUseTex; // [OBSOLETE] Enable anti-aliased lines/borders using textures for legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // [OBSOLETE] Old CurveTessellationTol = New CurveTessellationMaxError*CurveTessellationMaxError. // Changed in 1.93.0 // TabMinWidthForCloseButton = TabCloseButtonMinWidthUnselected // Renamed in 1.91.9. #endif @@ -3876,7 +3877,7 @@ struct ImFontAtlas // Input ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). - int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). + int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method never relies on bilinear filtering you may set this to 0. int TexMinWidth; // Minimum desired texture width. Must be a power of two. Default to 512. int TexMinHeight; // Minimum desired texture height. Must be a power of two. Default to 128. int TexMaxWidth; // Maximum desired texture width. Must be a power of two. Default to 8192. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d1188a348..9aaeccf41 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8912,9 +8912,15 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); + Checkbox("Anti-aliased line ends", &style.AntiAliasedLineEnds); + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + BeginDisabled(); Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); SameLine(); HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering)."); + EndDisabled(); +#endif Checkbox("Anti-aliased fill", &style.AntiAliasedFill); PushItemWidth(GetFontSize() * 8); From 008e0990b3b21ae012d068712712b524e60a0b15 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 27 Jul 2026 21:26:10 +0200 Subject: [PATCH 121/245] DrawList: comment about ImFontAtlasFlags_NoBakedLines. Demo: amend test bed to exercices more flags. --- docs/CHANGELOG.txt | 2 ++ imgui.h | 2 +- imgui_demo.cpp | 57 ++++++++++++++++++++++++++-------------------- 3 files changed, 35 insertions(+), 26 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fb7af7591..a4b76821e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -149,6 +149,8 @@ HOW TO UPDATE? - `ImDrawListFlags_AllowVtxOffset` -> `ImDrawFlags_UseVtxOffset` - `ImDrawListFlags_TextNoPixelSnap` -> `ImDrawFlags_TextNoPixelSnap` Unifying them allows easily using them for both per-primitives and scope alterations. +- (Breaking) Enabling ImFontAtlasFlags_NoBakedLines in the font atlas will disable + support for anti-aliased lines. - Tweaked line rendering in various locations to avoid blurryness: - Windows: title-bar and menu-bar border (when thickness>1.0f). - Tables: borders (when thickness>1.0f). diff --git a/imgui.h b/imgui.h index 27fc13213..fd38c3074 100644 --- a/imgui.h +++ b/imgui.h @@ -3759,7 +3759,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). + ImFontAtlasFlags_NoBakedLines = 1 << 2, // [OBSOLETE] Don't build line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENT ANTI-ALIASED STROKES FROM WORKING. ImFontAtlasFlags_NoBakedRoundCorners= 1 << 3, // Don't build round corners into the atlas. }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9aaeccf41..77c689461 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10436,32 +10436,39 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::ColorEdit4("Stroke Color", &colf_stroke.x); ImGui::ColorEdit4("Fill Color", &colf_fill.x); - static ImDrawFlags stroke_flags = ImDrawFlags_AALineEnds; - static ImDrawFlags other_flags = ImDrawFlags_None; - ImGui::Text("Stroke Flags:"); - ImGui::RadioButton("Default", &stroke_flags, ImDrawFlags_None); ImGui::SameLine(); - ImGui::RadioButton("Inside", &stroke_flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); - ImGui::RadioButton("Center", &stroke_flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); - ImGui::RadioButton("CenterBiased", &stroke_flags, ImDrawFlags_StrokeCenterBiased); ImGui::SameLine(); - ImGui::RadioButton("Outside", &stroke_flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); - ImGui::RadioButton("Legacy", &stroke_flags, ImDrawFlags_StrokeLegacy); - ImGui::CheckboxFlags("MiterOnly", &other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); - ImGui::CheckboxFlags("SquareCap", &other_flags, ImDrawFlags_SquareCap); ImGui::SameLine(); - ImGui::CheckboxFlags("AALineEnds", &other_flags, ImDrawFlags_AALineEnds); - ImGui::Spacing(); + static ImDrawFlags prim_stroke_flags = ImDrawFlags_None; + static ImDrawFlags prim_other_flags = ImDrawFlags_AALineEnds; + ImGui::SeparatorText("Per primitive flags (AddXXX functions)"); + ImGui::RadioButton("Default", &prim_stroke_flags, ImDrawFlags_None); ImGui::SameLine(); + ImGui::RadioButton("Inside", &prim_stroke_flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); + ImGui::RadioButton("Center", &prim_stroke_flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); + ImGui::RadioButton("CenterBiased", &prim_stroke_flags, ImDrawFlags_StrokeCenterBiased); ImGui::SameLine(); + ImGui::RadioButton("Outside", &prim_stroke_flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); + ImGui::RadioButton("Legacy", &prim_stroke_flags, ImDrawFlags_StrokeLegacy); + ImGui::CheckboxFlags("AAFill", &prim_other_flags, ImDrawFlags_AAFill); ImGui::SameLine(); // Note: Only for functions taking flags. + ImGui::CheckboxFlags("AALines", &prim_other_flags, ImDrawFlags_AALines); ImGui::SameLine(); // Note: Only for functions taking flags. + ImGui::CheckboxFlags("AALineEnds", &prim_other_flags, ImDrawFlags_AALineEnds); ImGui::SameLine(); + ImGui::CheckboxFlags("MiterOnly", &prim_other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); + ImGui::CheckboxFlags("SquareCap", &prim_other_flags, ImDrawFlags_SquareCap); + //ImGui::CheckboxFlags("UseTexForRoundCorners", &prim_other_flags, ImDrawFlags_UseTexForRoundCorners); ImGui::SameLine(); + //ImGui::CheckboxFlags("UseTexForStrokeLegacy", &prim_other_flags, ImDrawFlags_UseTexForStrokeLegacy); - // FIXME: Clarify how this is exposed, consider changing Demo code to simply alter Style.s - const ImDrawFlags scope_flags_mask = ImDrawFlags_AllowedInScope_; - static ImDrawFlags scope_flags = scope_flags_mask; // All - ImGui::Text("AA Flags:"); + static ImDrawFlags scope_flags = draw_list->Flags; // First init copy current state. + ImGui::SeparatorText("Current ImDrawList flags (e.g. PushDrawFlag function)"); + ImGui::PushID("ScopeFlags"); ImGui::CheckboxFlags("AAFill", &scope_flags, ImDrawFlags_AAFill); ImGui::SameLine(); ImGui::CheckboxFlags("AALines", &scope_flags, ImDrawFlags_AALines); ImGui::SameLine(); - ImGui::CheckboxFlags("AALineEnds", &scope_flags, ImDrawFlags_AALineEnds); - ImGui::CheckboxFlags("UseTexForRoundCorners", &scope_flags, ImDrawFlags_UseTexForRoundCorners); - ImGui::CheckboxFlags("UseTexForStrokeLegacy", &scope_flags, ImDrawFlags_UseTexForStrokeLegacy); ImGui::SameLine(); + ImGui::CheckboxFlags("AALineEnds", &scope_flags, ImDrawFlags_AALineEnds); ImGui::SameLine(); + ImGui::CheckboxFlags("StrokeLegacy", &scope_flags, ImDrawFlags_StrokeLegacy); + //ImGui::CheckboxFlags("UseTexForRoundCorners", &scope_flags, ImDrawFlags_UseTexForRoundCorners); ImGui::SameLine(); + //ImGui::CheckboxFlags("UseTexForStrokeLegacy", &scope_flags, ImDrawFlags_UseTexForStrokeLegacy); + ImGui::PopID(); + ImGui::Spacing(); + ImDrawFlags backup_draw_list_flags = draw_list->Flags; - draw_list->Flags = (draw_list->Flags & ~scope_flags_mask) | scope_flags; - const ImDrawFlags flags = stroke_flags | other_flags; + draw_list->Flags = (draw_list->Flags & ~ImDrawFlags_AllowedInScope_) | scope_flags; // Equivalent to an hypothetical PushDrawFlags() API + const ImDrawFlags flags = prim_stroke_flags | prim_other_flags; + const ImDrawFlags fill_flags = flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); ImVec2 start_pos = ImGui::GetCursorScreenPos(); const float pi = 3.141592f; @@ -10494,9 +10501,9 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddNgonFilled({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments); x += sz + spacing; // N-gon draw_list->AddCircleFilled({ x + half_sz, y + half_sz }, half_sz, col, circle_segments); x += sz + spacing; // Circle draw_list->AddEllipseFilled({ x + half_sz, y + half_sz }, { sz * 0.5f, sz * 0.3f }, col, -0.3f, circle_segments); x += sz + spacing;// Ellipse - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col); x += sz + spacing; // Square - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding); x += sz + spacing; // Square with all rounded corners - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, 0.0f, fill_flags); x += sz + spacing; // Square + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, fill_flags); x += sz + spacing; // Square with all rounded corners + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, corners_tl_br | fill_flags); x += sz + spacing; // Square with two rounded corners draw_list->AddTriangleFilled({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col); x += sz + spacing; // Triangle draw_list->AddTriangleFilled({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col); x += (float)(int)(sz * 0.4f) + spacing; // Thin triangle PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape From 7e87cb984dab5f695b47cba5ec0236af5bdb46ff Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 11:24:48 +0200 Subject: [PATCH 122/245] DrawList: consistently support scope flags (ImDrawFlags::Flags) + primitive flags. ImDrawFlags_AAEnds and ImDrawFlags_StrokeLegacy ok. (the most important ones). ImDrawFlags_UseTexForRoundCorners ok. ImDrawFlags_AAFill, ImDrawFlags_AAStrokes: for primitives: only for selected ones taking flags params. Haven't added the flag to all functions because it feels like a fringe use case. ImDrawFlags_TextNoPixelSnap supported in RenderText(), per-prim (9417) --- docs/CHANGELOG.txt | 1 + imgui.h | 2 +- imgui_draw.cpp | 33 +++++++++++++++++++++++---------- imgui_internal.h | 1 - 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a4b76821e..aef92b48f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -151,6 +151,7 @@ HOW TO UPDATE? Unifying them allows easily using them for both per-primitives and scope alterations. - (Breaking) Enabling ImFontAtlasFlags_NoBakedLines in the font atlas will disable support for anti-aliased lines. +- `ImDrawFlags_TextNoPixelSnap` may be passed to low-level RenderText() primitive. (#9417) - Tweaked line rendering in various locations to avoid blurryness: - Windows: title-bar and menu-bar border (when thickness>1.0f). - Tables: borders (when thickness>1.0f). diff --git a/imgui.h b/imgui.h index fd38c3074..1548b6926 100644 --- a/imgui.h +++ b/imgui.h @@ -3373,7 +3373,7 @@ struct ImDrawList ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector VtxBuffer; // Vertex buffer. - ImDrawFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. + ImDrawFlags Flags; // Current flags for drawing primitives. You may poke into these to adjust anti-aliasing settings per-primitive. Will be exposed as PushDrawFlags(). // [Internal, used while building lists] unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1f16f5a2d..05db80d74 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -964,7 +964,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 ImVec4 tex_uvs; float fringe; - if (Flags & ImDrawFlags_AALines) + flags |= Flags; + if (flags & ImDrawFlags_AALines) { _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); } @@ -1306,7 +1307,8 @@ void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, // Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); - if (Flags & ImDrawFlags_AALines) + flags |= Flags; + if (flags & ImDrawFlags_AALines) { // Anti-aliased stroke const float AA_SIZE = _FringeScale; @@ -1320,7 +1322,7 @@ void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, // Do we want to draw this line using a texture? // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. // - If AA_SIZE is not 1.0f we cannot use the texture path. - const bool use_texture = (Flags & ImDrawFlags_UseTexForStrokeLegacy) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); + const bool use_texture = (flags & ImDrawFlags_UseTexForStrokeLegacy) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); // We should never hit this, because NewFrame() doesn't set ImDrawFlags_UseTexForStrokeLegacy unless ImFontAtlasFlags_NoBakedLines is off IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); @@ -1566,7 +1568,8 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun }*/ const ImVec2 uv = _Data->TexUvWhitePixel; - if (Flags & ImDrawFlags_AAFill) + flags |= Flags; + if (flags & ImDrawFlags_AAFill) { const float half_aa = _FringeScale * 0.5f; ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -2173,7 +2176,7 @@ ImDrawFlags ImDrawList::_GetStrokePos(ImDrawFlags flags, ImDrawFlags default_str { if (flags & ImDrawFlags_StrokeMask_) return (flags & ImDrawFlags_StrokeMask_); - return _Data->OverrideStrokePos ? _Data->OverrideStrokePos : default_stroke_pos; + return default_stroke_pos; } IM_MSVC_RUNTIME_CHECKS_RESTORE @@ -2201,7 +2204,8 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t ImVec4 tex_uvs; float fringe; - if (Flags & ImDrawFlags_AALines) + flags |= Flags; + if (flags & ImDrawFlags_AALines) { _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); } @@ -2339,6 +2343,7 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th if ((col & IM_COL32_A_MASK) == 0) return; + flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { @@ -2354,6 +2359,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th if ((col & IM_COL32_A_MASK) == 0) return; + flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { @@ -2399,6 +2405,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th if ((col & IM_COL32_A_MASK) == 0) return; + flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) { @@ -2575,7 +2582,8 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImVec4 tex_uvs; float fringe; - if (Flags & ImDrawFlags_AALines) + flags |= Flags; + if (flags & ImDrawFlags_AALines) { _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); } @@ -2709,6 +2717,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if ((col & IM_COL32_A_MASK) == 0) return; + flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY @@ -2799,7 +2808,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (Flags & (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners); + const bool allow_tex_corners = (flags & (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners); if (allow_tex_corners && s_thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { // Pixel aligned rect with round corners rendered using baked textures. @@ -2897,6 +2906,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c float width = p_max.x - p_min.x; float height = p_max.y - p_min.y; const float min_dim = ImMin(width, height); + flags |= Flags; // The rect is smaller than pixel in one dimension. if (min_dim < _FringeScale) IM_UNLIKELY @@ -2945,7 +2955,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c return; } // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (Flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); + const bool allow_tex_corners = (flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); if (allow_tex_corners && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); @@ -3033,6 +3043,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu if ((col & IM_COL32_A_MASK) == 0) return; + flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { @@ -3117,6 +3128,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; + flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { @@ -7724,7 +7736,8 @@ begin: float y = pos.y; if (y > clip_rect.w) return; - if ((draw_list->Flags & ImDrawFlags_TextNoPixelSnap) == 0) + flags |= draw_list->Flags; + if ((flags & ImDrawFlags_TextNoPixelSnap) == 0) { x = IM_TRUNC(x); y = IM_TRUNC(y); diff --git a/imgui_internal.h b/imgui_internal.h index 8466c2030..2a246cd7f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -953,7 +953,6 @@ struct IMGUI_API ImDrawListSharedData ImFont* Font; // Current font (used for simplified AddText overload) float FontSize; // Current font size (used for simplified AddText overload) float FontScale; // Current font scale (== FontSize / Font->FontSize) - ImDrawFlags OverrideStrokePos; // Override default StrokePos when not specified by an individual primitive. == 0 or ImDrawFlags_StrokeLegacy only. float CurveTessellationMaxError; // Tessellation tolerance when using PathBezierCurveTo() float CircleTessellationMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc ImDrawFlags InitialDrawFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) From f2cd901be646e689364596eda22fbe0f7e1cb94c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 15:48:40 +0200 Subject: [PATCH 123/245] DrawList: added PushDrawFlag(), PopDrawFlag(), ImSmallStack_<>. (#9504) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 10 ++++------ imgui.h | 24 +++++++++++++++++++----- imgui_demo.cpp | 9 +++++---- imgui_draw.cpp | 26 +++++++++++++++++++++++--- 5 files changed, 52 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index aef92b48f..a271b716b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -137,6 +137,7 @@ HOW TO UPDATE? Thickness=2.0f blurry sharp sharp sharp sharp Thickness=3.0f sharp sharp sharp blurry sharp ------------------------------------------------------------------------ +- Added ImDrawList::PushDrawFlag()/PopDrawFlag() to alter certain flags for a scope. - (Breaking) AddRect, AddCircle, AddNgon, AddEllipse: defaulting to "inside" stroke. - All closed shapes with thickness=1.0f will appear identical. - The difference for thickness>1.0f shapes may be minimal since very large strokes diff --git a/imgui.cpp b/imgui.cpp index aa636181b..c4c24af0a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -17693,10 +17693,9 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con Selectable(buf, false); if (fg_draw_list && IsItemHovered()) { - ImDrawFlags backup_flags = fg_draw_list->Flags; - fg_draw_list->Flags &= ~ImDrawFlags_AALines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + fg_draw_list->PushDrawFlag(ImDrawFlags_AALines, false); // Disable AA on triangle outlines is more readable for very large and thin triangles. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), 1.0f, ImDrawFlags_Closed); - fg_draw_list->Flags = backup_flags; + fg_draw_list->PopDrawFlag(); } } TreePop(); @@ -17712,8 +17711,7 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co // Draw wire-frame version of all triangles ImRect clip_rect = draw_cmd->ClipRect; ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); - ImDrawFlags backup_flags = out_draw_list->Flags; - out_draw_list->Flags &= ~ImDrawFlags_AALines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + out_draw_list->PushDrawFlag(ImDrawFlags_AALines, false); // Disable AA on triangle outlines is more readable for very large and thin triangles. for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; ) { ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list @@ -17731,7 +17729,7 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles } - out_draw_list->Flags = backup_flags; + out_draw_list->PopDrawFlag(); } // [DEBUG] Compute mask of inputs with the same codepoint. diff --git a/imgui.h b/imgui.h index 1548b6926..43944f023 100644 --- a/imgui.h +++ b/imgui.h @@ -2885,6 +2885,19 @@ struct ImGuiStorage #endif }; +// [Internal] Used for small stacks. Do not use. +template +struct ImSmallStack_ +{ + T LocalData[Capacity]; // FIXME: should evolve into using heap, e.g union {} with T* HeapData + add SZ_T Capacity. + SZ_T Size = 0; + + inline void clear() { Size = 0; } + inline T& back() { IM_ASSERT(Size > 0); return LocalData[Size - 1]; } + inline void push_back(const T& v) { IM_ASSERT(Size < Capacity); memcpy(&LocalData[Size], &v, sizeof(v)); Size++; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } +}; + // Flags for ImGuiListClipper (currently not fully exposed in function calls: a future refactor will likely add this to ImGuiListClipper::Begin function equivalent) enum ImGuiListClipperFlags_ { @@ -3300,9 +3313,8 @@ enum ImDrawFlags_ // About usage of flags: // - "Prim" column: 'OK' = flag can be used to configure an individual AddXXX() call. - // - "Scope" column: 'OK' = initialized by ImGui based on Style options (e.g. whether anti-aliased is enabled). + // - "Scope" column: 'OK' = initialized by ImGui based on Style options (e.g. whether anti-aliased is enabled) + may be modified using ImDrawList::PushDrawFlag(). // OK(0)/OK(1) indicates whether this flag is set in the default ImGui Style settings. - // (flag will be possible to alter in a scope using PushDrawFlags()). // - Rounding default to ImDrawFlags_RoundCornersAll when 'rounding > 0'. // - So you only need to use the _RoundCorners flags if you want a special configuration (e.g. a rectangle with one rounded corner). @@ -3352,7 +3364,7 @@ enum ImDrawFlags_ ImDrawFlags_UseVtxOffset = 1 << 23, // -- OK(1) // Can emit 'VtxOffset > 0' to allow large meshes with 16-bit ImDrawIdx. Used by default when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled by the backend. // [Internal] - ImDrawFlags_AllowedInScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset, // [Internal] Values allowed in scope e.g. incoming PushDrawFlags() stack. + ImDrawFlags_AllowedInScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset, // [Internal] Values allowed in PushDrawFlag() scope. ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, // [Internal] ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. @@ -3373,7 +3385,7 @@ struct ImDrawList ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector VtxBuffer; // Vertex buffer. - ImDrawFlags Flags; // Current flags for drawing primitives. You may poke into these to adjust anti-aliasing settings per-primitive. Will be exposed as PushDrawFlags(). + ImDrawFlags Flags; // Current flags for drawing primitives. You may poke into these to adjust anti-aliasing settings per-primitive. Alter with PushDrawFlag(). // [Internal, used while building lists] unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. @@ -3386,6 +3398,7 @@ struct ImDrawList ImVector _ClipRectStack; // [Internal] ImVector _TextureStack; // [Internal] ImVector _CallbacksDataBuf; // [Internal] + ImSmallStack_ _DrawFlagsStack;// [Internal] float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content float _InvFringeScale; // [internal] 1.0 / _FringeScale // FIXME: Consider renaming to _PixelDensity. bool _FringeScaleIsInteger; // [Internal] true if 1/_FringeScale is a whole number, used to select fast path for rendering @@ -3401,6 +3414,8 @@ struct ImDrawList IMGUI_API void PopClipRect(); IMGUI_API void PushTexture(ImTextureRef tex_ref); IMGUI_API void PopTexture(); + IMGUI_API void PushDrawFlag(ImDrawFlags flags, bool enabled); // [BETA] Please notify me if you are using this. + IMGUI_API void PopDrawFlag(); inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } @@ -3542,7 +3557,6 @@ struct ImDrawList IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe); IMGUI_API float _CalculateCenterBiasedOffset(float thickness); - }; // All draw data to render a Dear ImGui frame diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 77c689461..5a5c4892b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10465,8 +10465,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::PopID(); ImGui::Spacing(); - ImDrawFlags backup_draw_list_flags = draw_list->Flags; - draw_list->Flags = (draw_list->Flags & ~ImDrawFlags_AllowedInScope_) | scope_flags; // Equivalent to an hypothetical PushDrawFlags() API + draw_list->PushDrawFlag(ImDrawFlags_AllowedInScope_, false); // Reset all existing (very unusual: done for this demo) + draw_list->PushDrawFlag(scope_flags, true); const ImDrawFlags flags = prim_stroke_flags | prim_other_flags; const ImDrawFlags fill_flags = flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); @@ -10599,11 +10599,12 @@ static void ShowExampleAppCustomRendering(bool* p_open) } ImGui::Dummy(ImVec2((sz + spacing) * 15.0f, (sz + spacing) * 4.0f)); + draw_list->PopDrawFlag(); + draw_list->PopDrawFlag(); + ImGui::PopItemFlag(); ImGui::PopItemWidth(); ImGui::EndTabItem(); - - draw_list->Flags = backup_draw_list_flags; } if (ImGui::BeginTabItem("Canvas")) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 05db80d74..5d9851972 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -470,6 +470,7 @@ void ImDrawList::_ResetForNewFrame() _ClipRectStack.resize(0); _TextureStack.resize(0); _CallbacksDataBuf.resize(0); + _DrawFlagsStack.clear(); _Path.resize(0); _Splitter.Clear(); CmdBuffer.push_back(ImDrawCmd()); @@ -488,6 +489,7 @@ void ImDrawList::_ClearFreeMemory() _ClipRectStack.clear(); _TextureStack.clear(); _CallbacksDataBuf.clear(); + _DrawFlagsStack.clear(); _Path.clear(); _Splitter.ClearFreeMemory(); } @@ -711,6 +713,24 @@ void ImDrawList::PopTexture() _OnChangedTexture(); } +// IMPORTANT: currently limited to 3 deep +void ImDrawList::PushDrawFlag(ImDrawFlags flags, bool enabled) +{ + IM_ASSERT((flags & ~ImDrawFlags_AllowedInScope_) == 0); + _DrawFlagsStack.push_back(Flags); + if (enabled) + Flags |= flags; + else + Flags &= ~flags; +} + +void ImDrawList::PopDrawFlag() +{ + IM_ASSERT_USER_ERROR_RET(_DrawFlagsStack.Size > 0, "Calling PopDrawFlags() too many times!"); + Flags = _DrawFlagsStack.back(); + _DrawFlagsStack.pop_back(); +} + // This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). void ImDrawList::_SetTexture(ImTextureRef tex_ref) { @@ -3138,7 +3158,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ radius = ImMax(0.01f, radius); - // Check overestimate first before testing details. + // Check overestimate first before testing details (+1.0f is intended, not FringeScale) if (radius < (thickness * 2.0f + 1.0f)) { const float unit_apothem = ImCos(IM_PI / (float)num_segments); @@ -5343,7 +5363,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) const int pitch = tex->Width; for (int ly = 0; ly < h; ly++) { - for (int lx = 0; lx < h; lx++) + for (int lx = 0; lx < w; lx++) write_ptr[lx] = SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines) & DEBUG_TEX_CORNER_U8(lx, h); write_ptr += pitch; } @@ -5354,7 +5374,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) const int pitch = tex->Width; for (int ly = 0; ly < h; ly++) { - for (int lx = 0; lx < h; lx++) + for (int lx = 0; lx < w; lx++) write_ptr[lx] = IM_COL32(255, 255, 255, SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines)) & DEBUG_TEX_CORNER_U32(lx, h); write_ptr += pitch; } From 2fdcf895c8b06622a0dbca8ee8f8edad58d1165b Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 16:35:56 +0200 Subject: [PATCH 124/245] DrawList: moved _GetStrokePos() to a local inline function. --- imgui.h | 1 - imgui_draw.cpp | 21 ++++++++++----------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index 43944f023..37ab1cba3 100644 --- a/imgui.h +++ b/imgui.h @@ -3547,7 +3547,6 @@ struct ImDrawList IMGUI_API void _OnChangedTexture(); IMGUI_API void _OnChangedVtxOffset(); IMGUI_API void _SetTexture(ImTextureRef tex_ref); - IMGUI_API ImDrawFlags _GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos); IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5d9851972..7fbe9b3ac 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -925,6 +925,16 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv // Scale the fringe so that the texture matches the line thickness. *out_fringe = _FringeScale * screen_thickness * tex_uvs.w; // tex_uvs.w = 1 / thickness } + +// We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. +// The earlier should use verbatim legacy code but will be removed before release once we confirm that both matches. +static inline ImDrawFlags _GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos) +{ + if (flags & ImDrawFlags_StrokeMask_) + return (flags & ImDrawFlags_StrokeMask_); + return default_stroke_pos; +} + IM_MSVC_RUNTIME_CHECKS_RESTORE extern bool g_LEGACY_STROKES; @@ -2189,17 +2199,6 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } } -// We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. -// The earlier should use verbatim legacy code but will be removed before release once we confirm that both matches. -IM_MSVC_RUNTIME_CHECKS_OFF -ImDrawFlags ImDrawList::_GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos) -{ - if (flags & ImDrawFlags_StrokeMask_) - return (flags & ImDrawFlags_StrokeMask_); - return default_stroke_pos; -} -IM_MSVC_RUNTIME_CHECKS_RESTORE - void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) { if (g_LEGACY_STROKES) IM_UNLIKELY From bd0f638d8b06e87271449e64765bf95b58b5d19e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 16:16:54 +0200 Subject: [PATCH 125/245] Docs: update changelog. --- docs/CHANGELOG.txt | 104 +++++++++++++++++++++++++++------------------ 1 file changed, 63 insertions(+), 41 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a271b716b..9c435e85b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,12 +51,12 @@ HOW TO UPDATE? textures instead of tessellated geometry to draw round corners. - Most of the work courtesy of @memononen, with bits from @ocornut, @thedmd, @potocpav. - Refer to our full guides: - - ImDrawList Vector Rendering Reference - https://github.com/ocornut/imgui/wiki/Draw-List - - Pixel Perfect Anti-aliased Rendering - https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering - - How Anti-aliased Polyline Rendering is Implemented - https://github.com/ocornut/imgui/wiki/Polyline-Rendering + - ImDrawList Vector Rendering Reference: + https://github.com/ocornut/imgui/wiki/Draw-List + - Pixel Perfect Anti-aliased Rendering: + https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering + - How Anti-aliased Polyline Rendering is Implemented: + https://github.com/ocornut/imgui/wiki/Polyline-Rendering - (Breaking) AddLine: removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates. - This fixes inconsistencies in the API and matches the PathXXX API. - By default, stroke thickness extends on both side of the given segment. @@ -64,37 +64,44 @@ HOW TO UPDATE? - Use `ImDrawFlags_StrokeLegacy` to use old offset if required. But you might as well apply the offset manually! - Generally better to use to newly introduced `AddLineH()`, `AddLineV()` functions. READ IF YOU ARE MINDFUL OF PIXEL-PERFECTNESS IN YOUR CUSTOM RENDERING/WIDGETS: - Transition guide for axis-aligned lines: - - When switching from legacy `AddLine()` values to `AddLineV()`, `AddLineH()` you can keep same inputs coordinates as before. - - Old `AddLine({x, y1}, {x, y2}, col)` --> `AddLineV(x, y1, y2, col);` // Vertical line. - - Old `AddLine({x1, y}, {x2, y}, col)` --> `AddLineH(x1, x2, y, col);` // Horizontal line. - - This will be equivalent and faster for thickness=1.0f lines. - - Since `AddLine()` use default stroke pos Center and `AddLineV()`, `AddLineH()` use Inside, thickness>1.0f strokes will differ. - Using `ImDrawFlags_StrokeCenter` will match old result more closely (aka look centered), but is more likely - to look blurry as it already did before. Read table below about StrokePos if you care about pixel-perfect lines. - Transition guide for diagonal lines: - - Your lines will appear offset by -0.5f pixels on each axis. - Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. - It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. - - Old AddLine({x1, y1}, {x2, y2}, col) == AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy); // Offset by +0.5f + disable AA ends. - == AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col, thickness); // Same - This reapplies the old offset, and should get you exactly the same result you previously got for thickness=1.0f lines. - But said result was sometimes ambiguous and renderer dependent. (#3116, #3258, #2441) - - Old AddLine() did not have anti-aliased ends, which could create gaps when rendering shapes out - of multiple contiguous lines instead of using AddPolyline(). There is a possibility that you could - have added fudge offsets here and there which are not necessary anymore or may be simplified. -- AddPolyline(), PathStroke(), AddTriangle(): the algorithm to render lines got overhauled. (#2183, #2964, #7972) + - TRANSITION GUIDE FOR AXIS-ALIGNED LINES: + - When switching from legacy `AddLine()` values to `AddLineV()`, `AddLineH()` you can keep same inputs coordinates as before. + - Old `AddLine({x, y1}, {x, y2}, col)` --> `AddLineV(x, y1, y2, col);` // Vertical line. + - Old `AddLine({x1, y}, {x2, y}, col)` --> `AddLineH(x1, x2, y, col);` // Horizontal line. + - This will be equivalent and faster for thickness=1.0f lines. + - Since `AddLine()` use default stroke pos Center and `AddLineV()`, `AddLineH()` use Inside, thickness>1.0f strokes will differ. + Using `ImDrawFlags_StrokeCenter` will match old result more closely (aka look centered), but is more likely + to look blurry as it already did before. Read table below about StrokePos and the + "Pixel-Perfect Rendering" guide if you care about pixel-perfect lines. + - TRANSITION GUIDE FOR DIAGONAL LINES: + - Your lines will appear offset by -0.5f pixels on each axis. + Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. + It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. + - Old AddLine({x1, y1}, {x2, y2}, col) == AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy); // Offset by +0.5f + disable AA ends. + == AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col, thickness); // Same + This reapplies the old offset, and should get you exactly the same result you previously got for thickness=1.0f lines. + But said result was sometimes ambiguous and renderer dependent. (#3116, #3258, #2441) + - Old `AddLine()` did not have anti-aliased ends, which could create gaps when rendering shapes out + of multiple contiguous lines instead of using AddPolyline(). There is a possibility that you could + have added fudge offsets here and there which are not necessary anymore or may be simplified. +- AddPolyline(), PathStroke(), AddTriangle(): the algorithm to render lines got overhauled. + (#2183, #2964, #7972) - Generally fixed rendering of thick strokes/paths. - - The new stroke expansion now uses corner miter calculation, which keeps thickness along the line segments - consistent. If the corner becomes too sharp, it will be bevelled to avoid long spikes at corners. - - There are also some robustness measures for the case where the line thickness is larger than the - features being drawn. + - The new stroke expansion now uses corner miter calculation, which keeps thickness along + the line segments consistent. If the corner becomes too sharp, it will be bevelled to avoid + long spikes at corners. + - There are also some robustness measures for the case where the line thickness is larger + than the features being drawn. - Rendering artifacts are still possible when the path features are smaller than line thickness, but the artifacts should be more localized. The new implementation attempted to favor simple implementation and robustness over the corner case accuracy. - - Added anti-aliasing ends, most noticeable for thick lines. - - Added `ImDrawFlags_AALineEnds` flag to enable anti-aliased line ends. Enabling AA Ends - by default would be more "correct", but it is slower and increase vertex/index data. + - New rendering code fixes (subtle) inconsistencies between graphics API (e.g. DirectX vs OpenGL) + using different diamond exits rules. New code should work precisely the same regardless + of graphics API. (#3116, #3258, #2441) + - Added `ImDrawFlags_AALineEnds` flag to enable anti-aliased line ends. + - Most noticeable for thick lines. + - Helps fills minor gaps if combining multiple individual lines. + - Enabling AA Ends by default would be more "correct", but it is slower and increase vertex/index data.s - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner (closer to legacy rendering, slightly faster, but corners sharpers than 90 degrees may expand far out). Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() etc functions @@ -111,17 +118,18 @@ HOW TO UPDATE? - Integer-aligned coordinates and thicknesses will automatically use baked textures, saving on both CPU and vertex/index data. - Added `ImFontAtlasFlags_NoBakedRoundCorners` to disable baking round corners in font atlas. - - Added `ImDrawListFlags_RoundCornersUseTex` to disable using round corners. + - Added `ImDrawFlags_UseTexForRoundCorners` to enable using round corners. - AddRectFilled(): non-integer coordinates will now display anti-aliased edges. (#6971) -- Improved minor mismatches when overlapping strokes and filled shapes, e.g. when using inside strokes, +- Improved minor mismatches when overlapping strokes and filled shapes, + e.g. when using inside strokes, - `AddRect()` and `AddRectFilled()` with rounding now overlap better. (#3656) - `AddCircle()` and `AddCircleFilled()` now overlap better. -- Added flags to specify stroke position in all ImDrawList stroking functions: +- Added flags to specify stroke position in all `ImDrawList` stroking functions: - `ImDrawFlags_StrokeInside` (default for closed primitives and AddLineH, AddLineV) - `ImDrawFlags_StrokeCenter` (default for paths, bezier and AddLine) - `ImDrawFlags_StrokeCenterAligned` - `ImDrawFlags_StrokeOutside` - - `ImDrawFlags_StrokeLegacy` + - `ImDrawFlags_StrokeLegacy` (may be set as default for a given scope using PushItemFlag()). - Legacy code was generally applying +0.50f offset which meant that, - with thickness=1.0f: the stroke would appear inside. - with thickness>1.0f: the stroke would start expanding on both sides but starting from that slightly initial offset. @@ -129,7 +137,7 @@ HOW TO UPDATE? - TL;DR; the logic didn't make much sense for thickness>1.0f. - Defaulting to Inside for closed shapes ensure that rectangles and lines are never blurry, regardless of thickness, as long as input coordinates/sizes are integers. (#9359) - - Recap: + - Read our Wiki guides! Recap: ------------------------------------------------------------------------ Legacy Inside Outside Center CenterAligned -------------------------------------------------------------------------------- @@ -137,7 +145,8 @@ HOW TO UPDATE? Thickness=2.0f blurry sharp sharp sharp sharp Thickness=3.0f sharp sharp sharp blurry sharp ------------------------------------------------------------------------ -- Added ImDrawList::PushDrawFlag()/PopDrawFlag() to alter certain flags for a scope. +- Added ImDrawList::PushDrawFlag()/PopDrawFlag() to alter certain flags for a scope, + e.g. `PushDrawFlag(ImDrawFlags_StrokeLegacy, true);` enforce legacy tweaks. - (Breaking) AddRect, AddCircle, AddNgon, AddEllipse: defaulting to "inside" stroke. - All closed shapes with thickness=1.0f will appear identical. - The difference for thickness>1.0f shapes may be minimal since very large strokes @@ -150,9 +159,22 @@ HOW TO UPDATE? - `ImDrawListFlags_AllowVtxOffset` -> `ImDrawFlags_UseVtxOffset` - `ImDrawListFlags_TextNoPixelSnap` -> `ImDrawFlags_TextNoPixelSnap` Unifying them allows easily using them for both per-primitives and scope alterations. -- (Breaking) Enabling ImFontAtlasFlags_NoBakedLines in the font atlas will disable +- (Breaking) Enabling `ImFontAtlasFlags_NoBakedLines` in the font atlas will disable support for anti-aliased lines. -- `ImDrawFlags_TextNoPixelSnap` may be passed to low-level RenderText() primitive. (#9417) +- About `ImDrawFlags_StrokeLegacy`: + - This is designed to emulate old coordinates: + - Most shapes are "StrokeCenter". + - AddLine() adds a +0.5f,+0.5f offset. + - Closed shapes user miter angles. + - But there are known difference between legacy code and ImDrawFlags_StrokeLegacy: + - Thick shapes with acute angles will now preserve thickness. + - Thick shapes with acute angles will protrude a little more. +- About disabling anti-aliasing: + - Disabling anti-aliasing is now emulated by using different UV coordinates. + It does not result in a performance increase any more (however the tendency + is that the new code behave better than old code). + - Many thick shapes had broken corners with old no-AA code, and the old no-AA code + was wildly different from the AA code. Not the case any more. (#288) - Tweaked line rendering in various locations to avoid blurryness: - Windows: title-bar and menu-bar border (when thickness>1.0f). - Tables: borders (when thickness>1.0f). From f511ce18f9edd6ce551836b5ca7c2d72356d20a2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 18:51:22 +0200 Subject: [PATCH 126/245] DrawList: tweak _SelectFringeTexture(). move more-unlikely screen_thickness tests within already-unlikely block. re-add removed asserts. --- imgui_draw.cpp | 51 +++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7fbe9b3ac..c975beab1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -906,23 +906,18 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv // We assume that the screen_thickness has been clamped to 1.0 by the caller. IM_ASSERT_PARANOID(screen_thickness >= 1.0f); - ImVec4 tex_uvs; + // Handle the thickness between 1.0 - IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. + // We use super sampled textures in this range to make texture changes less noticeable. + // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). + int texture_idx; if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) IM_LIKELY - { - // Handle the thickness between 1.0 - IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. - // We use super sampled textures in this range to make texture changes less noticeable. - // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). - int texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f); - tex_uvs = _Data->TexUvLines[(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) + texture_idx]; - } + texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f) + (IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); else - { - const int texture_idx = ImMin((int)(screen_thickness + 0.5f), IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - tex_uvs = _Data->TexUvLines[texture_idx]; - } + texture_idx = ImMin((int)(screen_thickness + 0.5f), IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - *out_tex_uvs = tex_uvs; // Scale the fringe so that the texture matches the line thickness. + ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; + *out_tex_uvs = tex_uvs; *out_fringe = _FringeScale * screen_thickness * tex_uvs.w; // tex_uvs.w = 1 / thickness } @@ -951,15 +946,21 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 return; float screen_thickness = thickness * _InvFringeScale; - if (screen_thickness < 1.0f / 255.0f) - return; - if (screen_thickness < 1.0f) + if (screen_thickness < 1.0f) IM_UNLIKELY { + if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY + return; col = ImAlphaMultiply(col, screen_thickness); screen_thickness = 1.0f; thickness = _FringeScale; } + // If this assert triggers on legacy code: + // - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. + // - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. + // Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. + IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); + // Allocate data for temp buffers _Data->TempBuffer.reserve_discard(points_count * 2); ImVec2* normals = _Data->TempBuffer.Data; @@ -2212,10 +2213,10 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t return; float screen_thickness = thickness * _InvFringeScale; - if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY - return; if (screen_thickness < 1.0f) IM_UNLIKELY { + if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY + return; col = ImAlphaMultiply(col, screen_thickness); screen_thickness = 1.0f; thickness = _FringeScale; @@ -2590,10 +2591,10 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { float screen_thickness = thickness * _InvFringeScale; - if (screen_thickness < 1.0f / 255.0f) - return; - if (screen_thickness < 1.0f) + if (screen_thickness < 1.0f) IM_UNLIKELY { + if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY + return; col = ImAlphaMultiply(col, screen_thickness); screen_thickness = 1.0f; thickness = _FringeScale; @@ -2930,7 +2931,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c // The rect is smaller than pixel in one dimension. if (min_dim < _FringeScale) IM_UNLIKELY { - if (min_dim < (1.0f / 255.0f) * _FringeScale) + if (min_dim < (1.0f / 255.0f) * _FringeScale) IM_UNLIKELY return; if (width < _FringeScale) { @@ -3069,7 +3070,6 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu radius -= 0.5f; stroke_pos = ImDrawFlags_StrokeCenter; } - radius = ImMax(0.01f, radius); float outer_radius = radius; @@ -3154,7 +3154,6 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ radius -= 0.5f; stroke_pos = ImDrawFlags_StrokeCenter; } - radius = ImMax(0.01f, radius); // Check overestimate first before testing details (+1.0f is intended, not FringeScale) @@ -3195,7 +3194,7 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in const float diameter = radius * 2.0f; if (diameter < _FringeScale) IM_UNLIKELY { - if (diameter < (1.0f / 255.0f) * _FringeScale) + if (diameter < (1.0f / 255.0f) * _FringeScale) IM_UNLIKELY return; col = ImAlphaMultiply(col, diameter * _InvFringeScale); radius = _FringeScale * 0.5f; @@ -3246,7 +3245,7 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im // The ellipse is smaller than pixel in one dimension. if (min_dim < _FringeScale) IM_UNLIKELY { - if (min_dim < (1.0f / 255.0f) * _FringeScale) + if (min_dim < (1.0f / 255.0f) * _FringeScale) IM_UNLIKELY return; if (diameter_x < _FringeScale) { From 67bcd9d5451b1ef019598f0340964cf41cee0856 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 19:01:43 +0200 Subject: [PATCH 127/245] DrawList: moved no-AA handling into _SelectFringeTexture(). --- imgui.h | 2 +- imgui_draw.cpp | 96 ++++++++++++++++---------------------------------- 2 files changed, 31 insertions(+), 67 deletions(-) diff --git a/imgui.h b/imgui.h index 37ab1cba3..0e2566a84 100644 --- a/imgui.h +++ b/imgui.h @@ -3554,7 +3554,7 @@ struct ImDrawList IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags); IMGUI_API void _AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); - IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe); + IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe, ImDrawFlags flags); IMGUI_API float _CalculateCenterBiasedOffset(float thickness); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c975beab1..8e23dfd95 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -901,24 +901,33 @@ static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) } // Select texture and adjust fringe size for specified line thickness. -void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe) +void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe, ImDrawFlags flags) { // We assume that the screen_thickness has been clamped to 1.0 by the caller. IM_ASSERT_PARANOID(screen_thickness >= 1.0f); - // Handle the thickness between 1.0 - IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. - // We use super sampled textures in this range to make texture changes less noticeable. - // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). - int texture_idx; - if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) IM_LIKELY - texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f) + (IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); - else - texture_idx = ImMin((int)(screen_thickness + 0.5f), IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + if (flags & ImDrawFlags_AALines) + { + // Handle the thickness between 1.0 - IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. + // We use super sampled textures in this range to make texture changes less noticeable. + // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). + int texture_idx; + if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) IM_LIKELY + texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f) + (IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + else + texture_idx = ImMin((int)(screen_thickness + 0.5f), IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); - // Scale the fringe so that the texture matches the line thickness. - ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; - *out_tex_uvs = tex_uvs; - *out_fringe = _FringeScale * screen_thickness * tex_uvs.w; // tex_uvs.w = 1 / thickness + // Scale the fringe so that the texture matches the line thickness. + ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; + *out_tex_uvs = tex_uvs; + *out_fringe = _FringeScale * screen_thickness * tex_uvs.w; // tex_uvs.w = 1 / thickness + } + else + { + // For no anti-alias we use fully opaque texture, and no fringe expansion. + *out_tex_uvs = ImVec4(_Data->TexUvWhitePixel.x, _Data->TexUvWhitePixel.x, _Data->TexUvWhitePixel.y, 0.0f); // u0, u1, v, 1/thickness (unused) + *out_fringe = 0.0f; + } } // We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. @@ -993,23 +1002,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 sqr_lengths[points_count - 1] = 0.0f; } + flags |= Flags; ImVec4 tex_uvs; float fringe; - flags |= Flags; - if (flags & ImDrawFlags_AALines) - { - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); - } - else - { - // For no anti-alias we use fully opaque texture, and no fringe expansion. - tex_uvs.x = _Data->TexUvWhitePixel.x; // u0 - tex_uvs.y = _Data->TexUvWhitePixel.x; // u1 - tex_uvs.z = _Data->TexUvWhitePixel.y; // v - tex_uvs.w = 0.0f; // 1/thickness, unused. - fringe = 0.0f; - flags &= ~ImDrawFlags_AALineEnds; - } + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe, flags); const ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -1080,7 +1076,6 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dir.x = n1.y; dir.y = -n1.x; - if (flags & ImDrawFlags_SquareCap) { p1.x -= dir.x * half_thickness; @@ -1694,7 +1689,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - bool bevel = miter_distance_sqr > miter_distance_limit_sqr; + const bool bevel = miter_distance_sqr > miter_distance_limit_sqr; if (bevel) { // Limit inner bevel so that it is does not shoot out outside the polygon. @@ -1756,14 +1751,11 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun // Add indices for fill for (int i = 2; i < points_count; i++) - { IM_APPEND_TRI(vtx_inner_idx, vtx_inner_idx + i - 1, vtx_inner_idx + i); - } const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); IM_ASSERT(idx_used <= idx_count && vtx_used <= vtx_count); - if (idx_used < idx_count || vtx_used < vtx_count) PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } @@ -2222,23 +2214,10 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t thickness = _FringeScale; } + flags |= Flags; ImVec4 tex_uvs; float fringe; - flags |= Flags; - if (flags & ImDrawFlags_AALines) - { - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); - } - else - { - // For no anti-alias we use fully opaque texture, and no fringe expansion. - tex_uvs.x = _Data->TexUvWhitePixel.x; // u0 - tex_uvs.y = _Data->TexUvWhitePixel.x; // u1 - tex_uvs.z = _Data->TexUvWhitePixel.y; // v - tex_uvs.w = 0.0f; // 1/thickness, unused. - fringe = 0.0f; - flags &= ~ImDrawFlags_AALineEnds; - } + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe, flags); float dir_x = p2.x - p1.x; float dir_y = p2.y - p1.y; @@ -2289,7 +2268,6 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t float p1_y = p1.y; float p2_x = p2.x; float p2_y = p2.y; - if (flags & ImDrawFlags_SquareCap) { p1_x -= dir_x * half_thickness; @@ -2600,22 +2578,10 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, thickness = _FringeScale; } + flags |= Flags; ImVec4 tex_uvs; float fringe; - flags |= Flags; - if (flags & ImDrawFlags_AALines) - { - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe); - } - else - { - // For no anti-alias we use fully opaque texture, and no fringe expansion. - tex_uvs.x = _Data->TexUvWhitePixel.x; // u0 - tex_uvs.y = _Data->TexUvWhitePixel.x; // u1 - tex_uvs.z = _Data->TexUvWhitePixel.y; // v - tex_uvs.w = 0.0f; // 1/thickness, unused. - fringe = 0.0f; - } + _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe, flags); const int auto_seg_count = _CalcCircleAutoSegmentCount(rounding); int arc_step, arc_step_count; @@ -2693,10 +2659,8 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, // Arc if (is_rounded) - { for (int i = 0; i < arc_point_count - 1; i++) IM_APPEND_TRI(stem_idx, arc_idx + i, arc_idx + i + 1); - } // (keep braces because of macro above) // Connect with previous IM_APPEND_TRI(base_idx + 0, arc_idx, stem_idx); @@ -2715,7 +2679,6 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); IM_ASSERT_PARANOID(idx_used <= idx_count && vtx_used <= vtx_count); - if (idx_used < idx_count || vtx_used < vtx_count) PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); } @@ -2948,6 +2911,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c return; } + // When rounding non-integer and under threshold, has_rounding may be false but still affect is_truncated. Likely not worth catering for. const bool has_rounding = (flags & ImDrawFlags_RoundCornersMask_) != ImDrawFlags_RoundCornersNone && IM_HAS_ROUNDING(rounding); const bool is_truncated = IM_IS_TRUNCATED4(p_min.x, p_min.y, p_max.x, p_max.y) && IM_IS_TRUNCATED(rounding); From 5181e95a465a30a51795a225a0ed017a8723d2e6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 18:27:36 +0200 Subject: [PATCH 128/245] DrawList: removed g_LEGACY_STROKES. --- imgui.cpp | 17 -------------- imgui_draw.cpp | 38 ++++++++---------------------- imgui_tables.cpp | 18 ++------------- imgui_widgets.cpp | 59 ++++++++--------------------------------------- 4 files changed, 22 insertions(+), 110 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c4c24af0a..23ef0bd6b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1382,9 +1382,6 @@ static const ImVec2 TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5f, 1.0f); // Multi // [SECTION] FORWARD DECLARATIONS //------------------------------------------------------------------------- -extern bool g_LEGACY_STROKES; -bool g_LEGACY_STROKES = false; - static void SetCurrentWindow(ImGuiWindow* window); static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); @@ -5939,9 +5936,6 @@ void ImGui::NewFrame() g.DebugBeginReturnValueCullDepth = -1; #endif - g_LEGACY_STROKES = g.IO.KeyShift; - ImGui::Checkbox("g_LEGACY_STROKES", &g_LEGACY_STROKES); - CallContextHooks(&g, ImGuiContextHookType_NewFramePost); } @@ -7326,9 +7320,6 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) { float y = window->Pos.y + window->TitleBarHeight - 1; - if (g_LEGACY_STROKES) - window->DrawList->AddLineH(window->Pos.x + border_size * 0.5f, window->Pos.x + window->Size.x - border_size * 0.5f, y, border_col, g.Style.FrameBorderSize); - else window->DrawList->AddLineH(window->Pos.x + border_size, window->Pos.x + window->Size.x - border_size, y, border_col, g.Style.FrameBorderSize, ImDrawFlags_StrokeCenterBiased); } } @@ -7397,12 +7388,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) - { - if (g_LEGACY_STROKES) - window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5f, menu_bar_rect.Max.x - window_border_size * 0.5f, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize); - else window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size, menu_bar_rect.Max.x - window_border_size, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize, ImDrawFlags_StrokeCenterBiased); - } } // Scrollbars @@ -18347,9 +18333,6 @@ void ImGui::DebugDrawLineExtents(ImU32 col) float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y); float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y); window->DrawList->AddLineH(curr_x - 4.0f, curr_x + 5.0f, line_y1, col, 1.0f); - if (g_LEGACY_STROKES) - window->DrawList->AddLineV(curr_x - 0.5f, line_y1, line_y2, col, 1.0f); - else window->DrawList->AddLineV(curr_x, line_y1, line_y2, col, 1.0f); window->DrawList->AddLineH(curr_x - 4.0f, curr_x + 5.0f, line_y2, col, 1.0f); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8e23dfd95..30283c8fb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -930,8 +930,6 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv } } -// We intently don't turn g_LEGACY_STROKES into ImDrawFlags_StrokeLegacy here. -// The earlier should use verbatim legacy code but will be removed before release once we confirm that both matches. static inline ImDrawFlags _GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos) { if (flags & ImDrawFlags_StrokeMask_) @@ -941,16 +939,8 @@ static inline ImDrawFlags _GetStrokePos(ImDrawFlags flags, ImDrawFlags default_s IM_MSVC_RUNTIME_CHECKS_RESTORE -extern bool g_LEGACY_STROKES; - void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { - if (g_LEGACY_STROKES) - { - AddPolylineLegacy(points, points_count, col, thickness, flags); - return; - } - if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) return; @@ -2194,13 +2184,6 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) { - if (g_LEGACY_STROKES) IM_UNLIKELY - { - ImVec2 points[2] = { p1, p2 }; - AddPolylineLegacy(points, 2, col, thickness, flags); - return; - } - if ((col & IM_COL32_A_MASK) == 0) IM_UNLIKELY return; @@ -2343,7 +2326,7 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (stroke_pos == ImDrawFlags_StrokeLegacy) { _AddLine(ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f), col, thickness, flags); return; @@ -2359,7 +2342,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (stroke_pos == ImDrawFlags_StrokeLegacy) { _AddLine(ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f), col, thickness, flags); return; @@ -2405,7 +2388,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (stroke_pos == ImDrawFlags_StrokeLegacy) { _AddLine(ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f), col, thickness, flags); return; @@ -2702,8 +2685,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY + if (stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { if (Flags & ImDrawFlags_AALines) PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.50f, p_max.y - 0.50f), rounding, flags); @@ -2986,8 +2968,9 @@ void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, c if ((col & IM_COL32_A_MASK) == 0) return; - ImDrawFlags stroke_pos = g_LEGACY_STROKES ? ImDrawFlags_StrokeLegacy : _GetStrokePos(flags, ImDrawFlags_StrokeInside); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; + const ImVec2 points[4] = { p1, p2, p3, p4 }; AddPolyline(points, 4, col, thickness, flags | ImDrawFlags_Closed); } @@ -3006,7 +2989,7 @@ void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p if ((col & IM_COL32_A_MASK) == 0) return; - ImDrawFlags stroke_pos = g_LEGACY_STROKES ? ImDrawFlags_StrokeLegacy : _GetStrokePos(flags, ImDrawFlags_StrokeInside); + ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; const ImVec2 points[3] = { p1, p2, p3 }; @@ -3029,7 +3012,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY + if (stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { radius -= 0.5f; stroke_pos = ImDrawFlags_StrokeCenter; @@ -3113,7 +3096,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ flags |= Flags; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY + if (stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { radius -= 0.5f; stroke_pos = ImDrawFlags_StrokeCenter; @@ -3177,8 +3160,7 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co return; ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - - if (g_LEGACY_STROKES || stroke_pos == ImDrawFlags_StrokeLegacy) + if (stroke_pos == ImDrawFlags_StrokeLegacy) stroke_pos = ImDrawFlags_StrokeCenter; ImVec2 rad = radius; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 469311bcf..0391bf735 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2947,8 +2947,6 @@ static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_ return table->BorderColorLight; } -extern bool g_LEGACY_STROKES; - // FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow) void ImGui::TableDrawBorders(ImGuiTable* table) { @@ -2963,11 +2961,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) // Draw inner border and resizing feedback ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); const float border_size = TABLE_BORDER_SIZE; - float draw_y1; - if (g_LEGACY_STROKES) - draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? 1.0f : 0.0f); - else - draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f); + const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f); const float draw_y2_body = table->InnerRect.Max.y; const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; if (table->Flags & ImGuiTableFlags_BordersInnerV) @@ -3038,12 +3032,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const float h_inset = (table->Flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; const float border_y = table->RowPosY2; if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) - { - if (g_LEGACY_STROKES) - inner_drawlist->AddLineH(table->BorderX1, table->BorderX2, border_y, table->BorderColorLight, border_size); - else inner_drawlist->AddLineH(table->BorderX1 + h_inset, table->BorderX2 - h_inset, border_y, table->BorderColorLight, border_size); - } } inner_drawlist->PopClipRect(); @@ -3637,10 +3626,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label { // Draw border const float border_size = TABLE_BORDER_SIZE; - if (g_LEGACY_STROKES) - draw_list->AddLine(bg_shape[0] - ImVec2(border_size * 0.5f, 0.0f), bg_shape[3] - ImVec2(border_size * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), border_size); - else - draw_list->AddLine(bg_shape[0] + ImVec2(border_size * 0.5f, 0.0f), bg_shape[3] + ImVec2(border_size * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), border_size); + draw_list->AddLine(bg_shape[0] + ImVec2(border_size * 0.5f, 0.0f), bg_shape[3] + ImVec2(border_size * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), border_size); } } PopClipRect(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d5d3facbd..81262b9d2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -903,8 +903,6 @@ bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None); } -extern bool g_LEGACY_STROKES; - // Button to close a window bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) { @@ -934,7 +932,7 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact); const ImU32 cross_col = GetColorU32(ImGuiCol_Text); - const ImVec2 cross_center = g_LEGACY_STROKES ? (bb.GetCenter() - ImVec2(0.5f, 0.5f)) : bb.GetCenter(); + const ImVec2 cross_center = bb.GetCenter(); const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; const float cross_thickness = 1.0f * (float)(int)g.Style._MainScale; // FIXME-DPI window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness); @@ -1759,11 +1757,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end const float sep1_x1 = pos.x; const float sep2_x2 = bb.Max.x; - float seps_y; - if (g_LEGACY_STROKES) - seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.999f); - else - seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f) + 1.0f; + float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f) + 1.0f; const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f); const ImVec2 label_pos(pos.x + padding.x + ImMax(0.0f, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y); // FIXME-ALIGN @@ -5765,11 +5759,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ state->CursorAnim += io.DeltaTime; bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); - ImRect cursor_screen_rect; - if (g_LEGACY_STROKES) - cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); - else - cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 1.0f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.0f); + ImRect cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 1.0f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.0f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) draw_window->DrawList->AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, GetColorU32(ImGuiCol_InputTextCursor), style.InputTextCursorSize, ImDrawFlags_StrokeInside); @@ -7321,27 +7311,16 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) // FIXME: Could this be simplified using new stroke flags? ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; const float half_size = g.Style.TreeLinesSize * 0.5f; - float x1; - if (g_LEGACY_STROKES) - x1 = ImTrunc(parent_data->DrawLinesX1); - else - x1 = ImTrunc(parent_data->DrawLinesX1 - half_size) + half_size; // Draw line centered at X1, but snap to pixels boundary. + float x1 = ImTrunc(parent_data->DrawLinesX1 - half_size) + half_size; // Draw line centered at X1, but snap to pixels boundary. float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); - float y; - if (g_LEGACY_STROKES) - y = ImTrunc(target_pos.y); - else - y = ImTrunc(target_pos.y - half_size) + half_size; + float y = ImTrunc(target_pos.y - half_size) + half_size; float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f; parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding); if (x1 >= x2) return; if (rounding > 0.0f && rounding > half_size) { - if (g_LEGACY_STROKES) - x1 += 0.5f + rounding; - else - x1 += rounding; + x1 += rounding; window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3); if (x1 < x2) window->DrawList->PathLineTo(ImVec2(x2, y)); @@ -7351,8 +7330,7 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) { // We use AddLine() instead of AddLineH() as we provide coordinates for line center, // in order to make the code use same coordinates for both rounded and non-rounded version. (FIXME-OPT) - if (!g_LEGACY_STROKES) - x1 += half_size; // Avoid overdraw + x1 += half_size; // Avoid overdraw window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } } @@ -7376,11 +7354,7 @@ void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) y2 = ImMin(y2, window->ClipRect.Max.y); if (y2 <= y1) return; - float x; - if (g_LEGACY_STROKES) - x = ImTrunc(data->DrawLinesX1); - else - x = ImTrunc(data->DrawLinesX1 - g.Style.TreeLinesSize * 0.5f) + g.Style.TreeLinesSize * 0.5f; // Draw line centered at X1, but snap to pixels boundary. + float x = ImTrunc(data->DrawLinesX1 - g.Style.TreeLinesSize * 0.5f) + g.Style.TreeLinesSize * 0.5f; // Draw line centered at X1, but snap to pixels boundary. if (data->DrawLinesTableColumn != -1) TablePushColumnChannel(data->DrawLinesTableColumn); @@ -10977,18 +10951,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) { // Might be moved to TabItemBackground() ? - ImVec2 tl; - ImVec2 tr; - if (g_LEGACY_STROKES) - { - tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); - tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); - } - else - { - tl = bb.GetTL() + ImVec2(0, style.TabBarOverlineSize * 0.5f); - tr = bb.GetTR() + ImVec2(0, style.TabBarOverlineSize * 0.5f); - } + ImVec2 tl = bb.GetTL() + ImVec2(0, style.TabBarOverlineSize * 0.5f); + ImVec2 tr = bb.GetTR() + ImVec2(0, style.TabBarOverlineSize * 0.5f); ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline); if (style.TabRounding > 0.0f) { @@ -10999,9 +10963,6 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } else { - if (g_LEGACY_STROKES) - display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize); - else display_draw_list->AddLine(tl, tr, overline_col, style.TabBarOverlineSize); } } From 46e4c2609551d20efeaac7dd608da8418916466b Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 28 Jul 2026 18:29:52 +0200 Subject: [PATCH 129/245] DrawList: removed AddPolylineLegacy(), AddConvexPolyFilledLegacy(). --- imgui.h | 2 - imgui_draw.cpp | 351 ------------------------------------------------- 2 files changed, 353 deletions(-) diff --git a/imgui.h b/imgui.h index 0e2566a84..bb1f9452f 100644 --- a/imgui.h +++ b/imgui.h @@ -3451,9 +3451,7 @@ struct ImDrawList // - Only simple polygons are supported by filling functions (no self-intersections, no holes). // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); - IMGUI_API void AddPolylineLegacy(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags = 0); - IMGUI_API void AddConvexPolyFilledLegacy(const ImVec2* points, int num_points, ImU32 col); IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); // Image primitives diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 30283c8fb..2d09bf270 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1307,269 +1307,6 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 PrimUnreserve(remaining_idx_count, remaining_vtx_count); } -void ImDrawList::AddPolylineLegacy(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) -{ - if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) - return; - - const bool closed = (flags & ImDrawFlags_Closed) != 0; - const ImVec2 opaque_uv = _Data->TexUvWhitePixel; - const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw - const bool thick_line = (thickness > _FringeScale); - - // If this assert triggers on legacy code: - // - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. - // - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. - // Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. - IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); - - flags |= Flags; - if (flags & ImDrawFlags_AALines) - { - // Anti-aliased stroke - const float AA_SIZE = _FringeScale; - const ImU32 col_trans = col & ~IM_COL32_A_MASK; - - // Thicknesses <1.0 should behave like thickness 1.0 - thickness = ImMax(thickness, 1.0f); - const int integer_thickness = (int)thickness; - const float fractional_thickness = thickness - integer_thickness; - - // Do we want to draw this line using a texture? - // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. - // - If AA_SIZE is not 1.0f we cannot use the texture path. - const bool use_texture = (flags & ImDrawFlags_UseTexForStrokeLegacy) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); - - // We should never hit this, because NewFrame() doesn't set ImDrawFlags_UseTexForStrokeLegacy unless ImFontAtlasFlags_NoBakedLines is off - IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); - - const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); - const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); - PrimReserve(idx_count, vtx_count); - - // Temporary buffer - // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point - _Data->TempBuffer.reserve_discard(points_count * ((use_texture || !thick_line) ? 3 : 5)); - ImVec2* temp_normals = _Data->TempBuffer.Data; - ImVec2* temp_points = temp_normals + points_count; - - // Calculate normals (tangents) for each line segment - for (int i1 = 0; i1 < count; i1++) - { - const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; - float dx = points[i2].x - points[i1].x; - float dy = points[i2].y - points[i1].y; - IM_NORMALIZE2F_OVER_ZERO(dx, dy); - temp_normals[i1].x = dy; - temp_normals[i1].y = -dx; - } - if (!closed) - temp_normals[points_count - 1] = temp_normals[points_count - 2]; - - // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point - if (use_texture || !thick_line) - { - // [PATH 1] Texture-based lines (thick or non-thick) - // [PATH 2] Non texture-based lines (non-thick) - - // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus "one pixel" for AA. - // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture - // (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code. - // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to - // allow scaling geometry while preserving one-screen-pixel AA fringe). - const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; - - // If line is not closed, the first and last points need to be generated differently as there are no normals to blend - if (!closed) - { - temp_points[0] = points[0] + temp_normals[0] * half_draw_size; - temp_points[1] = points[0] - temp_normals[0] * half_draw_size; - temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size; - temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size; - } - - // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges - // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) - // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. - unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment - for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment - { - const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment - const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment - - // Average normals - float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; - float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; - IM_FIXNORMAL2F(dm_x, dm_y); - dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area - dm_y *= half_draw_size; - - // Add temporary vertices for the outer edges - ImVec2* out_vtx = &temp_points[i2 * 2]; - out_vtx[0].x = points[i2].x + dm_x; - out_vtx[0].y = points[i2].y + dm_y; - out_vtx[1].x = points[i2].x - dm_x; - out_vtx[1].y = points[i2].y - dm_y; - - if (use_texture) - { - // Add indices for two triangles - _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri - _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri - _IdxWritePtr += 6; - } - else - { - // Add indexes for four triangles - _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1 - _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2 - _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1 - _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2 - _IdxWritePtr += 12; - } - - idx1 = idx2; - } - - // Add vertices for each point on the line - if (use_texture) - { - // If we're using textures we only need to emit the left/right edge vertices - ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness]; - /*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false! - { - const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1]; - tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() - tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; - tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; - tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; - }*/ - ImVec2 tex_uv0(tex_uvs.x, tex_uvs.z); - ImVec2 tex_uv1(tex_uvs.y, tex_uvs.z); - for (int i = 0; i < points_count; i++) - { - _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge - _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge - _VtxWritePtr += 2; - } - } - else - { - // If we're not using a texture, we need the center vertex as well - for (int i = 0; i < points_count; i++) - { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Center of line - _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge - _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge - _VtxWritePtr += 3; - } - } - } - else - { - // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point - const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; - - // If line is not closed, the first and last points need to be generated differently as there are no normals to blend - if (!closed) - { - const int points_last = points_count - 1; - temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); - temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); - temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); - temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); - temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE); - temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness); - temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness); - temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); - } - - // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges - // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) - // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. - unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment - for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment - { - const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment - const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment - - // Average normals - float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; - float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; - IM_FIXNORMAL2F(dm_x, dm_y); - float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE); - float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE); - float dm_in_x = dm_x * half_inner_thickness; - float dm_in_y = dm_y * half_inner_thickness; - - // Add temporary vertices - ImVec2* out_vtx = &temp_points[i2 * 4]; - out_vtx[0].x = points[i2].x + dm_out_x; - out_vtx[0].y = points[i2].y + dm_out_y; - out_vtx[1].x = points[i2].x + dm_in_x; - out_vtx[1].y = points[i2].y + dm_in_y; - out_vtx[2].x = points[i2].x - dm_in_x; - out_vtx[2].y = points[i2].y - dm_in_y; - out_vtx[3].x = points[i2].x - dm_out_x; - out_vtx[3].y = points[i2].y - dm_out_y; - - // Add indexes - _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); - _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1); - _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); - _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); - _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3); - _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2); - _IdxWritePtr += 18; - - idx1 = idx2; - } - - // Add vertices - for (int i = 0; i < points_count; i++) - { - _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans; - _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; - _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; - _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans; - _VtxWritePtr += 4; - } - } - _VtxCurrentIdx += (ImDrawIdx)vtx_count; - } - else - { - // [PATH 4] Non texture-based, Non anti-aliased lines - const int idx_count = count * 6; - const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges - PrimReserve(idx_count, vtx_count); - - for (int i1 = 0; i1 < count; i1++) - { - const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; - const ImVec2& p1 = points[i1]; - const ImVec2& p2 = points[i2]; - - float dx = p2.x - p1.x; - float dy = p2.y - p1.y; - IM_NORMALIZE2F_OVER_ZERO(dx, dy); - dx *= (thickness * 0.5f); - dy *= (thickness * 0.5f); - - _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; - _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; - _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; - _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col; - _VtxWritePtr += 4; - - _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2); - _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3); - _IdxWritePtr += 6; - _VtxCurrentIdx += 4; - } - } -} - // - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, ImDrawFlags flags) @@ -1577,12 +1314,6 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun if (points_count < 3 || (col & IM_COL32_A_MASK) == 0) return; -/* if (ImGui::GetIO().KeyShift) - { - AddConvexPolyFilledLegacy(points, points_count, col); - return; - }*/ - const ImVec2 uv = _Data->TexUvWhitePixel; flags |= Flags; if (flags & ImDrawFlags_AAFill) @@ -1763,88 +1494,6 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun } } -void ImDrawList::AddConvexPolyFilledLegacy(const ImVec2* points, const int points_count, ImU32 col) -{ - if (points_count < 3 || (col & IM_COL32_A_MASK) == 0) - return; - - const ImVec2 uv = _Data->TexUvWhitePixel; - - if (Flags & ImDrawFlags_AAFill) - { - // Anti-aliased Fill - const float AA_SIZE = _FringeScale; - const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int idx_count = (points_count - 2)*3 + points_count * 6; - const int vtx_count = (points_count * 2); - PrimReserve(idx_count, vtx_count); - - // Add indexes for fill - unsigned int vtx_inner_idx = _VtxCurrentIdx; - unsigned int vtx_outer_idx = _VtxCurrentIdx + 1; - for (int i = 2; i < points_count; i++) - { - _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1)); - _IdxWritePtr += 3; - } - - // Compute normals - _Data->TempBuffer.reserve_discard(points_count); - ImVec2* temp_normals = _Data->TempBuffer.Data; - for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) - { - const ImVec2& p0 = points[i0]; - const ImVec2& p1 = points[i1]; - float dx = p1.x - p0.x; - float dy = p1.y - p0.y; - IM_NORMALIZE2F_OVER_ZERO(dx, dy); - temp_normals[i0].x = dy; - temp_normals[i0].y = -dx; - } - - for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) - { - // Average normals - const ImVec2& n0 = temp_normals[i0]; - const ImVec2& n1 = temp_normals[i1]; - float dm_x = (n0.x + n1.x) * 0.5f; - float dm_y = (n0.y + n1.y) * 0.5f; - IM_FIXNORMAL2F(dm_x, dm_y); - dm_x *= AA_SIZE * 0.5f; - dm_y *= AA_SIZE * 0.5f; - - // Add vertices - _VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner - _VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer - _VtxWritePtr += 2; - - // Add indexes for fringes - _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); - _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); - _IdxWritePtr += 6; - } - _VtxCurrentIdx += (ImDrawIdx)vtx_count; - } - else - { - // Non Anti-aliased Fill - const int idx_count = (points_count - 2)*3; - const int vtx_count = points_count; - PrimReserve(idx_count, vtx_count); - for (int i = 0; i < vtx_count; i++) - { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; - _VtxWritePtr++; - } - for (int i = 2; i < points_count; i++) - { - _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i); - _IdxWritePtr += 3; - } - _VtxCurrentIdx += (ImDrawIdx)vtx_count; - } -} - // Calculates arc step and step count for 90 degree arc. The calculated arc step will complete a 90 degree arc when stepped arc_step_count times. IM_MSVC_RUNTIME_CHECKS_OFF static void CalcArcStepAndCount(int segment_count, int& arc_step, int& arc_step_count) From eb02a7f24ceae9766860bc58cc2d80f012b17d05 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jul 2026 14:16:21 +0200 Subject: [PATCH 130/245] DrawList: support altering RoundCorners flags in scope as an undocumented trick/hack. (#9489) Not documented because it could become troublesome if treated as a guaranteed styling feature. --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index bb1f9452f..93513c85d 100644 --- a/imgui.h +++ b/imgui.h @@ -3364,8 +3364,8 @@ enum ImDrawFlags_ ImDrawFlags_UseVtxOffset = 1 << 23, // -- OK(1) // Can emit 'VtxOffset > 0' to allow large meshes with 16-bit ImDrawIdx. Used by default when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled by the backend. // [Internal] - ImDrawFlags_AllowedInScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset, // [Internal] Values allowed in PushDrawFlag() scope. ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, // [Internal] + ImDrawFlags_AllowedInScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundCornersMask_, // [Internal] Values allowed in PushDrawFlag() scope. ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. }; From b220bffdbb1175b7666f916cdec9703b57532ee6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jul 2026 15:02:15 +0200 Subject: [PATCH 131/245] Checkbox, Menus: check marks use anti-aliased ends. Currently not a satisfying resolution. --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9c435e85b..bc7c6bbb5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -182,6 +182,7 @@ HOW TO UPDATE? - Tree: hierarchy lines (when thickness>1.0f). - TabBar: selected overline border ((when thickness>1.0f). - Demo: Custom Rendering: canvas lines. +- Checkbox, Menus: check marks use anti-aliased ends. - Demo: Custom Rendering: exposed new flags; Showcasing overlapping strokes and filled shapes; Added an option to animation thickness; Added new shapes to showcase new rendering features that previously hit limitations. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2d09bf270..df4b7d21f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -7618,7 +7618,7 @@ void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float draw_list->PathLineTo(ImVec2(bx - third, by - third)); draw_list->PathLineTo(ImVec2(bx, by)); draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f)); - draw_list->PathStroke(col, thickness); + draw_list->PathStroke(col, thickness, (draw_list->Flags & ImDrawFlags_AALines) ? ImDrawFlags_AALineEnds : 0); // FIXME: Design idiomatic selection/threshold for this? } // Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. From ee66cfcdf35cca4f20763bd47e0c08aa87fa1141 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jul 2026 16:27:29 +0200 Subject: [PATCH 132/245] TabBar: simpify TabItem rendering using stroke flags. May tend toward using _StrokeInside more but _StrokeCenterBiased is closer to current behavior. --- imgui_widgets.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 81262b9d2..8a210c415 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -11052,14 +11052,14 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f)); const float y1 = bb.Min.y + 1.0f; // Leave a bit of room in title bars. const float y2 = bb.Max.y - g.Style.TabBarBorderSize; - draw_list->AddRectFilled(bb.Min, ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags_RoundCornersTop); + draw_list->AddRectFilled(ImVec2(bb.Min.x, y1), ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags_RoundCornersTop); if (g.Style.TabBorderSize > 0.0f) { - draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2)); - draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9); - draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12); - draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2)); - draw_list->PathStroke(GetColorU32(ImGuiCol_Border), g.Style.TabBorderSize); + draw_list->PathLineTo(ImVec2(bb.Min.x, y2)); + draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9); + draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12); + draw_list->PathLineTo(ImVec2(bb.Max.x, y2)); + draw_list->PathStroke(GetColorU32(ImGuiCol_Border), g.Style.TabBorderSize, ImDrawFlags_StrokeCenterBiased); // Use _StrokeInside? } } From 7a510274cec2a2e5f59a85d4b015db20874cfcff Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 29 Jul 2026 17:26:42 +0200 Subject: [PATCH 133/245] DrawList: Comments. Atlas's NoBakedLines automatically disable AA at Style level. Fix passing non-Legacy stroke mask to PushDrawFlag(). Demo: Custom Rendering: use LiveEdit everywhere. --- docs/CHANGELOG.txt | 8 ++++---- imgui.cpp | 2 ++ imgui.h | 4 ++-- imgui_draw.cpp | 15 +++++++++------ 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bc7c6bbb5..00f31e1de 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -103,7 +103,7 @@ HOW TO UPDATE? - Helps fills minor gaps if combining multiple individual lines. - Enabling AA Ends by default would be more "correct", but it is slower and increase vertex/index data.s - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner (closer to legacy - rendering, slightly faster, but corners sharpers than 90 degrees may expand far out). + rendering, slightly faster, but corners sharper than 90 degrees may expand far out). Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() etc functions since we know that the input path does not contains sharper corners. - Added `ImDrawFlags_SquareCap` flag to use extend lines ends using square caps. @@ -127,9 +127,9 @@ HOW TO UPDATE? - Added flags to specify stroke position in all `ImDrawList` stroking functions: - `ImDrawFlags_StrokeInside` (default for closed primitives and AddLineH, AddLineV) - `ImDrawFlags_StrokeCenter` (default for paths, bezier and AddLine) - - `ImDrawFlags_StrokeCenterAligned` + - `ImDrawFlags_StrokeCenterBiased` - `ImDrawFlags_StrokeOutside` - - `ImDrawFlags_StrokeLegacy` (may be set as default for a given scope using PushItemFlag()). + - `ImDrawFlags_StrokeLegacy` (may be set as default for a given scope using PushDrawFlag()). - Legacy code was generally applying +0.50f offset which meant that, - with thickness=1.0f: the stroke would appear inside. - with thickness>1.0f: the stroke would start expanding on both sides but starting from that slightly initial offset. @@ -139,7 +139,7 @@ HOW TO UPDATE? regardless of thickness, as long as input coordinates/sizes are integers. (#9359) - Read our Wiki guides! Recap: ------------------------------------------------------------------------ - Legacy Inside Outside Center CenterAligned + Legacy Inside Outside Center CenterBiased -------------------------------------------------------------------------------- Thickness=1.0f sharp sharp sharp blurry sharp Thickness=2.0f blurry sharp sharp sharp sharp diff --git a/imgui.cpp b/imgui.cpp index 23ef0bd6b..e03bc6f19 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5626,6 +5626,8 @@ static void SetupDrawListSharedData() g.DrawListSharedData.CurveTessellationMaxError = g.Style.CurveTessellationMaxError; g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError); g.DrawListSharedData.InitialDrawFlags = ImDrawFlags_None; + if (g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines) + g.Style.AntiAliasedLines = g.Style.AntiAliasedLineEnds = false; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AAFill; if (g.Style.AntiAliasedLines) diff --git a/imgui.h b/imgui.h index 93513c85d..737c9921e 100644 --- a/imgui.h +++ b/imgui.h @@ -3434,7 +3434,7 @@ struct ImDrawList IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); - IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f, ImDrawFlags = 0); + IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f, ImDrawFlags flags = 0); IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); @@ -3770,7 +3770,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoBakedLines = 1 << 2, // [OBSOLETE] Don't build line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENT ANTI-ALIASED STROKES FROM WORKING. + ImFontAtlasFlags_NoBakedLines = 1 << 2, // [OBSOLETE] Don't build line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENT ANTI-ALIASED STROKES FROM WORKING AND WILL DISABLE AA. ImFontAtlasFlags_NoBakedRoundCorners= 1 << 3, // Don't build round corners into the atlas. }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index df4b7d21f..6c905163b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -717,6 +717,7 @@ void ImDrawList::PopTexture() void ImDrawList::PushDrawFlag(ImDrawFlags flags, bool enabled) { IM_ASSERT((flags & ~ImDrawFlags_AllowedInScope_) == 0); + IM_ASSERT((flags & ImDrawFlags_StrokeMask_) == 0 || (flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy); _DrawFlagsStack.push_back(Flags); if (enabled) Flags |= flags; @@ -726,7 +727,7 @@ void ImDrawList::PushDrawFlag(ImDrawFlags flags, bool enabled) void ImDrawList::PopDrawFlag() { - IM_ASSERT_USER_ERROR_RET(_DrawFlagsStack.Size > 0, "Calling PopDrawFlags() too many times!"); + IM_ASSERT_USER_ERROR_RET(_DrawFlagsStack.Size > 0, "Calling PopDrawFlag() too many times!"); Flags = _DrawFlagsStack.back(); _DrawFlagsStack.pop_back(); } @@ -894,7 +895,7 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE IM_MSVC_RUNTIME_CHECKS_OFF static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) { - IM_ASSERT_PARANOID(a >= 0.0f && a < 1.0f); // We don't clamp! + IM_ASSERT_PARANOID(alpha_mul >= 0.0f && alpha_mul < 1.0f); // We don't clamp! ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); @@ -2022,7 +2023,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th } else { - // Replace stroke pos with the already calculated one. + // Replace stroke pos with the already calculated one, as AddPolyline() default is different. flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // For generic case use line, since it needs less triangles than AA rectangle. @@ -2068,7 +2069,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th } else { - // Replace stroke pos with the already calculated one. + // Replace stroke pos with the already calculated one, as AddPolyline() default is different. flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // For generic case use line, since it needs less triangles than AA rectangle. @@ -2617,8 +2618,9 @@ void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, c if ((col & IM_COL32_A_MASK) == 0) return; + //flags |= Flags; // Not needed. ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; + flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // As AddPolyline() default is different const ImVec2 points[4] = { p1, p2, p3, p4 }; AddPolyline(points, 4, col, thickness, flags | ImDrawFlags_Closed); @@ -2638,8 +2640,9 @@ void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p if ((col & IM_COL32_A_MASK) == 0) return; + //flags |= Flags; // Not needed. ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; + flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // As AddPolyline() default is different const ImVec2 points[3] = { p1, p2, p3 }; AddPolyline(points, 3, col, thickness, flags | ImDrawFlags_Closed); From ba918bc45c6c85e877187f83faf8a9124668be68 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Wed, 29 Jul 2026 19:02:14 +0300 Subject: [PATCH 134/245] DrawList: fixed filled rect baked AA. Always add 1px to the fill side of the rounded corner to prevent the corner AA to bleed into the rectangle edges. --- imgui_draw.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6c905163b..7ae1a0b29 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2575,9 +2575,10 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if (allow_tex_corners && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); - const int size = ImMax(2, s_rounding); // This is matching the baking calculations. - const int idx = (s_rounding - 1); - IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); + // This is matching the baking calculations. The rounding clamping above makes sure that there's enough space for the extra pixel. + const int size = s_rounding + 1; + const int idx = (s_rounding - 1); + IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); ImVec4 tex_uvs = _Data->TexUvCorners[idx]; _AddRectFilledBaked(p_min, p_max, col, (float)size * _FringeScale, tex_uvs, flags); return; @@ -4919,7 +4920,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) row_height = 0; for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) { - const int size = ImMax(2, ImMax(i + 1, thickness)) + 2; + const int size = ImMax(i + 2, thickness) + 2; row_width += size; row_height = ImMax(row_height, size); } @@ -4940,8 +4941,8 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Filled for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) { - const int rounding = n+1; - const int s = ImMax(2, rounding); // We need at least 2px so that stretching has solid color. + const int rounding = n + 1; + const int s = rounding + 1; // Always add 1px to the fill side of the rounded corner to prevent the corner AA to bleed into the rectangle edges. const int w = s + 2; const int h = s + 2; From a597beaf954bc90ad286b8a5599cfec43ab23430 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jul 2026 14:37:23 +0200 Subject: [PATCH 135/245] DrawList: fixed dropping prim flags in some paths (most for ImDrawFlags_AAXXX flags). --- imgui_draw.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7ae1a0b29..06838cdd3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -959,6 +959,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. // - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. // Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. + flags |= Flags; IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); // Allocate data for temp buffers @@ -993,7 +994,6 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 sqr_lengths[points_count - 1] = 0.0f; } - flags |= Flags; ImVec4 tex_uvs; float fringe; _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe, flags); @@ -2337,11 +2337,11 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); if (stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY { - if (Flags & ImDrawFlags_AALines) + if (flags & ImDrawFlags_AALines) PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.50f, p_max.y - 0.50f), rounding, flags); else PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.49f, p_max.y - 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeCenter); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeCenter | (flags & ~ImDrawFlags_StrokeMask_)); return; } @@ -2441,7 +2441,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { const ImVec2 points[4] = { outer_min, ImVec2(outer_max.x, outer_min.y), outer_max, ImVec2(outer_min.x, outer_max.y) }; - AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); + AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_)); } else { @@ -2461,7 +2461,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathArcToFast(ImVec2(outer_max.x - rounding_tr, outer_min.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(outer_max.x - rounding_br, outer_max.y - rounding_br), rounding_br, 0, 3); PathArcToFast(ImVec2(outer_min.x + rounding_bl, outer_max.y - rounding_bl), rounding_bl, 3, 6); - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_)); } } From 20f17eeb6f06f68722994aa0689baebf58c148eb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jul 2026 14:48:28 +0200 Subject: [PATCH 136/245] DrawList: fixed using ImDrawFlags_UseTexForRoundCorners when ImFontAtlasFlags_NoBakedRoundCorners has also been set. --- imgui.cpp | 2 +- imgui.h | 4 +++- imgui_demo.cpp | 4 ++-- imgui_draw.cpp | 10 +++++----- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e03bc6f19..fa5dfe7e4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5639,7 +5639,7 @@ static void SetupDrawListSharedData() g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForStrokeLegacy; #endif if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForRoundCorners; + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseVtxOffset; } diff --git a/imgui.h b/imgui.h index 737c9921e..3eef737d2 100644 --- a/imgui.h +++ b/imgui.h @@ -3362,10 +3362,12 @@ enum ImDrawFlags_ ImDrawFlags_UseTexForRoundCorners = 1 << 21, // -- OK(1) // Enable using textures instead of strokes to draw rounded corners/circles where possible (faster). Used by default unless 'ImFontAtlasFlags_NoBakedRoundCorners' is enabled in the font atlas. ImDrawFlags_UseTexForStrokeLegacy = 1 << 22, // -- OK(1) // Enable anti-aliased lines/borders using textures when using legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). Used by default unless 'ImFontAtlasFlags_NoBakedLines' is set in the font atlas. ImDrawFlags_UseVtxOffset = 1 << 23, // -- OK(1) // Can emit 'VtxOffset > 0' to allow large meshes with 16-bit ImDrawIdx. Used by default when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled by the backend. + ImDrawFlags_AllowTexForRoundCorners_= 1 << 24, // -- OK(1) // [Internal] // [Internal] ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, // [Internal] - ImDrawFlags_AllowedInScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundCornersMask_, // [Internal] Values allowed in PushDrawFlag() scope. + ImDrawFlags_AllowInPushScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundCornersMask_, // [Internal] Values allowed in PushDrawFlag() scope. + ImDrawFlags_AllowInFrameScope_ = ImDrawFlags_AllowInPushScope_ | ImDrawFlags_AllowTexForRoundCorners_, ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5a5c4892b..041cee6b4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10453,7 +10453,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) //ImGui::CheckboxFlags("UseTexForRoundCorners", &prim_other_flags, ImDrawFlags_UseTexForRoundCorners); ImGui::SameLine(); //ImGui::CheckboxFlags("UseTexForStrokeLegacy", &prim_other_flags, ImDrawFlags_UseTexForStrokeLegacy); - static ImDrawFlags scope_flags = draw_list->Flags; // First init copy current state. + static ImDrawFlags scope_flags = draw_list->Flags & ImDrawFlags_AllowInPushScope_; // First init copy current state. ImGui::SeparatorText("Current ImDrawList flags (e.g. PushDrawFlag function)"); ImGui::PushID("ScopeFlags"); ImGui::CheckboxFlags("AAFill", &scope_flags, ImDrawFlags_AAFill); ImGui::SameLine(); @@ -10465,7 +10465,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::PopID(); ImGui::Spacing(); - draw_list->PushDrawFlag(ImDrawFlags_AllowedInScope_, false); // Reset all existing (very unusual: done for this demo) + draw_list->PushDrawFlag(ImDrawFlags_AllowInPushScope_, false); // Reset all existing (very unusual: done for this demo) draw_list->PushDrawFlag(scope_flags, true); const ImDrawFlags flags = prim_stroke_flags | prim_other_flags; const ImDrawFlags fill_flags = flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 06838cdd3..77ce95140 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -462,7 +462,7 @@ void ImDrawList::_ResetForNewFrame() IdxBuffer.resize(0); VtxBuffer.resize(0); Flags = _Data->InitialDrawFlags; - IM_ASSERT((Flags & ~ImDrawFlags_AllowedInScope_) == 0); + IM_ASSERT((Flags & ~ImDrawFlags_AllowInFrameScope_) == 0); memset(&_CmdHeader, 0, sizeof(_CmdHeader)); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; @@ -716,7 +716,7 @@ void ImDrawList::PopTexture() // IMPORTANT: currently limited to 3 deep void ImDrawList::PushDrawFlag(ImDrawFlags flags, bool enabled) { - IM_ASSERT((flags & ~ImDrawFlags_AllowedInScope_) == 0); + IM_ASSERT((flags & ~ImDrawFlags_AllowInPushScope_) == 0); IM_ASSERT((flags & ImDrawFlags_StrokeMask_) == 0 || (flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy); _DrawFlagsStack.push_back(Flags); if (enabled) @@ -2423,7 +2423,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (flags & (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners); + const bool allow_tex_corners = (flags & (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_)) == (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_); if (allow_tex_corners && s_thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { // Pixel aligned rect with round corners rendered using baked textures. @@ -2571,10 +2571,10 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c return; } // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners)) == (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); + const bool allow_tex_corners = (flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_)) == (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_); if (allow_tex_corners && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) { - IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); + IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); // This is matching the baking calculations. The rounding clamping above makes sure that there's enough space for the extra pixel. const int size = s_rounding + 1; const int idx = (s_rounding - 1); From deb9c70acec3b1d06b9606ea64a2e1bba214e679 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jul 2026 15:02:53 +0200 Subject: [PATCH 137/245] DrawList: ImDrawFlags_AALineEnds also requires ImDrawFlags_AALine, which makes it easier for widgets to opt-in AAEnds. --- imgui.h | 2 +- imgui_demo.cpp | 3 ++- imgui_draw.cpp | 12 +++++++----- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 3eef737d2..de6fec28a 100644 --- a/imgui.h +++ b/imgui.h @@ -3343,7 +3343,7 @@ enum ImDrawFlags_ // Stroke/Fill Anti-aliasing ------------------ // Prim/Scope? ImDrawFlags_AAFill = 1 << 12, // OK* OK(1) // Enable anti-aliasing for Filled shapes. ImDrawFlags_AALines = 1 << 13, // OK* OK(1) // Enable anti-aliasing for Strokes (lines, borders). - ImDrawFlags_AALineEnds = 1 << 14, // OK OK(0) // Enable anti-aliasing for Strokes Ends. Useful on thick strokes or for precise continuity of multiple lines. A little more costly. + ImDrawFlags_AALineEnds = 1 << 14, // OK OK(0) // Enable anti-aliasing for Strokes Ends. Requires AALines to also be enabled. Useful on thick strokes or for precise continuity of multiple lines. A little more costly. //ImDrawFlags_NoAA = 1 << 15, // OK -- // Disable anti-aliasing for a given primitive. //ImDrawFlags_NoAALineEnds = 1 << 16, // OK -- // Disable anti-aliasing ends for a given primitive. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 041cee6b4..efd35bb0a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8911,8 +8911,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) Checkbox("Anti-aliased lines", &style.AntiAliasedLines); SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); - + BeginDisabled(style.AntiAliasedLines == false); Checkbox("Anti-aliased line ends", &style.AntiAliasedLineEnds); + EndDisabled(); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS BeginDisabled(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 77ce95140..b1cad1505 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1045,6 +1045,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; + const bool use_aa_ends = (flags & (ImDrawFlags_AALines | ImDrawFlags_AALineEnds)) == (ImDrawFlags_AALines | ImDrawFlags_AALineEnds); const int first_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); int base_idx = (int)_VtxCurrentIdx; @@ -1073,7 +1074,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 p1.y -= dir.y * half_thickness; } - if ((flags & ImDrawFlags_AALineEnds) == 0) + if (!use_aa_ends) { base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); @@ -1259,7 +1260,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 p1.y += dir.y * half_thickness; } - if ((flags & ImDrawFlags_AALineEnds) == 0) + if (!use_aa_ends) { IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); @@ -1889,8 +1890,9 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; + const bool use_aa_ends = (flags & (ImDrawFlags_AALines | ImDrawFlags_AALineEnds)) == (ImDrawFlags_AALines | ImDrawFlags_AALineEnds); - if ((flags & ImDrawFlags_AALineEnds) == 0) + if (!use_aa_ends) PrimReserve(2*3, 4); else PrimReserve(6*3, 8); @@ -1910,7 +1912,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t } // Start cap - if ((flags & ImDrawFlags_AALineEnds) == 0) + if (!use_aa_ends) { base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1_x - norm_x * thickness0, p1_y - norm_y * thickness0, uv0, col); @@ -7622,7 +7624,7 @@ void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float draw_list->PathLineTo(ImVec2(bx - third, by - third)); draw_list->PathLineTo(ImVec2(bx, by)); draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f)); - draw_list->PathStroke(col, thickness, (draw_list->Flags & ImDrawFlags_AALines) ? ImDrawFlags_AALineEnds : 0); // FIXME: Design idiomatic selection/threshold for this? + draw_list->PathStroke(col, thickness, ImDrawFlags_AALineEnds); } // Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. From 059017188d145988441b4859c4d26f121daa8851 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jul 2026 17:56:04 +0200 Subject: [PATCH 138/245] DrawList: baking half-texel in TexUvLines[] now that AddPolylineLegacy() was removed. --- imgui_draw.cpp | 31 ++++++++++++------------------- imgui_internal.h | 2 +- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b1cad1505..05b94231f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1033,12 +1033,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } PrimReserve(idx_count, vtx_count); - const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; const float ratio = thickness0 / (thickness0 + thickness1); // The points that use uv2 are placed directly on the path (offset = 0), calculate the texture position from stroke offsets. ImVec2 uv0, uv1, uv2; - uv0.x = tex_uvs.x + half_texel; + uv0.x = tex_uvs.x; uv0.y = tex_uvs.z; - uv1.x = tex_uvs.y - half_texel; + uv1.x = tex_uvs.y; uv1.y = tex_uvs.z; uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; uv2.y = tex_uvs.z; @@ -1877,13 +1876,11 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t thickness0 = fringe * 0.5f; float thickness1 = (thickness + fringe) - thickness0; - - const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. ImVec2 uv0, uv1, uv2; - uv0.x = tex_uvs.x + half_texel; + uv0.x = tex_uvs.x; uv0.y = tex_uvs.z; - uv1.x = tex_uvs.y - half_texel; + uv1.x = tex_uvs.y; uv1.y = tex_uvs.z; uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; uv2.y = tex_uvs.z; @@ -2244,12 +2241,11 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, rounding += half_fringe; const float stem_offset = ImMin(rounding, thickness); // The function might get called with rounding slightly bigger than thickness, which is ok, but we should keep the stem inside the shape. - const float half_texel = 0.5f * _Data->FontAtlas->TexUvScale.x; const float ratio = stem_offset / thickness; ImVec2 inner_uv, outer_uv, stem_uv; - outer_uv.x = tex_uvs.x + half_texel; + outer_uv.x = tex_uvs.x; outer_uv.y = tex_uvs.z; - inner_uv.x = tex_uvs.y - half_texel; + inner_uv.x = tex_uvs.y; inner_uv.y = tex_uvs.z; stem_uv.x = outer_uv.x + (inner_uv.x - outer_uv.x) * ratio; stem_uv.y = tex_uvs.z; @@ -2434,8 +2430,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl const int idx = (s_thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + s_rounding - 1; IM_ASSERT_PARANOID((_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners) == 0); IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); - const ImVec4 tex_uvs = _Data->TexUvCorners[idx]; - _AddRectBaked(outer_min, outer_max, col, (float)size * _FringeScale, (float)thickness, tex_uvs, flags); + _AddRectBaked(outer_min, outer_max, col, (float)size * _FringeScale, (float)thickness, _Data->TexUvCorners[idx], flags); return; } } @@ -2581,8 +2576,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c const int size = s_rounding + 1; const int idx = (s_rounding - 1); IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); - ImVec4 tex_uvs = _Data->TexUvCorners[idx]; - _AddRectFilledBaked(p_min, p_max, col, (float)size * _FringeScale, tex_uvs, flags); + _AddRectFilledBaked(p_min, p_max, col, (float)size * _FringeScale, _Data->TexUvCorners[idx], flags); return; } } @@ -5103,8 +5097,8 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) } // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; + ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 0.5f), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 0.5f), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts // Store inverse of the line-width (thickness) to the w component so that we can avoid division when selecting texture. float inv_line_width = (line_width > 0) ? (1.0f / (float)line_width) : 0.0f; @@ -5113,7 +5107,6 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) } { - ImU8 ramp[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]; for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; n++) ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.0f); @@ -5172,8 +5165,8 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) } // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r.x + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; + ImVec2 uv0 = ImVec2((float)(r.x + 0.5f), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x - 0.5f + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts // Store inverse of the line-width (thickness) to the w component so that we can avoid division when selecting texture. float inv_line_width = 1.0f / (1.0f + (float)n / (float)IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT); diff --git a/imgui_internal.h b/imgui_internal.h index 2a246cd7f..9024a6c90 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -4087,7 +4087,7 @@ struct ImFontAtlasBuilder ImFontAtlasRectId PackIdCornersTexData; // Cached UV coordinates - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines (u0, u1, v, 1/thickness) ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } From a547deed9b015b2fa96dac48955d6b39bbf2ccb9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 30 Jul 2026 18:12:53 +0200 Subject: [PATCH 139/245] DrawList: fixed AddRectFilled() path for minimum dimension. --- imgui_draw.cpp | 21 ++++----------------- 1 file changed, 4 insertions(+), 17 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 05b94231f..7513cecc3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1415,6 +1415,8 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun if (bevel) { // Limit inner bevel so that it is does not shoot out outside the polygon. + // (using ImMax is intentional: using min limited too much in Mikko's tests when you have short edge next to long one. + // The idea of that check is to keep that worst case overshoot no bigger than the polygon) const float ref_thickness_sqr = half_aa * half_aa; const float limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); const float ref_miter_dist_sqr = miter_distance_sqr * ref_thickness_sqr; @@ -2535,7 +2537,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c col = ImAlphaMultiply(col, height * _InvFringeScale); height = _FringeScale; } - const ImVec2 points[4] = { p_min, ImVec2(p_min.x + width, p_min.y), ImVec2(p_min.x + width, p_min.y + height), ImVec2(p_min.x, p_max.y + height) }; + const ImVec2 points[4] = { p_min, ImVec2(p_min.x + width, p_min.y), ImVec2(p_min.x + width, p_min.y + height), ImVec2(p_min.x, p_min.y + height) }; AddConvexPolyFilled(points, 4, col, ImDrawFlags_MiterOnly); return; } @@ -5058,9 +5060,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) } { - // Register texture region for thick lines - // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row - // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them + // FIXME: Lines 0 to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH(4) are currently never used and could be ditched, saving DETAILED_WIDTH*WIDTH_MAX for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle @@ -5076,10 +5076,8 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); for (int i = 0; i < pad_left; i++) *(write_ptr + i) = 0x00; - for (int i = 0; i < line_width; i++) *(write_ptr + pad_left + i) = 0xFF; - for (int i = 0; i < pad_right; i++) *(write_ptr + pad_left + line_width + i) = 0x00; } @@ -5088,10 +5086,8 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); for (int i = 0; i < pad_left; i++) *(write_ptr + i) = IM_COL32(255, 255, 255, 0); - for (int i = 0; i < line_width; i++) *(write_ptr + pad_left + i) = IM_COL32_WHITE; - for (int i = 0; i < pad_right; i++) *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); } @@ -5132,34 +5128,25 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) { ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); int idx = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; i++) write_ptr[idx++] = ramp[i]; - for (int i = 0; i < line_width; i++) write_ptr[idx++] = 0xFF; - for (int i = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT - 1; i >= 0; i--) write_ptr[idx++] = ramp[i]; - while (idx < r.w) write_ptr[idx++] = 0x0; } else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) { ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); - int idx = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; i++) write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); - for (int i = 0; i < line_width; i++) write_ptr[idx++] = IM_COL32(255, 255, 255, 255); - for (int i = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT - 1; i >= 0; i--) write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); - while (idx < r.w) write_ptr[idx++] = IM_COL32(255, 255, 255, 0); } From 640e9312845d4cdebdadb521a7a4aaf16da74be3 Mon Sep 17 00:00:00 2001 From: thedmd Date: Thu, 30 Jul 2026 21:25:37 +0200 Subject: [PATCH 140/245] DrawList: fixed passing large thickness value (e.g. 1e20f) to thickness crashing the code. --- imgui_draw.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7513cecc3..703c196ca 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -915,8 +915,10 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv int texture_idx; if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) IM_LIKELY texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f) + (IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + else if (screen_thickness < (float)IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1.5f) IM_LIKELY + texture_idx = (int)(screen_thickness + 0.5f); else - texture_idx = ImMin((int)(screen_thickness + 0.5f), IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1); + texture_idx = IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1; // Catches large values of screen_thickness (and +inf/NaN) that a ImMin() wouldn't. // Scale the fringe so that the texture matches the line thickness. ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; From 475660f53c4fb000aa1d90a5a33fedafcaf8abd0 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 31 Jul 2026 11:39:16 +0300 Subject: [PATCH 141/245] DrawList: fixed overdraw issue for filled baked corner rendering. Require all corners to fit inside the rect to avoid overdraw (or fallback to path rendering). eg. AddRectFilled() w/ size=10, rounding=8 or 10 would break. --- imgui_draw.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 703c196ca..bf4ff1a82 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2577,11 +2577,15 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c { IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); // This is matching the baking calculations. The rounding clamping above makes sure that there's enough space for the extra pixel. - const int size = s_rounding + 1; - const int idx = (s_rounding - 1); - IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); - _AddRectFilledBaked(p_min, p_max, col, (float)size * _FringeScale, _Data->TexUvCorners[idx], flags); - return; + const int corner_size = s_rounding + 1; + // Check that the baked corners do not overlap (this could be made more accurate if tested for x and y separately). + if ((float)corner_size * 2.0f * _FringeScale < min_dim) + { + const int idx = (s_rounding - 1); + IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); + _AddRectFilledBaked(p_min, p_max, col, (float)corner_size * _FringeScale, _Data->TexUvCorners[idx], flags); + return; + } } } From 91dc4f456a63812a6b64fd158b10f056a3ec1b8d Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 31 Jul 2026 11:45:41 +0300 Subject: [PATCH 142/245] DrawList: fixed rendering issues on small and degenerate shapes. The "does stroke cover the whole shape" used to be overly pessimistic to stroking artifacts. This was due to the fringe, where the geometry would mess up before visually closing the shape. Fixed the issue by adding max inner offest for the AddPolyline(), which limits the inner offset and also adjusts the texture coords. Second part of the fix was to calculate the pass the max inner offset from the common shapes (circle, ngon, ellipse, rect). While this does not fix all the ellipse rendering issues, it limits the issue a lot. e.g. AddRect() w/ size=5, thickness=2 used to trigger AddRectFilled() fallback because threshold was pessimistic to prevent the AddPolyline() issues. --- imgui.h | 5 ++-- imgui_draw.cpp | 76 +++++++++++++++++++++++++++++++++++++------------- 2 files changed, 60 insertions(+), 21 deletions(-) diff --git a/imgui.h b/imgui.h index de6fec28a..1e0246ece 100644 --- a/imgui.h +++ b/imgui.h @@ -3452,7 +3452,7 @@ struct ImDrawList // General polygon // - Only simple polygons are supported by filling functions (no self-intersections, no holes). // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. - IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); + inline void AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0) { _AddPolyline(points, num_points, col, thickness, flags, FLT_MAX); } IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags = 0); IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); @@ -3472,7 +3472,7 @@ struct ImDrawList inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } inline void PathFillConvex(ImU32 col, ImDrawFlags flags = 0) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, flags); _Path.Size = 0; } inline void PathFillConcave(ImU32 col) { AddConcavePolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } - inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0) { AddPolyline(_Path.Data, _Path.Size, col, thickness, flags); _Path.Size = 0; } + inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0) { _AddPolyline(_Path.Data, _Path.Size, col, thickness, flags, FLT_MAX); _Path.Size = 0; } IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments = 0); // Ellipse @@ -3556,6 +3556,7 @@ struct ImDrawList IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe, ImDrawFlags flags); IMGUI_API float _CalculateCenterBiasedOffset(float thickness); + IMGUI_API void _AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags, float max_inner_thickness); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bf4ff1a82..6fd56bb04 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -942,7 +942,7 @@ static inline ImDrawFlags _GetStrokePos(ImDrawFlags flags, ImDrawFlags default_s IM_MSVC_RUNTIME_CHECKS_RESTORE -void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, float max_inner_offset) { if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) return; @@ -1044,6 +1044,16 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; uv2.y = tex_uvs.z; + // Clamp inner offset and adjust texture coordinates to match the change. + // This is used by some of the convex shape rendering to avoid rendering artifacts when thickness is about to fill the whole shape. + if (thickness1 > max_inner_offset) + { + thickness1 = max_inner_offset; + const float s = (thickness0 + thickness1) / (thickness + fringe); + const float du = uv1.x - uv0.x; + uv1.x = uv0.x + du * s; + } + const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; const bool use_aa_ends = (flags & (ImDrawFlags_AALines | ImDrawFlags_AALineEnds)) == (ImDrawFlags_AALines | ImDrawFlags_AALineEnds); @@ -2369,7 +2379,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl const float width = outer_max.x - outer_min.x; const float height = outer_max.y - outer_min.y; - if (ImMin(width, height) < (thickness + _FringeScale) * 2.0f) IM_UNLIKELY + const float half_min_dim = ImMin(width, height) * 0.5f; + if (half_min_dim <= thickness) IM_UNLIKELY { // Rectangle has collapsed into filled rectangle. AddRectFilled(outer_min, outer_max, col, outer_rounding, flags); @@ -2442,7 +2453,8 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { const ImVec2 points[4] = { outer_min, ImVec2(outer_max.x, outer_min.y), outer_max, ImVec2(outer_min.x, outer_max.y) }; - AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_)); + _AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside, half_min_dim); + _Path.Size = 0; } else { @@ -2462,7 +2474,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathArcToFast(ImVec2(outer_max.x - rounding_tr, outer_min.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(outer_max.x - rounding_br, outer_max.y - rounding_br), rounding_br, 0, 3); PathArcToFast(ImVec2(outer_min.x + rounding_bl, outer_max.y - rounding_bl), rounding_bl, 3, 6); - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_)); + + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_), half_min_dim); + _Path.Size = 0; } } @@ -2628,7 +2642,7 @@ void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, c flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // As AddPolyline() default is different const ImVec2 points[4] = { p1, p2, p3, p4 }; - AddPolyline(points, 4, col, thickness, flags | ImDrawFlags_Closed); + _AddPolyline(points, 4, col, thickness, flags | ImDrawFlags_Closed, FLT_MAX); } void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col) @@ -2650,7 +2664,7 @@ void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // As AddPolyline() default is different const ImVec2 points[3] = { p1, p2, p3 }; - AddPolyline(points, 3, col, thickness, flags | ImDrawFlags_Closed); + _AddPolyline(points, 3, col, thickness, flags | ImDrawFlags_Closed, FLT_MAX); } void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col) @@ -2662,6 +2676,14 @@ void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImV AddConvexPolyFilled(points, 3, col); } +static float ApproxApothem(int num_segments) +{ + // Calculates approximation (within 0.001%) distance from the center of the circumscribed circle to the edge of the polygon, cos(pi / n) + IM_ASSERT_PARANOID(num_segments >= 3); + const float u = 1.0f / num_segments; + return ((4.058712f * u * u) - 4.934802f) * u * u + 1.0f; +} + void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) @@ -2685,7 +2707,8 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) outer_radius = radius + thickness; - if (outer_radius < (thickness + _FringeScale)) IM_UNLIKELY + + if (outer_radius <= thickness) IM_UNLIKELY { // The circle has collapsed into a filled circle. AddCircleFilled(center, outer_radius, col, num_segments); @@ -2709,7 +2732,15 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); } - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos); + if (_Path.Size < 3) + return; + + // Calculate distance to the edge of the polygon describing the circle. + // This will be used by _AddPolyline() to clamp the inner stroke expansion, to avoid creating rendering artifacts. + const float unit_apothem = ApproxApothem(_Path.Size); + const float edge_dist = radius * unit_apothem; + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos, edge_dist); + _Path.Size = 0; } void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) @@ -2760,22 +2791,24 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ } radius = ImMax(0.01f, radius); - // Check overestimate first before testing details (+1.0f is intended, not FringeScale) - if (radius < (thickness * 2.0f + 1.0f)) - { - const float unit_apothem = ImCos(IM_PI / (float)num_segments); - const float miter_thickness = thickness / unit_apothem; + // Calculate distance to the edge of the polygon describing the circle. + // This will be used by _AddPolyline() to clamp the inner stroke expansion, to avoid creating rendering artifacts. + const float unit_apothem = ApproxApothem(num_segments); + const float edge_dist = radius * unit_apothem; + // Check overestimate first before testing details. + if (radius < thickness * 2.0f) + { float outer_radius = radius; if (stroke_pos == ImDrawFlags_StrokeCenter) - outer_radius = radius + miter_thickness * 0.5f; + outer_radius = radius + thickness * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - outer_radius = radius + _CalculateCenterBiasedOffset(miter_thickness); + outer_radius = radius + _CalculateCenterBiasedOffset(thickness); else if (stroke_pos == ImDrawFlags_StrokeInside) outer_radius = radius; else if (stroke_pos == ImDrawFlags_StrokeOutside) - outer_radius = radius + miter_thickness; - if (outer_radius < (miter_thickness + _FringeScale)) IM_UNLIKELY + outer_radius = radius + thickness; + if (outer_radius * unit_apothem <= thickness) IM_UNLIKELY { // The polygon has collapsed into a filled polygon. AddNgonFilled(center, outer_radius, col, num_segments); @@ -2786,7 +2819,8 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos); + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos, edge_dist); + _Path.Size = 0; } // Guaranteed to honor 'num_segments' @@ -2832,7 +2866,11 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; PathEllipticalArcTo(center, rad, rot, 0.0f, a_max, num_segments - 1); - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos); + + // Prevent the inside part of the stroke to be expanded too much to prevent some rendering artifacts. + const float max_inner_offset = ImMin(rad.x, rad.y); + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos, max_inner_offset); + _Path.Size = 0; } void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments) From c6c352f77d2fc81c27cb9414ae05dfe4053957bc Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 31 Jul 2026 12:39:29 +0300 Subject: [PATCH 143/245] DrawList: fixed too many detailed line textures being created. Fixed issue where were creating detailed line textures up to detailed witdh + 1 Changed IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT which no accounts for all the detailed line textures. --- imgui_draw.cpp | 11 ++++++++--- imgui_internal.h | 6 +++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6fd56bb04..2f1ecea62 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -911,7 +911,7 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv { // Handle the thickness between 1.0 - IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. // We use super sampled textures in this range to make texture changes less noticeable. - // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX+1 textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). + // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT-1 maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). int texture_idx; if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) IM_LIKELY texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f) + (IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); @@ -5098,7 +5098,9 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false; if (add_and_draw) { - ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1); + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT); builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid); } @@ -5147,11 +5149,14 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) } { + // Calculate super sampled lin textures for smaller line widths to make transition between sizes smoother. + + // Calc ramp used for all the textures. ImU8 ramp[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]; for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; n++) ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.0f); - for (int n = 0; n < IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1; n++) + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT; n++) { const int y = IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n; // For integer thickness lines the one pixel line texture looks like this: diff --git a/imgui_internal.h b/imgui_internal.h index 9024a6c90..1f2e26268 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -938,7 +938,7 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag #ifndef IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX #define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (4) // 0: fill, 1-3: strokes thickness #endif -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX (IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) +#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT ((IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH - 1) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 1) // Data shared between all ImDrawList instances // Conceptually this could have been called e.g. ImDrawListSharedContext @@ -4087,8 +4087,8 @@ struct ImFontAtlasBuilder ImFontAtlasRectId PackIdCornersTexData; // Cached UV coordinates - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines (u0, u1, v, 1/thickness) - ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT]; // UVs for baked anti-aliased lines (u0, u1, v, 1/thickness) + ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } }; From 3dbb849acf074a1840b61cba3b9bc0f847218e26 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Fri, 31 Jul 2026 16:45:01 +0300 Subject: [PATCH 144/245] DrawList: fixed PathArcTo to not emit small segments. - Changed PathArcTo to select start/end sample in quatized multiples of arc fast sample count - This is done in order to avoid small segments at the start and end of the path, which causes issues with line AA ends - Renamed CalcArcStepAndCount to CalcCornerArcStepAndCount to make it more clear that it returns the values for 90 degree arc --- imgui_draw.cpp | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2f1ecea62..109336105 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1511,7 +1511,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun // Calculates arc step and step count for 90 degree arc. The calculated arc step will complete a 90 degree arc when stepped arc_step_count times. IM_MSVC_RUNTIME_CHECKS_OFF -static void CalcArcStepAndCount(int segment_count, int& arc_step, int& arc_step_count) +static void CalcCornerArcStepAndCount(int segment_count, int& arc_step, int& arc_step_count) { arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / segment_count, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); arc_step_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step; @@ -1534,7 +1534,7 @@ void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_ // Calculate step size using the common function. No need to clamp, the step is already in range. const int auto_seg_count = _CalcCircleAutoSegmentCount(radius); int arc_step_count; - CalcArcStepAndCount(auto_seg_count, a_step, arc_step_count); + CalcCornerArcStepAndCount(auto_seg_count, a_step, arc_step_count); } else { @@ -1664,16 +1664,25 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa // Automatic segment count if (radius <= _Data->ArcFastRadiusCutoff) - { + { const bool a_is_reverse = a_max < a_min; + // Calculate number of segments per circle. + // First we calculate the step count as usual, then match to the precomputed directions. + // This will give us the spacing between the samples (step), and how many segments to use in total for a full circle. + const int auto_seg_count = _CalcCircleAutoSegmentCount(radius); + int arc_step, arc_step_count; + CalcCornerArcStepAndCount(auto_seg_count, arc_step, arc_step_count); + const int arc_seg_count = arc_step_count * 4; // Seg count for full circle. + // We are going to use precomputed values for mid samples. // Determine first and last sample in lookup table that belong to the arc. - const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f); - const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f); + // In first step we use the coarser segment count, and after rounding, convert back to the precomputed array index. + const float a_min_sample_f = arc_seg_count * a_min / (IM_PI * 2.0f); + const float a_max_sample_f = arc_seg_count * a_max / (IM_PI * 2.0f); - const int a_min_sample = a_is_reverse ? (int)ImFloor(a_min_sample_f) : (int)ImCeil(a_min_sample_f); - const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloor(a_max_sample_f); + const int a_min_sample = (a_is_reverse ? (int)ImFloor(a_min_sample_f) : (int)ImCeil(a_min_sample_f)) * arc_step; + const int a_max_sample = (a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloor(a_max_sample_f)) * arc_step; const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0); const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX; @@ -1685,7 +1694,7 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa if (a_emit_start) _Path.push_back(ImVec2(center.x + ImCos(a_min) * radius, center.y + ImSin(a_min) * radius)); if (a_mid_samples > 0) - _PathArcToFastEx(center, radius, a_min_sample, a_max_sample, 0); + _PathArcToFastEx(center, radius, a_min_sample, a_max_sample, arc_step); if (a_emit_end) _Path.push_back(ImVec2(center.x + ImCos(a_max) * radius, center.y + ImSin(a_max) * radius)); } @@ -2231,7 +2240,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, const int auto_seg_count = _CalcCircleAutoSegmentCount(rounding); int arc_step, arc_step_count; - CalcArcStepAndCount(auto_seg_count, arc_step, arc_step_count); + CalcCornerArcStepAndCount(auto_seg_count, arc_step, arc_step_count); const int arc_point_count = arc_step_count + 1; int vtx_count = (2 + arc_point_count) * 4 + 3; @@ -4847,7 +4856,7 @@ static int InitCornerGeometry(float cx, float cy, float rounding, float circle_s const int auto_seg_count = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(rounding, circle_segment_max_error); int arc_step, arc_step_count; - CalcArcStepAndCount(auto_seg_count, arc_step, arc_step_count); + CalcCornerArcStepAndCount(auto_seg_count, arc_step, arc_step_count); const int arc_point_count = arc_step_count + 1; // Build arc of points, with straight segments at each end. From 230cd6feb0ac32a27b8e2119a7ddaadc95197033 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jul 2026 17:52:34 +0200 Subject: [PATCH 145/245] DrawList: simplify ImFontAtlasBuildUpdateTexDataCorners() by merging fill/strokes loops. --- imgui_draw.cpp | 128 +++++++++++++------------------------------------ 1 file changed, 34 insertions(+), 94 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 109336105..0b0e5c648 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4910,20 +4910,22 @@ static float SampleConvex(float x, float y, const ImVec2* line_normals, const fl return result; } -static ImU8 SampleCorner(float x, float y, const ImVec2* line_normals, const float* line_distances, int num_lines) +static ImU8 SampleCornerFillOrStroke(float x, float y, float thickness, const ImVec2* line_normals, const float* line_distances, int num_lines) { const float d = SampleConvex(x, y, line_normals, line_distances, num_lines); const float aa_width = 1.0f; - return (ImU8)(ImClamp(1.0f - (d + aa_width * 0.5f) / aa_width, 0.0f, 1.0f) * 255.0f); -} - -static ImU8 SampleCornerStroke(float x, float y, float thickness, const ImVec2* line_normals, const float* line_distances, int num_lines) -{ - const float d = SampleConvex(x, y, line_normals, line_distances, num_lines); - const float aa_width = 1.0f; - const float outer = 1.0f - (d + aa_width * 0.5f) / aa_width; - const float inner = (d + thickness + aa_width * 0.5f) / aa_width; - return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.0f); + if (thickness == 0.0f) + { + // Fill + return (ImU8)(ImClamp(1.0f - (d + aa_width * 0.5f) / aa_width, 0.0f, 1.0f) * 255.0f); + } + else + { + // Stroke + const float outer = 1.0f - (d + aa_width * 0.5f) / aa_width; + const float inner = (d + thickness + aa_width * 0.5f) / aa_width; + return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.0f); + } } #if 0 // Set to 1 to visualize coverage of textured corners @@ -4948,30 +4950,21 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // if (atlas->OwnerContext) // circle_segment_max_error = atlas->OwnerContext->DrawListSharedData.CircleSegmentMaxError; + // Calculate size and pack ImFontAtlasRect r; bool add_and_draw = atlas->GetCustomRect(builder->PackIdCornersTexData, &r) == false; if (add_and_draw) { + // (thickness 0 for filled, thickness >0 for strokes) ImVec2i pack_size(0, 0); - // Filled corners - int row_width = 0; - int row_height = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) + for (int thickness = 0; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) { - const int size = ImMax(2, i+1) + 2; - row_width += size; - row_height = ImMax(row_height, size); - } - pack_size.x = ImMax(pack_size.x, row_width); - pack_size.y += row_height; - // Rounded corners - for (int thickness = 1; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) - { - row_width = 0; - row_height = 0; + const bool is_filled = (thickness == 0); + int row_width = 0; + int row_height = 0; for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) { - const int size = ImMax(i + 2, thickness) + 2; + const int size = is_filled ? ImMax(i + 1, 2) + 2 : ImMax(i + 2, thickness) + 2; row_width += size; row_height = ImMax(row_height, size); } @@ -4982,80 +4975,27 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) IM_ASSERT(builder->PackIdCornersTexData != ImFontAtlasRectId_Invalid); } - int x = r.x; + // Render int y = r.y; - int row_height = 0; - ImVec2 line_normals[IM_DRAWLIST_CORNER_POINTS_MAX]; float line_distances[IM_DRAWLIST_CORNER_POINTS_MAX]; - - // Filled - for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) + for (int thickness = 0; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) { - const int rounding = n + 1; - const int s = rounding + 1; // Always add 1px to the fill side of the rounded corner to prevent the corner AA to bleed into the rectangle edges. - const int w = s + 2; - const int h = s + 2; - - // Corner circle - const float cx = 1.0f + (float)(n+1); - const float cy = 1.0f + (float)(n+1); - IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds before we start writing pixels - - const int num_lines = InitCornerGeometry(cx, cy, (float)rounding, circle_segment_max_error, line_normals, line_distances); - - // Write each slice - if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) - { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(x, y); - const int pitch = tex->Width; - for (int ly = 0; ly < h; ly++) - { - for (int lx = 0; lx < w; lx++) - write_ptr[lx] = SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines) & DEBUG_TEX_CORNER_U8(lx, h); - write_ptr += pitch; - } - } - else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) - { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(x, y); - const int pitch = tex->Width; - for (int ly = 0; ly < h; ly++) - { - for (int lx = 0; lx < w; lx++) - write_ptr[lx] = IM_COL32(255, 255, 255, SampleCorner((float)lx + 0.5f, (float)ly + 0.5f, line_normals, line_distances, num_lines)) & DEBUG_TEX_CORNER_U32(lx, h); - write_ptr += pitch; - } - } - - // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; - builder->TexUvCorners[n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); - - x += w; - row_height = ImMax(row_height, h); - } - y += row_height; - - // Stroked - for (int thickness = 1; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) - { - x = r.x; - row_height = 0; + const bool is_filled = (thickness == 0); + int x = r.x; + int row_height = 0; for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) { - const int rounding = n+1; - const int s = ImMax(rounding, thickness); + // Filled: Always add 1px to the fill side of the rounded corner to prevent the corner AA to bleed into the rectangle edges. + const int rounding = n + 1; + const int s = is_filled ? (rounding + 1) : ImMax(rounding, thickness); const int w = s + 2; const int h = s + 2; // Corner circle const float cx = 1.0f + (float)(n + 1); const float cy = 1.0f + (float)(n + 1); - - IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds before we start writing pixels - + IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds const int num_lines = InitCornerGeometry(cx, cy, (float)rounding, circle_segment_max_error, line_normals, line_distances); // Write each slice @@ -5065,8 +5005,8 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) const int pitch = tex->Width; for (int ly = 0; ly < h; ly++) { - for (int lx = 0; lx < h; lx++) - write_ptr[lx] = SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines) & DEBUG_TEX_CORNER_U8(lx, h); + for (int lx = 0; lx < w; lx++) + write_ptr[lx] = SampleCornerFillOrStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines) & DEBUG_TEX_CORNER_U8(lx, h); write_ptr += pitch; } } @@ -5076,8 +5016,8 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) const int pitch = tex->Width; for (int ly = 0; ly < h; ly++) { - for (int lx = 0; lx < h; lx++) - write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines)) & DEBUG_TEX_CORNER_U32(lx, h); + for (int lx = 0; lx < w; lx++) + write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerFillOrStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines)) & DEBUG_TEX_CORNER_U32(lx, h); write_ptr += pitch; } } @@ -5085,7 +5025,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; - builder->TexUvCorners[thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX + n] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + builder->TexUvCorners[n + thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); x += w; row_height = ImMax(row_height, h); From 451e107b3fa30b65c609a4f06ce149fb895dd370 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jul 2026 21:36:28 +0200 Subject: [PATCH 146/245] DrawList: removed ImDrawFlags_UseTexForStrokeLegacy as it doesn't have any use now that legacy code is out of the way. --- imgui.cpp | 5 ----- imgui.h | 10 ++++------ 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fa5dfe7e4..9735c8320 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -398,7 +398,6 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: 2026/10/07 (1.93.0) - merged ImDrawListFlags into ImDrawFlags. obsoleted ImDrawListFlags (which were rarely used directly): - ImDrawListFlags_AntiAliasedLines -> ImDrawFlags_AALines, - ImDrawListFlags_AntiAliasedFill -> ImDrawFlags_AAFill, - - ImDrawListFlags_AntiAliasedLinesUseTex -> ImDrawFlags_UseTexForStrokeLegacy - ImDrawListFlags_AllowVtxOffset -> ImDrawFlags_UseVtxOffset, - ImDrawListFlags_TextNoPixelSnap -> ImDrawFlags_TextNoPixelSnap, unifying them allows easily using them for both per-primitives alterations and scope alterations. @@ -5634,10 +5633,6 @@ static void SetupDrawListSharedData() g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALines; if (g.Style.AntiAliasedLineEnds) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALineEnds; -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines)) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForStrokeLegacy; -#endif if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) diff --git a/imgui.h b/imgui.h index 1e0246ece..2cc63c679 100644 --- a/imgui.h +++ b/imgui.h @@ -3360,13 +3360,12 @@ enum ImDrawFlags_ // Other Options ------------------------------ // Prim/Scope? ImDrawFlags_TextNoPixelSnap = 1 << 20, // OK OK(0) // Disable automatically snapping AddText() calls to pixel boundaries. ImDrawFlags_UseTexForRoundCorners = 1 << 21, // -- OK(1) // Enable using textures instead of strokes to draw rounded corners/circles where possible (faster). Used by default unless 'ImFontAtlasFlags_NoBakedRoundCorners' is enabled in the font atlas. - ImDrawFlags_UseTexForStrokeLegacy = 1 << 22, // -- OK(1) // Enable anti-aliased lines/borders using textures when using legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). Used by default unless 'ImFontAtlasFlags_NoBakedLines' is set in the font atlas. - ImDrawFlags_UseVtxOffset = 1 << 23, // -- OK(1) // Can emit 'VtxOffset > 0' to allow large meshes with 16-bit ImDrawIdx. Used by default when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled by the backend. - ImDrawFlags_AllowTexForRoundCorners_= 1 << 24, // -- OK(1) // [Internal] + ImDrawFlags_UseVtxOffset = 1 << 22, // -- OK(1) // Can emit 'VtxOffset > 0' to allow large meshes with 16-bit ImDrawIdx. Used by default when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled by the backend. + ImDrawFlags_AllowTexForRoundCorners_= 1 << 23, // -- OK(1) // [Internal] // [Internal] ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, // [Internal] - ImDrawFlags_AllowInPushScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseTexForStrokeLegacy | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundCornersMask_, // [Internal] Values allowed in PushDrawFlag() scope. + ImDrawFlags_AllowInPushScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundCornersMask_, // [Internal] Values allowed in PushDrawFlag() scope. ImDrawFlags_AllowInFrameScope_ = ImDrawFlags_AllowInPushScope_ | ImDrawFlags_AllowTexForRoundCorners_, ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. @@ -4295,7 +4294,6 @@ namespace ImGui #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) // OBSOLETED in 1.92.8: Use ImGui::GetPlatformIO().DrawCallback_ResetRenderState - // -- RENAMED in 1.93.0: Merged ImDrawListFlags into ImDrawFlags. typedef ImDrawFlags ImDrawListFlags; enum ImDrawListFlags_ @@ -4303,7 +4301,7 @@ enum ImDrawListFlags_ ImDrawListFlags_None = ImDrawFlags_None, ImDrawListFlags_AntiAliasedFill = ImDrawFlags_AAFill, ImDrawListFlags_AntiAliasedLines = ImDrawFlags_AALines, - ImDrawListFlags_AntiAliasedLinesUseTex = ImDrawFlags_UseTexForStrokeLegacy,// Only apply to StrokeLegacy mode! + ImDrawListFlags_AntiAliasedLinesUseTex = 0, // Only apply to StrokeLegacy mode! ImDrawListFlags_AllowVtxOffset = ImDrawFlags_UseVtxOffset, ImDrawListFlags_TextNoPixelSnap = ImDrawFlags_TextNoPixelSnap, }; From dee0e34504cdc1c42f875fca53835f10cec43043 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jul 2026 21:47:46 +0200 Subject: [PATCH 147/245] DrawList: amend PushDrawFlag() to report reaching capacity. --- imgui.h | 1 + imgui_draw.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/imgui.h b/imgui.h index 2cc63c679..aa0d0f079 100644 --- a/imgui.h +++ b/imgui.h @@ -2896,6 +2896,7 @@ struct ImSmallStack_ inline T& back() { IM_ASSERT(Size > 0); return LocalData[Size - 1]; } inline void push_back(const T& v) { IM_ASSERT(Size < Capacity); memcpy(&LocalData[Size], &v, sizeof(v)); Size++; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + inline int capacity() const { return Capacity; } }; // Flags for ImGuiListClipper (currently not fully exposed in function calls: a future refactor will likely add this to ImGuiListClipper::Begin function equivalent) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0b0e5c648..1882eb160 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -718,6 +718,7 @@ void ImDrawList::PushDrawFlag(ImDrawFlags flags, bool enabled) { IM_ASSERT((flags & ~ImDrawFlags_AllowInPushScope_) == 0); IM_ASSERT((flags & ImDrawFlags_StrokeMask_) == 0 || (flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy); + IM_ASSERT_USER_ERROR_RET(_DrawFlagsStack.Size < _DrawFlagsStack.capacity(), "PushDrawFlag() has a depth limit. Contact us."); _DrawFlagsStack.push_back(Flags); if (enabled) Flags |= flags; From 7415edbad103f47d4537be3ead7c6cdd78cfb217 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jul 2026 21:49:55 +0200 Subject: [PATCH 148/245] DrawList: fixed ImFontAtlasBuildUpdateTexDataCorners() packing vs render to match. --- imgui_draw.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1882eb160..8b409f1dd 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4963,11 +4963,12 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) const bool is_filled = (thickness == 0); int row_width = 0; int row_height = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; i++) + for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) { - const int size = is_filled ? ImMax(i + 1, 2) + 2 : ImMax(i + 2, thickness) + 2; - row_width += size; - row_height = ImMax(row_height, size); + const int rounding = n + 1; + const int size = (is_filled ? (rounding + 1) : ImMax(rounding, thickness)); + row_width += size + 2; + row_height = ImMax(row_height, size + 2); } pack_size.x = ImMax(pack_size.x, row_width); pack_size.y += row_height; @@ -4989,9 +4990,9 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) { // Filled: Always add 1px to the fill side of the rounded corner to prevent the corner AA to bleed into the rectangle edges. const int rounding = n + 1; - const int s = is_filled ? (rounding + 1) : ImMax(rounding, thickness); - const int w = s + 2; - const int h = s + 2; + const int size = (is_filled ? (rounding + 1) : ImMax(rounding, thickness)); + const int w = size + 2; + const int h = size + 2; // Corner circle const float cx = 1.0f + (float)(n + 1); @@ -5025,7 +5026,7 @@ static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) // Refresh UV coordinates ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(x + 1 + s), (float)(y + 1 + s)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(x + 1 + size), (float)(y + 1 + size)) * atlas->TexUvScale; builder->TexUvCorners[n + thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); x += w; From c52f84c71914e6517336883bf3c6d436ac47d371 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 4 Aug 2026 15:33:54 +0200 Subject: [PATCH 149/245] DrawList: rework _SelectFringeTexture() for use by third-party extensions + rename to _SelectLineTexture(). --- imgui.h | 2 +- imgui_draw.cpp | 45 ++++++++++++++------------------------------- 2 files changed, 15 insertions(+), 32 deletions(-) diff --git a/imgui.h b/imgui.h index aa0d0f079..eafe71d32 100644 --- a/imgui.h +++ b/imgui.h @@ -3554,7 +3554,7 @@ struct ImDrawList IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags); IMGUI_API void _AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags); IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); - IMGUI_API void _SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe, ImDrawFlags flags); + IMGUI_API void _SelectLineTexture(float screen_thickness, ImVec2* out_uv0, ImVec2* out_uv1, float* out_fringe, ImDrawFlags flags); IMGUI_API float _CalculateCenterBiasedOffset(float thickness); IMGUI_API void _AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags, float max_inner_thickness); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8b409f1dd..8f53a8120 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -903,7 +903,7 @@ static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) } // Select texture and adjust fringe size for specified line thickness. -void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uvs, float* out_fringe, ImDrawFlags flags) +void ImDrawList::_SelectLineTexture(float screen_thickness, ImVec2* out_uv0, ImVec2* out_uv1, float* out_fringe, ImDrawFlags flags) { // We assume that the screen_thickness has been clamped to 1.0 by the caller. IM_ASSERT_PARANOID(screen_thickness >= 1.0f); @@ -923,13 +923,15 @@ void ImDrawList::_SelectFringeTexture(float screen_thickness, ImVec4* out_tex_uv // Scale the fringe so that the texture matches the line thickness. ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; - *out_tex_uvs = tex_uvs; + out_uv0->x = tex_uvs.x; + out_uv1->x = tex_uvs.y; + out_uv0->y = out_uv1->y = tex_uvs.z; *out_fringe = _FringeScale * screen_thickness * tex_uvs.w; // tex_uvs.w = 1 / thickness } else { // For no anti-alias we use fully opaque texture, and no fringe expansion. - *out_tex_uvs = ImVec4(_Data->TexUvWhitePixel.x, _Data->TexUvWhitePixel.x, _Data->TexUvWhitePixel.y, 0.0f); // u0, u1, v, 1/thickness (unused) + *out_uv0 = *out_uv1 = _Data->TexUvWhitePixel; *out_fringe = 0.0f; } } @@ -997,9 +999,9 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 sqr_lengths[points_count - 1] = 0.0f; } - ImVec4 tex_uvs; + ImVec2 uv0, uv1; float fringe; - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe, flags); + _SelectLineTexture(screen_thickness, &uv0, &uv1, &fringe, flags); const ImU32 col_trans = col & ~IM_COL32_A_MASK; @@ -1037,13 +1039,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 PrimReserve(idx_count, vtx_count); const float ratio = thickness0 / (thickness0 + thickness1); // The points that use uv2 are placed directly on the path (offset = 0), calculate the texture position from stroke offsets. - ImVec2 uv0, uv1, uv2; - uv0.x = tex_uvs.x; - uv0.y = tex_uvs.z; - uv1.x = tex_uvs.y; - uv1.y = tex_uvs.z; - uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; - uv2.y = tex_uvs.z; + const ImVec2 uv2(uv0.x + (uv1.x - uv0.x) * ratio, uv0.y); // Clamp inner offset and adjust texture coordinates to match the change. // This is used by some of the convex shape rendering to avoid rendering artifacts when thickness is about to fill the whole shape. @@ -1872,9 +1868,9 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t } flags |= Flags; - ImVec4 tex_uvs; + ImVec2 uv0, uv1; float fringe; - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe, flags); + _SelectLineTexture(screen_thickness, &uv0, &uv1, &fringe, flags); float dir_x = p2.x - p1.x; float dir_y = p2.y - p1.y; @@ -1901,13 +1897,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t float thickness1 = (thickness + fringe) - thickness0; const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. - ImVec2 uv0, uv1, uv2; - uv0.x = tex_uvs.x; - uv0.y = tex_uvs.z; - uv1.x = tex_uvs.y; - uv1.y = tex_uvs.z; - uv2.x = uv0.x + (uv1.x - uv0.x) * ratio; - uv2.y = tex_uvs.z; + const ImVec2 uv2(uv0.x + (uv1.x - uv0.x) * ratio, uv0.y); const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. const float half_thickness = thickness * 0.5f; @@ -1988,7 +1978,6 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t // AA cap IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - } } @@ -2235,9 +2224,9 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, } flags |= Flags; - ImVec4 tex_uvs; + ImVec2 outer_uv, inner_uv; float fringe; - _SelectFringeTexture(screen_thickness, &tex_uvs, &fringe, flags); + _SelectLineTexture(screen_thickness, &outer_uv, &inner_uv, &fringe, flags); const int auto_seg_count = _CalcCircleAutoSegmentCount(rounding); int arc_step, arc_step_count; @@ -2266,13 +2255,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, const float stem_offset = ImMin(rounding, thickness); // The function might get called with rounding slightly bigger than thickness, which is ok, but we should keep the stem inside the shape. const float ratio = stem_offset / thickness; - ImVec2 inner_uv, outer_uv, stem_uv; - outer_uv.x = tex_uvs.x; - outer_uv.y = tex_uvs.z; - inner_uv.x = tex_uvs.y; - inner_uv.y = tex_uvs.z; - stem_uv.x = outer_uv.x + (inner_uv.x - outer_uv.x) * ratio; - stem_uv.y = tex_uvs.z; + const ImVec2 stem_uv(outer_uv.x + (inner_uv.x - outer_uv.x) * ratio, outer_uv.y); // Previous vertices, copied from the last vertices. int base_idx = (int)_VtxCurrentIdx; From 0e756a649d19996d6ca91d64e10a6aaf09f969a5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 6 Oct 2026 16:33:42 +0200 Subject: [PATCH 150/245] (Breaking) DrawList: renamed ImDrawFlags_RoundCornersXXX to ImDrawFlags_RoundXXX. (#9504) --- docs/CHANGELOG.txt | 13 +++++ imgui.cpp | 14 ++++-- imgui.h | 63 +++++++++++++++--------- imgui_demo.cpp | 2 +- imgui_draw.cpp | 120 ++++++++++++++++++++++----------------------- imgui_widgets.cpp | 12 ++--- 6 files changed, 130 insertions(+), 94 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 00f31e1de..83e95c2ff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -189,6 +189,19 @@ HOW TO UPDATE? Breaking Changes: +- DrawList: + - Renamed all `ImDrawFlags_RoundCornersXXX` flags to `ImDrawFlags_RoundXXX`. + - `ImDrawFlags_RoundCornersNone` -> `ImDrawFlags_RoundNone` + - `ImDrawFlags_RoundCornersAll` -> `ImDrawFlags_RoundAll` + - `ImDrawFlags_RoundCornersTopLeft` -> `ImDrawFlags_RoundTopLeft` + - `ImDrawFlags_RoundCornersTopRight` -> `ImDrawFlags_RoundTopRight` + - `ImDrawFlags_RoundCornersBottomLeft` -> `ImDrawFlags_RoundBottomLeft` + - `ImDrawFlags_RoundCornersBottomRight` -> `ImDrawFlags_RoundBottomRight` + - `ImDrawFlags_RoundCornersTop` -> `ImDrawFlags_RoundTop` + - `ImDrawFlags_RoundCornersBottom` -> `ImDrawFlags_RoundBottom` + - `ImDrawFlags_RoundCornersLeft` -> `ImDrawFlags_RoundLeft` + - `ImDrawFlags_RoundCornersRight` -> `ImDrawFlags_RoundRight` + Kept redirection enums (will obsolete). - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. It is easier to tweak + this allows us to easily scale error threshold on high density screens. diff --git a/imgui.cpp b/imgui.cpp index 9735c8320..e51cde0e3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -401,6 +401,14 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ImDrawListFlags_AllowVtxOffset -> ImDrawFlags_UseVtxOffset, - ImDrawListFlags_TextNoPixelSnap -> ImDrawFlags_TextNoPixelSnap, unifying them allows easily using them for both per-primitives alterations and scope alterations. + - renamed ImDrawFlags_RoundCornersXXXX to ImDrawFlags_RoundXXXX. + - ImDrawFlags_RoundCornersAll -> ImDrawFlags_RoundAll, + - ImDrawFlags_RoundCornersNone -> ImDrawFlags_RoundNone, + - ImDrawFlags_RoundCornersTopLeft -> ImDrawFlags_RoundTopLeft, + - ImDrawFlags_RoundCornersTop -> ImDrawFlags_RoundTop, + - ImDrawFlags_RoundCornersBottom -> ImDrawFlags_RoundBottom, + etc. + kept redirection enums (will obsolete). - obsoleted style.AntiAliasedLinesUseTex which now only makes sense for legacy strokes. - 2026/09/30 (1.93.0) - ImFont: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). (#609, #5748) - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. @@ -7365,7 +7373,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar if (bg_col & IM_COL32_A_MASK) { ImRect bg_rect(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size); - ImDrawFlags bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersBottom; + ImDrawFlags bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundAll : ImDrawFlags_RoundBottom; ImDrawList* bg_draw_list = window->DrawList; bg_draw_list->AddRectFilled(bg_rect.Min, bg_rect.Max, bg_col, window_rounding, bg_rounding_flags); } @@ -7375,7 +7383,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); - window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop); + window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundTop); } // Menu bar @@ -7383,7 +7391,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar { ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. - window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); + window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundTop); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size, menu_bar_rect.Max.x - window_border_size, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize, ImDrawFlags_StrokeCenterBiased); } diff --git a/imgui.h b/imgui.h index eafe71d32..f3eeea91f 100644 --- a/imgui.h +++ b/imgui.h @@ -3317,19 +3317,19 @@ enum ImDrawFlags_ // - "Scope" column: 'OK' = initialized by ImGui based on Style options (e.g. whether anti-aliased is enabled) + may be modified using ImDrawList::PushDrawFlag(). // OK(0)/OK(1) indicates whether this flag is set in the default ImGui Style settings. - // - Rounding default to ImDrawFlags_RoundCornersAll when 'rounding > 0'. - // - So you only need to use the _RoundCorners flags if you want a special configuration (e.g. a rectangle with one rounded corner). + // - Rounding default to ImDrawFlags_RoundAll when 'rounding > 0'. + // - So you only need to use the ImDrawFlags_RoundXXX flags if you want a special configuration (e.g. a rectangle with one rounded corner). // Rounding for AddRectXXX(), PathRect() ------ // Prim/Scope? - ImDrawFlags_RoundCornersTopLeft = 1 << 4, // OK -- // Round top-left corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundCornersTopRight = 1 << 5, // OK -- // Round top-right corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // OK -- // Round bottom-left corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundCornersBottomRight = 1 << 7, // OK -- // Round bottom-right corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundCornersNone = 1 << 8, // OK -- // Disable rounding even when 'rounding > 0.0f'. This value is NOT zero, it is NOT an implicit flag! - ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, // (Default!!) - ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, - ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, - ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, - ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundTopLeft = 1 << 4, // OK -- // Round top-left corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundTopRight = 1 << 5, // OK -- // Round top-right corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundBottomLeft = 1 << 6, // OK -- // Round bottom-left corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundBottomRight = 1 << 7, // OK -- // Round bottom-right corner only (when 'rounding > 0.0f', we default to all corners). + ImDrawFlags_RoundNone = 1 << 8, // OK -- // Disable rounding even when 'rounding > 0.0f'. This value is NOT zero, it is NOT an implicit flag! + ImDrawFlags_RoundAll = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundTopRight | ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundBottomRight, // (Default!!) + ImDrawFlags_RoundTop = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundTopRight, + ImDrawFlags_RoundBottom = ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundBottomRight, + ImDrawFlags_RoundLeft = ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundTopLeft, + ImDrawFlags_RoundRight = ImDrawFlags_RoundBottomRight | ImDrawFlags_RoundTopRight, // Stroke Options ----------------------------- // Prim/Scope? ImDrawFlags_Closed = 1 << 9, // OK -- // PathStroke(), AddPolyline(): specify that shape should be closed. @@ -3365,11 +3365,26 @@ enum ImDrawFlags_ ImDrawFlags_AllowTexForRoundCorners_= 1 << 23, // -- OK(1) // [Internal] // [Internal] - ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, // [Internal] - ImDrawFlags_AllowInPushScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundCornersMask_, // [Internal] Values allowed in PushDrawFlag() scope. + ImDrawFlags_RoundMask_ = ImDrawFlags_RoundAll | ImDrawFlags_RoundNone, // [Internal] + ImDrawFlags_AllowInPushScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundMask_, // [Internal] Values allowed in PushDrawFlag() scope. ImDrawFlags_AllowInFrameScope_ = ImDrawFlags_AllowInPushScope_ | ImDrawFlags_AllowTexForRoundCorners_, ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. + + // Obsolete names +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // RENAMED in 1.93.0 (Oct 2026): ImDrawFlags_RoundCornersXXXX -> ImDrawFlags_RoundXXXX. + ImDrawFlags_RoundCornersTopLeft = ImDrawFlags_RoundTopLeft, + ImDrawFlags_RoundCornersTopRight = ImDrawFlags_RoundTopRight, + ImDrawFlags_RoundCornersBottomLeft = ImDrawFlags_RoundBottomLeft, + ImDrawFlags_RoundCornersBottomRight = ImDrawFlags_RoundBottomRight, + ImDrawFlags_RoundCornersNone = ImDrawFlags_RoundNone, + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundAll, + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundTop, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundBottom, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundRight, +#endif }; // Draw command list @@ -4330,16 +4345,16 @@ typedef ImFontAtlasRect ImFontAtlasCustomRect; //typedef ImDrawFlags ImDrawCornerFlags; //enum ImDrawCornerFlags_ //{ -// ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit -// ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). -// ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. -// ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. -// ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. -// ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 -// ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, -// ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, -// ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, -// ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, +// ImDrawCornerFlags_None = ImDrawFlags_RoundNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundNone which is != 0 and not implicit +// ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). +// ImDrawCornerFlags_TopRight = ImDrawFlags_RoundTopRight, // Was == 0x02 (1 << 1) prior to 1.82. +// ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. +// ImDrawCornerFlags_BotRight = ImDrawFlags_RoundBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. +// ImDrawCornerFlags_All = ImDrawFlags_RoundAll, // Was == 0x0F prior to 1.82 +// ImDrawCornerFlags_Top = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundTopRight, +// ImDrawCornerFlags_Bot = ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundBottomRight, +// ImDrawCornerFlags_Left = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundBottomLeft, +// ImDrawCornerFlags_Right = ImDrawFlags_RoundTopRight | ImDrawFlags_RoundBottomRight, //}; // RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index efd35bb0a..2f5450e09 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10474,7 +10474,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImVec2 start_pos = ImGui::GetCursorScreenPos(); const float pi = 3.141592f; const float spacing = 10.0f; - const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; + const ImDrawFlags corners_tl_br = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundBottomRight; const float half_sz = sz * 0.5f; const float half_szi = (float)(int)(sz * 0.5f); const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8f53a8120..a696fade0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1826,13 +1826,13 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr const bool has_rounding = IM_HAS_ROUNDING(rounding); if (has_rounding) { - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags |= ImDrawFlags_RoundCornersAll; + if ((flags & ImDrawFlags_RoundMask_) == 0) + flags |= ImDrawFlags_RoundAll; - rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); - rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundTop) == ImDrawFlags_RoundTop) || ((flags & ImDrawFlags_RoundBottom) == ImDrawFlags_RoundBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundLeft) == ImDrawFlags_RoundLeft) || ((flags & ImDrawFlags_RoundRight) == ImDrawFlags_RoundRight) ? 0.5f : 1.0f) - 1.0f); } - if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + if (!has_rounding || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) { PathLineTo(a); PathLineTo(ImVec2(b.x, a.y)); @@ -1841,10 +1841,10 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } else { - const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? rounding : 0.0f; - const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? rounding : 0.0f; - const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? rounding : 0.0f; - const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? rounding : 0.0f; + const float rounding_tl = (flags & ImDrawFlags_RoundTopLeft) ? rounding : 0.0f; + const float rounding_tr = (flags & ImDrawFlags_RoundTopRight) ? rounding : 0.0f; + const float rounding_br = (flags & ImDrawFlags_RoundBottomRight) ? rounding : 0.0f; + const float rounding_bl = (flags & ImDrawFlags_RoundBottomLeft) ? rounding : 0.0f; PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9); PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3); @@ -2103,7 +2103,7 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c ImDrawVert* start_vtx_ptr = _VtxWritePtr; ImDrawIdx* start_idx_ptr = _IdxWritePtr; - if (flags & ImDrawFlags_RoundCornersTopLeft) + if (flags & ImDrawFlags_RoundTopLeft) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p_min.x, p_min.y, uv_tl, col); @@ -2114,7 +2114,7 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } - if (flags & ImDrawFlags_RoundCornersTopRight) + if (flags & ImDrawFlags_RoundTopRight) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p_max.x - r, p_min.y, uv_tr, col); @@ -2125,7 +2125,7 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } - if (flags & ImDrawFlags_RoundCornersBottomRight) + if (flags & ImDrawFlags_RoundBottomRight) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p_max.x - r, p_max.y - r, uv_br, col); @@ -2136,7 +2136,7 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } - if (flags & ImDrawFlags_RoundCornersBottomLeft) + if (flags & ImDrawFlags_RoundBottomLeft) { ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p_min.x, p_max.y - r, uv_bl, col); @@ -2147,10 +2147,10 @@ void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 c IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); } - const float r_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? r : 0; - const float r_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? r : 0; - const float r_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? r : 0; - const float r_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? r : 0; + const float r_tl = (flags & ImDrawFlags_RoundTopLeft) ? r : 0; + const float r_tr = (flags & ImDrawFlags_RoundTopRight) ? r : 0; + const float r_br = (flags & ImDrawFlags_RoundBottomRight) ? r : 0; + const float r_bl = (flags & ImDrawFlags_RoundBottomLeft) ? r : 0; const ImVec2 opaque_uv = _Data->TexUvWhitePixel; { @@ -2241,7 +2241,7 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImDrawIdx* start_idx_ptr = _IdxWritePtr; static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; - static const ImDrawFlags corner_flags[4] = { ImDrawFlags_RoundCornersTopLeft, ImDrawFlags_RoundCornersTopRight, ImDrawFlags_RoundCornersBottomRight, ImDrawFlags_RoundCornersBottomLeft }; + static const ImDrawFlags corner_flags[4] = { ImDrawFlags_RoundTopLeft, ImDrawFlags_RoundTopRight, ImDrawFlags_RoundBottomRight, ImDrawFlags_RoundBottomLeft }; const float half_fringe = fringe * 0.5f; const ImVec2 corner_pos[4] = { @@ -2327,11 +2327,11 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl // If this assert triggers on legacy code: // - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. // - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. - // - 1.82.0 (2021/03): changed ImDrawCornerFlags to ImDrawFlags_RoundCornersXXX values. + // - 1.82.0 (2021/03): changed ImDrawCornerFlags to ImDrawFlags_RoundXXX values. // If you used hard-coded 1 to 15 or ~0 in flags to configure corner rounding use the new flags! - // - Hard coded support for ~0 == ImDrawFlags_RoundCornersAll. + // - Hard coded support for ~0 == ImDrawFlags_RoundAll. // - Hard coded support for values 0x01 to 0x0F (matching 15 out of 16 old flags combinations) --> see FixRectCornerFlags() in <1.90 code. - // - Hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f'. + // - Hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundNone or use 'float rounding = 0.0f'. // See "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); // Or misuse of legacy hard-coded ImDrawCornerFlags values @@ -2380,13 +2380,13 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl return; } - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags |= ImDrawFlags_RoundCornersAll; + if ((flags & ImDrawFlags_RoundMask_) == 0) + flags |= ImDrawFlags_RoundAll; if (has_rounding) { // Constrain rounding to rect dimensions - outer_rounding = ImMin(outer_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); - outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + outer_rounding = ImMin(outer_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundTop) == ImDrawFlags_RoundTop) || ((flags & ImDrawFlags_RoundBottom) == ImDrawFlags_RoundBottom) ? 0.5f : 1.0f) - 1.0f); + outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundLeft) == ImDrawFlags_RoundLeft) || ((flags & ImDrawFlags_RoundRight) == ImDrawFlags_RoundRight) ? 0.5f : 1.0f) - 1.0f); } const bool is_truncated = IM_IS_TRUNCATED4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && IM_IS_TRUNCATED4(outer_rounding, thickness, 0.0f, 0.0f); //-V501 @@ -2397,7 +2397,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (s_thickness <= 0) return; - if (s_rounding <= 0 || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + if (s_rounding <= 0 || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) { // Pixel aligned non-rounded rect. const ImVec2 opaque_uv = _Data->TexUvWhitePixel; @@ -2443,7 +2443,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl } } - if (!has_rounding || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + if (!has_rounding || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) { const ImVec2 points[4] = { outer_min, ImVec2(outer_max.x, outer_min.y), outer_max, ImVec2(outer_min.x, outer_max.y) }; _AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside, half_min_dim); @@ -2459,10 +2459,10 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl _AddRectTinyRounding(outer_min, outer_max, col, outer_rounding, thickness, flags); return; } - const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? outer_rounding : 0.0f; - const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? outer_rounding : 0.0f; - const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? outer_rounding : 0.0f; - const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? outer_rounding : 0.0f; + const float rounding_tl = (flags & ImDrawFlags_RoundTopLeft) ? outer_rounding : 0.0f; + const float rounding_tr = (flags & ImDrawFlags_RoundTopRight) ? outer_rounding : 0.0f; + const float rounding_br = (flags & ImDrawFlags_RoundBottomRight) ? outer_rounding : 0.0f; + const float rounding_bl = (flags & ImDrawFlags_RoundBottomLeft) ? outer_rounding : 0.0f; PathArcToFast(ImVec2(outer_min.x + rounding_tl, outer_min.y + rounding_tl), rounding_tl, 6, 9); PathArcToFast(ImVec2(outer_max.x - rounding_tr, outer_min.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(outer_max.x - rounding_br, outer_max.y - rounding_br), rounding_br, 0, 3); @@ -2483,10 +2483,10 @@ void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, I PrimReserve(9 * 2 * 3, 4 * 4); - const float r_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? r : 0.0f; - const float r_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? r : 0.0f; - const float r_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? r : 0.0f; - const float r_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? r : 0.0f; + const float r_tl = (flags & ImDrawFlags_RoundTopLeft) ? r : 0.0f; + const float r_tr = (flags & ImDrawFlags_RoundTopRight) ? r : 0.0f; + const float r_br = (flags & ImDrawFlags_RoundBottomRight) ? r : 0.0f; + const float r_bl = (flags & ImDrawFlags_RoundBottomLeft) ? r : 0.0f; ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; IM_APPEND_VTX(p_min.x, p_min.y, uv_tl, col); @@ -2552,7 +2552,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c } // When rounding non-integer and under threshold, has_rounding may be false but still affect is_truncated. Likely not worth catering for. - const bool has_rounding = (flags & ImDrawFlags_RoundCornersMask_) != ImDrawFlags_RoundCornersNone && IM_HAS_ROUNDING(rounding); + const bool has_rounding = (flags & ImDrawFlags_RoundMask_) != ImDrawFlags_RoundNone && IM_HAS_ROUNDING(rounding); const bool is_truncated = IM_IS_TRUNCATED4(p_min.x, p_min.y, p_max.x, p_max.y) && IM_IS_TRUNCATED(rounding); if (_FringeScaleIsInteger && is_truncated) @@ -2565,11 +2565,11 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c return; } - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags |= ImDrawFlags_RoundCornersAll; + if ((flags & ImDrawFlags_RoundMask_) == 0) + flags |= ImDrawFlags_RoundAll; - rounding = ImMin(rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); - rounding = ImMin(rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundTop) == ImDrawFlags_RoundTop) || ((flags & ImDrawFlags_RoundBottom) == ImDrawFlags_RoundBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundLeft) == ImDrawFlags_RoundLeft) || ((flags & ImDrawFlags_RoundRight) == ImDrawFlags_RoundRight) ? 0.5f : 1.0f) - 1.0f); const int s_rounding = (int)(rounding * _InvFringeScale); if (s_rounding <= 0) @@ -2994,10 +2994,10 @@ void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, cons return; IM_ASSERT((flags & 0x0F) == 0 && "Misuse of legacy hardcoded ImDrawCornerFlags values!"); // If this assert triggers on legacy code: see comments in ImDrawList::PathRect(). - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags |= ImDrawFlags_RoundCornersAll; + if ((flags & ImDrawFlags_RoundMask_) == 0) + flags |= ImDrawFlags_RoundAll; - if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) + if (rounding < 0.5f || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) { AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col); return; @@ -7678,14 +7678,14 @@ void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const bool fill_R = (inner.Max.x < outer.Max.x); const bool fill_U = (inner.Min.y > outer.Min.y); const bool fill_D = (inner.Max.y < outer.Max.y); - if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomLeft)); - if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopRight) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomRight)); - if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersTopRight)); - if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersBottomRight)); - if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopLeft); - if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopRight); - if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomLeft); - if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight); + if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, ImDrawFlags_RoundNone | (fill_U ? 0 : ImDrawFlags_RoundTopLeft) | (fill_D ? 0 : ImDrawFlags_RoundBottomLeft)); + if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, ImDrawFlags_RoundNone | (fill_U ? 0 : ImDrawFlags_RoundTopRight) | (fill_D ? 0 : ImDrawFlags_RoundBottomRight)); + if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundNone | (fill_L ? 0 : ImDrawFlags_RoundTopLeft) | (fill_R ? 0 : ImDrawFlags_RoundTopRight)); + if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundNone | (fill_L ? 0 : ImDrawFlags_RoundBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundBottomRight)); + if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundTopLeft); + if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundTopRight); + if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundBottomLeft); + if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundBottomRight); } ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold) @@ -7694,9 +7694,9 @@ ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRe bool round_r = r_in.Max.x >= r_outer.Max.x - threshold; bool round_t = r_in.Min.y <= r_outer.Min.y + threshold; bool round_b = r_in.Max.y >= r_outer.Max.y - threshold; - return ImDrawFlags_RoundCornersNone - | ((round_t && round_l) ? ImDrawFlags_RoundCornersTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundCornersTopRight : 0) - | ((round_b && round_l) ? ImDrawFlags_RoundCornersBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundCornersBottomRight : 0); + return ImDrawFlags_RoundNone + | ((round_t && round_l) ? ImDrawFlags_RoundTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundTopRight : 0) + | ((round_b && round_l) ? ImDrawFlags_RoundBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundBottomRight : 0); } // Helper for ColorPicker4() @@ -7704,8 +7704,8 @@ ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRe // Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float alpha, float grid_step, ImVec2 grid_off, float rounding, ImDrawFlags flags) { - if ((flags & ImDrawFlags_RoundCornersMask_) == 0) - flags = ImDrawFlags_RoundCornersAll; + if ((flags & ImDrawFlags_RoundMask_) == 0) + flags = ImDrawFlags_RoundAll; if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) { IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f); @@ -7731,12 +7731,12 @@ void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p float x1 = ImClamp((float)(int)x, p_min.x, p_max.x), x2 = ImMin((float)(int)(x + grid_step), p_max.x); if (x2 <= x1) continue; - ImDrawFlags cell_flags = ImDrawFlags_RoundCornersNone; // FIXME: Could use CalcRoundingFlagsForRectInRect() - if (y1 <= p_min.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersTopLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersTopRight; } - if (y2 >= p_max.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersBottomLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersBottomRight; } + ImDrawFlags cell_flags = ImDrawFlags_RoundNone; // FIXME: Could use CalcRoundingFlagsForRectInRect() + if (y1 <= p_min.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundTopLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundTopRight; } + if (y2 >= p_max.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundBottomLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundBottomRight; } // Combine flags - cell_flags = (flags == ImDrawFlags_RoundCornersNone || cell_flags == ImDrawFlags_RoundCornersNone) ? ImDrawFlags_RoundCornersNone : (cell_flags & flags); + cell_flags = (flags == ImDrawFlags_RoundNone || cell_flags == ImDrawFlags_RoundNone) ? ImDrawFlags_RoundNone : (cell_flags & flags); ImU32 col_bg = dual_layer ? col_bg2 : (((yi + xi) & 1) ? col_bg2 : col_bg1); draw_list->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg, rounding, cell_flags); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8a210c415..287d94062 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1980,12 +1980,12 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size); RenderNavCursor(bb, id); if (!(flags & ImGuiComboFlags_NoPreview)) - window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft); + window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundAll : ImDrawFlags_RoundLeft); if (!(flags & ImGuiComboFlags_NoArrowButton)) { ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); ImU32 text_col = GetColorU32(ImGuiCol_Text); - window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight); + window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundAll : ImDrawFlags_RoundRight); if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x) RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f); } @@ -6623,10 +6623,10 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl { float mid_x = IM_ROUND((bb.Min.x + bb.Max.x) * 0.5f); if ((flags & ImGuiColorEditFlags_AlphaNoBg) == 0) - RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, ColorConvertFloat4ToU32(col_rgb), g.Style.Alpha, grid_step, ImVec2(-grid_step, 0.0f), rounding, ImDrawFlags_RoundCornersRight); + RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, ColorConvertFloat4ToU32(col_rgb), g.Style.Alpha, grid_step, ImVec2(-grid_step, 0.0f), rounding, ImDrawFlags_RoundRight); else - window->DrawList->AddRectFilled(ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundCornersRight); - window->DrawList->AddRectFilled(bb.Min, ImVec2(mid_x, bb.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft); + window->DrawList->AddRectFilled(ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundRight); + window->DrawList->AddRectFilled(bb.Min, ImVec2(mid_x, bb.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundLeft); } else { @@ -11052,7 +11052,7 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f)); const float y1 = bb.Min.y + 1.0f; // Leave a bit of room in title bars. const float y2 = bb.Max.y - g.Style.TabBarBorderSize; - draw_list->AddRectFilled(ImVec2(bb.Min.x, y1), ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags_RoundCornersTop); + draw_list->AddRectFilled(ImVec2(bb.Min.x, y1), ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags_RoundTop); if (g.Style.TabBorderSize > 0.0f) { draw_list->PathLineTo(ImVec2(bb.Min.x, y2)); From 475b793baabb3e989c4ebcbfec1e45f4ebf6d0f9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 31 Jul 2026 19:44:00 +0200 Subject: [PATCH 151/245] Docs: reworked Changelog, comments. --- docs/CHANGELOG.txt | 391 +++++++++++++++++++++++++++------------------ imgui.cpp | 30 +++- imgui.h | 20 +-- imgui_demo.cpp | 8 +- imgui_draw.cpp | 14 +- imgui_internal.h | 4 +- 6 files changed, 283 insertions(+), 184 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 83e95c2ff..70a89b246 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,160 +39,118 @@ HOW TO UPDATE? VERSION 1.93.0 WIP (In Progress) ----------------------------------------------------------------------- -- In 1.93, the ImDrawList rendering has been improved to be more robust and more consistent over - the whole range of shapes. The rendering now matches much closer to common vector drawing APIs, - like html canvas. Improvements, like anti-aliased line endings and stroke position were added, - and the coordinates passed to the API are now consistent. - Some details are now rendered slightly differently (even if generally more consistent). - The difference in rendering is in the range of half a pixel, but that can lead to issues like - some lines now look blurrier or more transparent. - The rendering of common shapes was optimized when the shapes fall on integer coordinates - (which is most of the UI). This includes skipping anti-aliasing when not needed, or using - textures instead of tessellated geometry to draw round corners. -- Most of the work courtesy of @memononen, with bits from @ocornut, @thedmd, @potocpav. -- Refer to our full guides: - - ImDrawList Vector Rendering Reference: - https://github.com/ocornut/imgui/wiki/Draw-List - - Pixel Perfect Anti-aliased Rendering: - https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering - - How Anti-aliased Polyline Rendering is Implemented: - https://github.com/ocornut/imgui/wiki/Polyline-Rendering -- (Breaking) AddLine: removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates. - - This fixes inconsistencies in the API and matches the PathXXX API. - - By default, stroke thickness extends on both side of the given segment. - e.g for a "pixel-perfect" looking line with thickness=1.0f, coords should be passed as center of each ends of the line. - - Use `ImDrawFlags_StrokeLegacy` to use old offset if required. But you might as well apply the offset manually! - - Generally better to use to newly introduced `AddLineH()`, `AddLineV()` functions. - READ IF YOU ARE MINDFUL OF PIXEL-PERFECTNESS IN YOUR CUSTOM RENDERING/WIDGETS: - - TRANSITION GUIDE FOR AXIS-ALIGNED LINES: - - When switching from legacy `AddLine()` values to `AddLineV()`, `AddLineH()` you can keep same inputs coordinates as before. - - Old `AddLine({x, y1}, {x, y2}, col)` --> `AddLineV(x, y1, y2, col);` // Vertical line. - - Old `AddLine({x1, y}, {x2, y}, col)` --> `AddLineH(x1, x2, y, col);` // Horizontal line. - - This will be equivalent and faster for thickness=1.0f lines. - - Since `AddLine()` use default stroke pos Center and `AddLineV()`, `AddLineH()` use Inside, thickness>1.0f strokes will differ. - Using `ImDrawFlags_StrokeCenter` will match old result more closely (aka look centered), but is more likely - to look blurry as it already did before. Read table below about StrokePos and the - "Pixel-Perfect Rendering" guide if you care about pixel-perfect lines. - - TRANSITION GUIDE FOR DIAGONAL LINES: - - Your lines will appear offset by -0.5f pixels on each axis. - Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. - It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. - - Old AddLine({x1, y1}, {x2, y2}, col) == AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy); // Offset by +0.5f + disable AA ends. - == AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col, thickness); // Same - This reapplies the old offset, and should get you exactly the same result you previously got for thickness=1.0f lines. - But said result was sometimes ambiguous and renderer dependent. (#3116, #3258, #2441) - - Old `AddLine()` did not have anti-aliased ends, which could create gaps when rendering shapes out - of multiple contiguous lines instead of using AddPolyline(). There is a possibility that you could - have added fudge offsets here and there which are not necessary anymore or may be simplified. -- AddPolyline(), PathStroke(), AddTriangle(): the algorithm to render lines got overhauled. - (#2183, #2964, #7972) - - Generally fixed rendering of thick strokes/paths. - - The new stroke expansion now uses corner miter calculation, which keeps thickness along - the line segments consistent. If the corner becomes too sharp, it will be bevelled to avoid - long spikes at corners. - - There are also some robustness measures for the case where the line thickness is larger - than the features being drawn. - - Rendering artifacts are still possible when the path features are smaller than line thickness, - but the artifacts should be more localized. The new implementation attempted to favor simple - implementation and robustness over the corner case accuracy. - - New rendering code fixes (subtle) inconsistencies between graphics API (e.g. DirectX vs OpenGL) - using different diamond exits rules. New code should work precisely the same regardless - of graphics API. (#3116, #3258, #2441) - - Added `ImDrawFlags_AALineEnds` flag to enable anti-aliased line ends. - - Most noticeable for thick lines. - - Helps fills minor gaps if combining multiple individual lines. - - Enabling AA Ends by default would be more "correct", but it is slower and increase vertex/index data.s - - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner (closer to legacy - rendering, slightly faster, but corners sharper than 90 degrees may expand far out). - Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() etc functions - since we know that the input path does not contains sharper corners. - - Added `ImDrawFlags_SquareCap` flag to use extend lines ends using square caps. -- AddConvexPolyFilled()/PathFillConvex(): improved to handle input geometry more robustly. - The rendering of sharp corners was improved. Earlier there were issues with sharp corners - either creating long spikes, or messing up the adjacent edge’s anti-aliasing. Now the - anti-aliasing fringe calculation is more consistent, and sharp corners get bevelled to - avoid spikes. There might still be issues when the smallest extent of a long thin polygon - is less than a pixel. Also supports `ImDrawFlags_MiterOnly`, to facilitate matching - a stroke using the same flag. -- AddRect(), AddRectFilled(): various optimization for rounded rectangles. (#1962) - - Integer-aligned coordinates and thicknesses will automatically use baked textures, - saving on both CPU and vertex/index data. - - Added `ImFontAtlasFlags_NoBakedRoundCorners` to disable baking round corners in font atlas. - - Added `ImDrawFlags_UseTexForRoundCorners` to enable using round corners. -- AddRectFilled(): non-integer coordinates will now display anti-aliased edges. (#6971) -- Improved minor mismatches when overlapping strokes and filled shapes, - e.g. when using inside strokes, - - `AddRect()` and `AddRectFilled()` with rounding now overlap better. (#3656) - - `AddCircle()` and `AddCircleFilled()` now overlap better. -- Added flags to specify stroke position in all `ImDrawList` stroking functions: - - `ImDrawFlags_StrokeInside` (default for closed primitives and AddLineH, AddLineV) - - `ImDrawFlags_StrokeCenter` (default for paths, bezier and AddLine) - - `ImDrawFlags_StrokeCenterBiased` - - `ImDrawFlags_StrokeOutside` - - `ImDrawFlags_StrokeLegacy` (may be set as default for a given scope using PushDrawFlag()). - - Legacy code was generally applying +0.50f offset which meant that, - - with thickness=1.0f: the stroke would appear inside. - - with thickness>1.0f: the stroke would start expanding on both sides but starting from that slightly initial offset. - - with thickness>1.0f for even integer values, the stroke would look blurry. - - TL;DR; the logic didn't make much sense for thickness>1.0f. - - Defaulting to Inside for closed shapes ensure that rectangles and lines are never blurry, - regardless of thickness, as long as input coordinates/sizes are integers. (#9359) - - Read our Wiki guides! Recap: - ------------------------------------------------------------------------ - Legacy Inside Outside Center CenterBiased - -------------------------------------------------------------------------------- - Thickness=1.0f sharp sharp sharp blurry sharp - Thickness=2.0f blurry sharp sharp sharp sharp - Thickness=3.0f sharp sharp sharp blurry sharp - ------------------------------------------------------------------------ -- Added ImDrawList::PushDrawFlag()/PopDrawFlag() to alter certain flags for a scope, - e.g. `PushDrawFlag(ImDrawFlags_StrokeLegacy, true);` enforce legacy tweaks. -- (Breaking) AddRect, AddCircle, AddNgon, AddEllipse: defaulting to "inside" stroke. - - All closed shapes with thickness=1.0f will appear identical. - - The difference for thickness>1.0f shapes may be minimal since very large strokes - were not well supported for widgets, but stroke will default inside widgets. -- (Breaking) Merged `ImDrawListFlags` into `ImDrawFlags`. - `ImDrawListFlags` was very rarely used directly. Keep inline redirection (will obsolete). - - `ImDrawListFlags_AntiAliasedLines` -> `ImDrawFlags_AALines` - - `ImDrawListFlags_AntiAliasedFill` -> `ImDrawFlags_AAFill` - - `ImDrawListFlags_AntiAliasedLinesUseTex` -> `ImDrawFlags_UseTexForStrokeLegacy` - - `ImDrawListFlags_AllowVtxOffset` -> `ImDrawFlags_UseVtxOffset` - - `ImDrawListFlags_TextNoPixelSnap` -> `ImDrawFlags_TextNoPixelSnap` - Unifying them allows easily using them for both per-primitives and scope alterations. -- (Breaking) Enabling `ImFontAtlasFlags_NoBakedLines` in the font atlas will disable - support for anti-aliased lines. -- About `ImDrawFlags_StrokeLegacy`: - - This is designed to emulate old coordinates: - - Most shapes are "StrokeCenter". - - AddLine() adds a +0.5f,+0.5f offset. - - Closed shapes user miter angles. - - But there are known difference between legacy code and ImDrawFlags_StrokeLegacy: - - Thick shapes with acute angles will now preserve thickness. - - Thick shapes with acute angles will protrude a little more. -- About disabling anti-aliasing: - - Disabling anti-aliasing is now emulated by using different UV coordinates. - It does not result in a performance increase any more (however the tendency - is that the new code behave better than old code). - - Many thick shapes had broken corners with old no-AA code, and the old no-AA code - was wildly different from the AA code. Not the case any more. (#288) -- Tweaked line rendering in various locations to avoid blurryness: - - Windows: title-bar and menu-bar border (when thickness>1.0f). - - Tables: borders (when thickness>1.0f). - - SeparatorText: border (when thickness>1.0f). - - Tree: hierarchy lines (when thickness>1.0f). - - TabBar: selected overline border ((when thickness>1.0f). - - Demo: Custom Rendering: canvas lines. -- Checkbox, Menus: check marks use anti-aliased ends. -- Demo: Custom Rendering: exposed new flags; Showcasing overlapping strokes and - filled shapes; Added an option to animation thickness; Added new shapes to - showcase new rendering features that previously hit limitations. +In 1.93.0, the `ImDrawList` rendering API has been improved to be more robust and +more consistent over the whole range of shapes. The rendering now matches much closer +to common vector drawing APIs, like html canvas. Improvements, like anti-aliased line +endings and stroke position were added. The coordinates passed to the API are now +consistently describing shape outlines. + +For code using custom rendering: some details are now rendered slightly differently +(even if generally more consistent). The difference in rendering is in the range of +half a pixel, but that can lead to issues like some lines now look blurrier or more +transparent. All Dear ImGui widgets should appear identical or better. + +The rendering of common shapes was optimized when the shapes fall on integer coordinates +(which is most of the UI). This includes skipping anti-aliasing when not needed, or +using textures instead of tessellated geometry to draw round corners. +The varying code-paths are designed to look indistinguishable from each others. + +New rendering code fixes some inconsistencies between graphics APIs (e.g. DirectX vs OpenGL) +which are using different diamond exits rules. +New code should work precisely the same regardless of graphics API. +(note that using _StrokeLegacy mode can lead to similar inconsistencies) + +New rendering code also deals better with animating thickness and rounding +(integer values are recommended). + +While the current version doesn't make lots of visible use of the new features and +facilities, they are among the pillars that will make it easier to create prettier +contents, both for custom rendering and future versions of the library. + +Main work courtesy of @memononen. +Additional work/reviewing/guidance by @ocornut. +With legacy bits from @thedmd, @potocpav. + +Refer to our guides: + +- ImDrawList Vector Rendering Reference + https://github.com/ocornut/imgui/wiki/Draw-List + (includes a precise list of differences between 1.92.9 and 1.93.0). + +- ImDrawList 1.92.9 vs 1.93.0 Interactive Testbed + https://www.dearimgui.com/docs/drawlist_v193 + (interactively discuss and compare differences between 1.92.9 and 1.93.9) + (downloadable HTML file, may be used offline) + +- Pixel Perfect Anti-aliased Rendering + https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering + +- How Anti-aliased Polyline Rendering is Implemented + https://github.com/ocornut/imgui/wiki/Polyline-Rendering + +- Main topic: + https://github.com/ocornut/imgui/issues/9504 + (if you have a problem to discuss, please open a new issue) Breaking Changes: - DrawList: + - AddLine(): removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates. (#9504) + - This fixes inconsistencies in the API and matches the PathXXX API. + - By default, stroke thickness extends on both side of the given segment. + e.g for a "pixel-perfect" looking line with thickness=1.0f, coords should be passed as center of each ends of the line. + - Use `ImDrawFlags_StrokeLegacy` to use old offset if required. Or you can apply the offset manually! + - Generally better, simple and faster to use `AddLineH()`, `AddLineV()` functions added in 1.92.8. + READ IF YOU ARE MINDFUL OF PIXEL-PERFECTNESS IN YOUR CUSTOM RENDERING/WIDGETS: + - TRANSITION GUIDE FOR AXIS-ALIGNED LINES: + - When switching from legacy `AddLine()` values to `AddLineV()`, `AddLineH()` you can keep same inputs coordinates as before: + - Old `AddLine({x, y1}, {x, y2}, col)` --> `AddLineV(x, y1, y2, col);` // Vertical line. + - Old `AddLine({x1, y}, {x2, y}, col)` --> `AddLineH(x1, x2, y, col);` // Horizontal line. + - This will be equivalent and faster for thickness=1.0f lines. + - Since `AddLine()` use default stroke pos Center and `AddLineV()`, `AddLineH()` use Inside, thickness>1.0f strokes will differ. + Using `ImDrawFlags_StrokeCenter` will match old result more closely (aka look centered), + but is more likely to look blurry as it already did before. + - Read table below about StrokePos and the "Pixel-Perfect Rendering" guide if you care about pixel-perfect lines. + - TRANSITION GUIDE FOR DIAGONAL LINES: + - Your lines will appear offset by -0.5f pixels on each axis. + Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. + It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. + - Old `AddLine({x1, y1}, {x2, y2}, col)` --> `AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col);` // Same + or use `ImDrawFlags_StrokeLegacy` --> `AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy); // Offset by +0.5f + disable AA ends. + This reapplies the old offset, and should get you exactly the same result you previously + got for thickness=1.0f lines. But said result were previously sometimes ambiguous and + renderer-dependent. (#3116, #3258, #2441) + - Old code did not support anti-aliased ends, which could create gaps when rendering shapes out + of multiple contiguous lines instead of using `AddPolyline()`. There is a possibility that you + legacy code added fudge offsets here and there; which may not be necessary anymore if you use + `_AALineEnds`, or if you combine rendering of contiguous lines using `AddPolyline()`. + - AddRect(), AddCircle(), AddNgon(), AddEllipse(), AddTriangle(), AddQuad(): defaulting to "inside" stroke. + - All closed shapes with thickness=1.0f will appear identical. + - The difference for thickness>1.0f shapes may be minimal since very large strokes + were not well supported for widgets, but stroke will default inside widgets. + - AddCircle(), AddNgon(): removed +0.5f offset added to radius. + - This fixes inconsistencies in the API. + - Use `ImDrawFlags_StrokeLegacy` to use old method if required. Or you can apply the offset manually! + - AddRectFilled(): non-integer coordinates will now display anti-aliased edges. + Previously, non-integer coordinates rendered with aliased edges snapped by the + rasterizer. (#6971) + - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible + unless using ImDrawList_StrokeLegacy mode. With inverted coordinates (min > max): + - Legacy `AddRect()` rounding off -> visible but incorrect outer size. + - Legacy `AddRect()` rounding on -> visible but very glitchy. + - Legacy `AddRectFilled()` rounding off -> visible and correct. + - Legacy `AddRectFilled()` rounding on -> visible but very glitchy. + - Merged `ImDrawListFlags` into `ImDrawFlags`. `ImDrawListFlags` was rarely used directly + and generally setup by the ImGui context. Keep inline redirection enums (will obsolete). + - `ImDrawListFlags_AntiAliasedLines` -> `ImDrawFlags_AALines` + - `ImDrawListFlags_AntiAliasedFill` -> `ImDrawFlags_AAFill` + - `ImDrawListFlags_AllowVtxOffset` -> `ImDrawFlags_UseVtxOffset` + - `ImDrawListFlags_TextNoPixelSnap` -> `ImDrawFlags_TextNoPixelSnap` + Unifying them allows easily using them for both per-primitives and scope alterations. + Kept redirection enums (will obsolete). - Renamed all `ImDrawFlags_RoundCornersXXX` flags to `ImDrawFlags_RoundXXX`. - - `ImDrawFlags_RoundCornersNone` -> `ImDrawFlags_RoundNone` - `ImDrawFlags_RoundCornersAll` -> `ImDrawFlags_RoundAll` + - `ImDrawFlags_RoundCornersNone` -> `ImDrawFlags_RoundNone` - `ImDrawFlags_RoundCornersTopLeft` -> `ImDrawFlags_RoundTopLeft` - `ImDrawFlags_RoundCornersTopRight` -> `ImDrawFlags_RoundTopRight` - `ImDrawFlags_RoundCornersBottomLeft` -> `ImDrawFlags_RoundBottomLeft` @@ -202,6 +160,10 @@ Breaking Changes: - `ImDrawFlags_RoundCornersLeft` -> `ImDrawFlags_RoundLeft` - `ImDrawFlags_RoundCornersRight` -> `ImDrawFlags_RoundRight` Kept redirection enums (will obsolete). + - Marked `ImDrawListFlags_AntiAliasedLinesUseTex` and `style.AntiAliasedLinesUseTex` as + obsolete, as the new line rendering code always uses textures. + - Enabling `ImFontAtlasFlags_NoBakedLines` in the font atlas will now disable support for + anti-aliased lines by clearing `style.AntiAliasedLines`/`style.AntiAliasedLineEnds`. - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. It is easier to tweak + this allows us to easily scale error threshold on high density screens. @@ -218,8 +180,119 @@ Breaking Changes: sub-optimal and not reliable on some setup. Use `ImGui_ImplOpenGL3_SetClipOrigin(0)` to enable auto-detection, or e.g. `ImGui_ImplOpenGL3_SetClipOrigin(GL_UPPER_LEFT)`. + Other Changes: +- DrawList: + - Added flags to specify stroke position in all `ImDrawList` stroking functions: (#9504) [@memononen] + - `ImDrawFlags_StrokeInside` (default for Rect, Circle/Ellipse, Triangle, Quad, Ngon + AddLineH, AddLineV) + - `ImDrawFlags_StrokeCenter` (default for Line, Polyline, Beziers, Paths function) + - `ImDrawFlags_StrokeCenterBiased` (center w/ bias for pixel perfect alignment) + - `ImDrawFlags_StrokeOutside` + - `ImDrawFlags_StrokeLegacy` (match old behavior) + - Legacy mode may be set as default for a given scope using `PushDrawFlag(ImDrawFlags_StrokeLegacy, true)`. + - Legacy code was generally applying +0.50f offsets which meant that, + - with thickness=1.0f: the stroke would appear inside. + - with thickness>1.0f: the stroke would start expanding on both sides but starting from that small initial offset. + - with thickness>1.0f for even integer values, the stroke would look blurry. + - TL;DR; the logic didn't make much sense for thickness>1.0f. + - Defaulting to Inside for closed shapes ensure that rectangles and lines are + never blurry, regardless of thickness, as long as input coordinates/sizes + are integers. (#9359) Recap: + ------------------------------------------------------------------------ + Thickness Legacy Inside Outside Center CenterBiased + ------------------------------------------------------------------------ + 1.0f sharp sharp sharp blurry sharp + 2.0f blurry sharp sharp sharp sharp + 3.0f sharp sharp sharp blurry sharp + ------------------------------------------------------------------------ + - Read our Wiki guides for more details! + https://github.com/ocornut/imgui/wiki/Draw-List + - And interactive 1.92.9 vs 1.93.0 comparing testbed: + https://www.dearimgui.com/docs/drawlist_v193 + - AddPolyline(), PathStroke(), AddTriangle(): the algorithm to render lines got overhauled. + (#9504, #2183, #2964, #7972 + #9360, #6331, #4250, #4091) [@memononen] + - Generally fixed rendering of thick strokes/paths. + - The new stroke expansion now uses corner miter calculation, which keeps thickness along + the line segments consistent. If the corner becomes too sharp, it will be bevelled to + avoid long spikes at corners. + - There are also some robustness measures for the case where the line thickness is larger + than the features being drawn. + - Rendering artifacts are still possible when the path features are smaller than line thickness, + but the artifacts should be more localized. The new implementation attempted to favor simple + implementation and robustness over the corner case accuracy. + - All functions: new rendering code fixes some inconsistencies between graphics APIs + (e.g. DirectX vs OpenGL) which are using different diamond exits rules. New code should + work precisely the same regardless of graphics API. (#3116, #3258, #2441) [@memononen] + - Added `ImDrawFlags_AALineEnds` flag to enable anti-aliased line ends. + - Most noticeable for thick lines. + - Also helps fill minor gaps if combining multiple individual lines. For best looking + continuous lines you should use AddPolyline(), it creates joins between line segments + to avoid any gaps. + - Added `style.AntiAliasedLineEnds` in ImGui to set default state. + - This is disabled by default! Enabling AA Ends by default would be more "correct", + but since it is very slightly slower and increases vertex/index data we decided + to not enable it by default. + This keeps situations such as "throw tens of thousands of lines at ImDrawList" + optimal. You can opt-in for a given shape or in a scope using `PushDrawFlag()`. + - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner. + - Closer to legacy rendering and slightly faster, but corners sharper than + 90 degrees may expand far out. + - Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() functions + since we know that the input path does not contain sharper corners. + - Added `ImDrawFlags_SquareCap` flag to extend lines ends using square caps. (#9360) + - AddConvexPolyFilled()/PathFillConvex(): improved to handle input geometry more robustly. + The rendering of sharp corners was improved. Earlier there were issues with sharp corners + either creating long spikes, or messing up the adjacent edge's anti-aliasing. Now the + anti-aliasing fringe calculation is more consistent, and sharp corners get bevelled to + avoid spikes. There might still be issues when the smallest extent of a long thin polygon + is less than a pixel. Also supports `ImDrawFlags_MiterOnly`, to facilitate matching + a stroke using the same flag. + - AddRect(), AddRectFilled(): various optimizations for rounded rectangles. (#1962, #9504) + - Integer-aligned coordinates and thicknesses will automatically use baked textures, + saving on both CPU and vertex/index data. + - Enabled by default. Use `ImFontAtlasFlags_NoBakedRoundCorners` to disable baking + round corners in font atlas. + - Added `ImDrawFlags_UseTexForRoundCorners` flag to enable in scope or per-shape. + Added for consistency and debugging, not really needed in practice. + - Improved debug-build performance in various locations. + - Improved minor mismatches when overlapping strokes and filled shapes. + For example, when using inside strokes, + - `AddRect()` and `AddRectFilled()` with rounding now overlap better. (#3656) + - `AddCircle()` and `AddCircleFilled()` now overlap better. + - Added ImDrawList::PushDrawFlag()/PopDrawFlag() to alter certain flags for a + scope and a given `ImDrawList`. (#9489) + - e.g. `PushDrawFlag(ImDrawFlags_StrokeLegacy, true);` enforce legacy tweaks. + - About `ImDrawFlags_StrokeLegacy`: + - This is designed to emulate old behavior: + - Most shapes use `ImDrawFlags_StrokeCenter`. + - AddLine() add +0.5f,+0.5f offset to position. + - AddRect() and AddRectFilled() allow inverted positions. + - AddRectFilled() has no AA when passed non-integer coordinates. + - AddCircle(), AddNgon() add a -0.5f offset to radius. + - Closed shapes use miter corners. + - Lines don't have anti-aliased ends. + - But there are known difference between legacy code and ImDrawFlags_StrokeLegacy: + - Thick shapes with acute angles will now preserve thickness better, + which may make them appear as protruding a little more. + - About disabling anti-aliasing: + - Disabling anti-aliasing is now emulated by applying different UV coordinates. + - It does not result in a performance increase or vertex/index data decrease any more. + (however the tendency is that the new code behaves better than old code). + - But may be a useful stylistic choice in some circumstances. + - Many thick shapes had broken corners with old no-AA code, and the old no-AA code + was wildly different from the AA code. Not the case any more. (#288) + - Per-viewport FramebufferScale for Apple/Retina screen is applied to draw lists: + - AA Fringe is scaled accordingly. + - Circle and Curves tessellation error are scaled accordingly. + - Reworked assert in PushTexture() to allow convenience grace period of using a + texture that was queue for destroy during the frame. Make it safe to stick to + an existing texture during the frame. (#9528, #8465) + - Added optional `platform_io.DrawCallback_SetSamplerFromTex` standard backend-agnostic + draw callback for requesting to use the sampler associated already associated to a texture. + Currently only supported by the OpenGL2/3 and SDLRenderer3 backend. (#9378) + - Fixed dangling ImDrawList::_OwnerName when using animated label. (#9552) [@ubi-dcastonguay] + - Drags, Sliders: - Fixed an overflow using `ImGuiSliderFlags_Logarithmic` with S32/S64 types which leads to clamped interactions. (#9526, #3361, #1823, #1316, #642) [@lailoken] @@ -297,19 +370,19 @@ Other Changes: the hashed data. (#9557, #9560) [@sthalik] - IO: restore default clipboard/ime/shell platform handlers on ClearPlatformHandlers(), fixing issues switching backends mid-session to one relying on default. (#9537, #8945, #2769) [@lstalmir] -- DrawList: - - Per-viewport FramebufferScale for Apple/Retina screen is applied to draw lists: - - AA Fringe is scaled accordingly. - - Circle and Curves tessellation error are scaled accordingly. - - Reworked assert in PushTexture() to allow convenience grace period of using a - texture that was queue for destroy during the frame. Make it safe to stick to - an existing texture during the frame. (#9528, #8465) - - Added optional `platform_io.DrawCallback_SetSamplerFromTex` standard backend-agnostic - draw callback for requesting to use the sampler associated already associated to a texture. - Currently only supported by the OpenGL2/3 and SDLRenderer3 backend. (#9378) - - Fixed dangling ImDrawList::_OwnerName when using animated label. (#9552) [@ubi-dcastonguay] +- Widgets: + - Checkbox, Menus: check marks use anti-aliased ends. + - Tweaked rendering in various locations to avoid blurryness: + - Windows: title-bar and menu-bar border (when thickness>1.0f). + - SeparatorText: border (when thickness>1.0f). + - Tree: hierarchy lines (when thickness>1.0f). + - InputText: input caret (when thickness>1.0f). + - TabBar: selected overline border (when thickness>1.0f). - Demo: - Added `Widgets->Mixed Values` section. (#5518, #5677, #6865) + - Custom Rendering section: exposed new flags; showcasing overlapping strokes + and filled shapes; added an option to animate thickness; added new shapes + to showcase new rendering features that previously hit limitations. - Style Editor: fixed style/colors combo box applying style when opening Combo. - Backends: - QNX: added QNX Screen backend. (#9492) [@mgorchak-blackberry] diff --git a/imgui.cpp b/imgui.cpp index e51cde0e3..ddef7ec4d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -395,7 +395,29 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2026/10/07 (1.93.0) - merged ImDrawListFlags into ImDrawFlags. obsoleted ImDrawListFlags (which were rarely used directly): + 2026/10/07 (1.93.0) - large cleanup/refactor of ImDrawList. many issues and inconsistencies fixed! (#9504) + BELOW IS A SIMPLIFIED/SHORTENED RECAP OF CHANGES. READ CHANGELOG AND LINKS ABOVE FOR MORE DETAILS! + useful links: + - ImDrawList 1.92.9 <> 1.93 Interactive Testbed: https://www.dearimgui.com/docs/drawlist_v193 (<-- you can download this locally) + - ImDrawList Wiki Reference: https://github.com/ocornut/imgui/wiki/Draw-List + - Discussion thread: https://github.com/ocornut/imgui/issues/9504 + - Use ImDrawFlags_StrokeLegacy mode to emulate old rendering per-primitive or per-scope. + - AddLine: removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates by this function, and led to lots of inconsistencies. + - This fixes inconsistencies in the API and matches the PathXXX API. + - By default, stroke thickness extends on both side of the given segment. e.g for a "pixel-perfect" looking line with thickness=1.0f, coords should be passed as center of each ends of the line. + - Use `ImDrawFlags_StrokeLegacy` to use old offset if required. Or you can apply the offset manually! + - Generally better, simpler and faster to use `AddLineH()`, `AddLineV()` functions added in 1.92.8. + - IF YOU ARE MINDFUL OF PIXEL-PERFECTNESS IN YOUR CUSTOM RENDERING/WIDGETS read Changelog and links above for details. + - AddRect(), AddCircle(), AddNgon(), AddEllipse(), AddTriangle(), AddQuad(): defaulting to "inside" stroke. All closed shapes with thickness=1.0f will appear identical. The difference for thickness>1.0f shapes may be minimal since very large strokes were not well supported for widgets, but stroke will default inside widgets. + - AddCircle(), AddNgon(): removed +0.5f offset added to radius. This fixes inconsistencies in the API. Use `ImDrawFlags_StrokeLegacy` to use old method if required. Or you can apply the offset manually! + - AddRectFilled(): non-integer coordinates will now display anti-aliased edges. Previously, non-integer coordinates rendered with aliased edges snapped by the rasterizer. + - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible unless using ImDrawList_StrokeLegacy mode. + With inverted coordinates: + - Legacy `AddRect()` rounding off -> visible but incorrect outer size. + - Legacy `AddRect()` rounding on -> visible but very glitchy. + - Legacy `AddRectFilled()` rounding off -> visible and correct. + - Legacy `AddRectFilled()` rounding on -> visible but very glitchy. + - merged ImDrawListFlags into ImDrawFlags. obsoleted ImDrawListFlags (which were rarely used directly): - ImDrawListFlags_AntiAliasedLines -> ImDrawFlags_AALines, - ImDrawListFlags_AntiAliasedFill -> ImDrawFlags_AAFill, - ImDrawListFlags_AllowVtxOffset -> ImDrawFlags_UseVtxOffset, @@ -405,11 +427,11 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ImDrawFlags_RoundCornersAll -> ImDrawFlags_RoundAll, - ImDrawFlags_RoundCornersNone -> ImDrawFlags_RoundNone, - ImDrawFlags_RoundCornersTopLeft -> ImDrawFlags_RoundTopLeft, + - ImDrawFlags_RoundCornersTopRight -> ImDrawFlags_RoundTopRight, - ImDrawFlags_RoundCornersTop -> ImDrawFlags_RoundTop, - ImDrawFlags_RoundCornersBottom -> ImDrawFlags_RoundBottom, - etc. - kept redirection enums (will obsolete). - - obsoleted style.AntiAliasedLinesUseTex which now only makes sense for legacy strokes. + etc. kept redirection enums (will obsolete). + - obsoleted style.AntiAliasedLinesUseTex and ImDrawListFlags_AntiAliasedLinesUseTex, as the new line rendering code always uses textures. - 2026/09/30 (1.93.0) - ImFont: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). (#609, #5748) - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. diff --git a/imgui.h b/imgui.h index f3eeea91f..8296daa49 100644 --- a/imgui.h +++ b/imgui.h @@ -2395,7 +2395,7 @@ struct ImGuiStyle float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. // Rendering & Tessellation - bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). bool AntiAliasedLines; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. bool AntiAliasedLineEnds; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawFlags_AAFill in all draw-lists. float CurveTessellationMaxError; // Maximum error (in pixels) when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. @@ -3337,7 +3337,7 @@ enum ImDrawFlags_ ImDrawFlags_SquareCap = 1 << 11, // OK -- // PathStroke(), AddPolyline(): use square cap line ends. // About Stroke Ends: - // - Rendering is optimized for fast pixel-perfect UI, so line ends are not anti-aliased by default. It cheaper (we can emit less vertices). + // - Rendering is optimized for fast pixel-perfect UI, so line ends are not anti-aliased by default. It's cheaper (we can emit less vertices). // - For more free-form drawings, light graphs and markers, or when using thick strokes: you can turn them on using the ImDrawFlags_AALineEnds flag. // - See 'Demo->Examples->Custom Rendering' to interactively toy with those flags. // - 'OK*' indicates using this at the AddXXX() call site is unlikely: it would only makes sense if (1) the option is disabled in style/scope and (2) you want to forcefully enable it for a single primitives. Possible but unlikely! Only supported for functions taking flags inputs. @@ -3349,12 +3349,12 @@ enum ImDrawFlags_ //ImDrawFlags_NoAALineEnds = 1 << 16, // OK -- // Disable anti-aliasing ends for a given primitive. // About Stroke Position: - // - Read https://github.com/ocornut/imgui/wiki/Draw-List + // - Read https://github.com/ocornut/imgui/wiki/Draw-List (this guide includes a precise list of differences between 1.92.9 and 1.93.0) // - Read https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering // Stroke Position relative to shape outline -- // Prim/Scope? ImDrawFlags_StrokeInside = 1 << 17, // OK -- // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) ImDrawFlags_StrokeCenter = 2 << 17, // OK -- // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) - ImDrawFlags_StrokeCenterBiased = 3 << 17, // OK -- // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! + ImDrawFlags_StrokeCenterBiased = 3 << 17, // OK -- // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and the rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! ImDrawFlags_StrokeOutside = 4 << 17, // OK -- // Draw stroke outside of the shape outline ImDrawFlags_StrokeLegacy = 7 << 17, // OK OK(0) // Use legacy positioning + enable MiterOnly + disable AALineEnds. Must be all bits set. @@ -3368,8 +3368,8 @@ enum ImDrawFlags_ ImDrawFlags_RoundMask_ = ImDrawFlags_RoundAll | ImDrawFlags_RoundNone, // [Internal] ImDrawFlags_AllowInPushScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundMask_, // [Internal] Values allowed in PushDrawFlag() scope. ImDrawFlags_AllowInFrameScope_ = ImDrawFlags_AllowInPushScope_ | ImDrawFlags_AllowTexForRoundCorners_, - ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] - ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. + ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] + ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -3402,7 +3402,7 @@ struct ImDrawList ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector VtxBuffer; // Vertex buffer. - ImDrawFlags Flags; // Current flags for drawing primitives. You may poke into these to adjust anti-aliasing settings per-primitive. Alter with PushDrawFlag(). + ImDrawFlags Flags; // Current flags for drawing primitives. Alter with PushDrawFlag()/PopDrawFlags() to adjust defaults to a given scope. // [Internal, used while building lists] unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. @@ -3571,7 +3571,7 @@ struct ImDrawList IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); IMGUI_API void _SelectLineTexture(float screen_thickness, ImVec2* out_uv0, ImVec2* out_uv1, float* out_fringe, ImDrawFlags flags); IMGUI_API float _CalculateCenterBiasedOffset(float thickness); - IMGUI_API void _AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags, float max_inner_thickness); + IMGUI_API void _AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags, float max_inner_offset); }; // All draw data to render a Dear ImGui frame @@ -3788,7 +3788,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoBakedLines = 1 << 2, // [OBSOLETE] Don't build line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENT ANTI-ALIASED STROKES FROM WORKING AND WILL DISABLE AA. + ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build anti-aliased line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENTS ANTI-ALIASED LINES FROM WORKING AND WILL DISABLE THEM. ImFontAtlasFlags_NoBakedRoundCorners= 1 << 3, // Don't build round corners into the atlas. }; @@ -4317,7 +4317,7 @@ enum ImDrawListFlags_ ImDrawListFlags_None = ImDrawFlags_None, ImDrawListFlags_AntiAliasedFill = ImDrawFlags_AAFill, ImDrawListFlags_AntiAliasedLines = ImDrawFlags_AALines, - ImDrawListFlags_AntiAliasedLinesUseTex = 0, // Only apply to StrokeLegacy mode! + ImDrawListFlags_AntiAliasedLinesUseTex = ImDrawFlags_AALines, // No effect, anti-aliased rendering always uses textures from 1.93+ ImDrawListFlags_AllowVtxOffset = ImDrawFlags_UseVtxOffset, ImDrawListFlags_TextNoPixelSnap = ImDrawFlags_TextNoPixelSnap, }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2f5450e09..29dcb7f91 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10451,8 +10451,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::CheckboxFlags("AALineEnds", &prim_other_flags, ImDrawFlags_AALineEnds); ImGui::SameLine(); ImGui::CheckboxFlags("MiterOnly", &prim_other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); ImGui::CheckboxFlags("SquareCap", &prim_other_flags, ImDrawFlags_SquareCap); - //ImGui::CheckboxFlags("UseTexForRoundCorners", &prim_other_flags, ImDrawFlags_UseTexForRoundCorners); ImGui::SameLine(); - //ImGui::CheckboxFlags("UseTexForStrokeLegacy", &prim_other_flags, ImDrawFlags_UseTexForStrokeLegacy); + //ImGui::CheckboxFlags("UseTexForRoundCorners", &prim_other_flags, ImDrawFlags_UseTexForRoundCorners); static ImDrawFlags scope_flags = draw_list->Flags & ImDrawFlags_AllowInPushScope_; // First init copy current state. ImGui::SeparatorText("Current ImDrawList flags (e.g. PushDrawFlag function)"); @@ -10461,8 +10460,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::CheckboxFlags("AALines", &scope_flags, ImDrawFlags_AALines); ImGui::SameLine(); ImGui::CheckboxFlags("AALineEnds", &scope_flags, ImDrawFlags_AALineEnds); ImGui::SameLine(); ImGui::CheckboxFlags("StrokeLegacy", &scope_flags, ImDrawFlags_StrokeLegacy); - //ImGui::CheckboxFlags("UseTexForRoundCorners", &scope_flags, ImDrawFlags_UseTexForRoundCorners); ImGui::SameLine(); - //ImGui::CheckboxFlags("UseTexForStrokeLegacy", &scope_flags, ImDrawFlags_UseTexForStrokeLegacy); + //ImGui::CheckboxFlags("UseTexForRoundCorners", &scope_flags, ImDrawFlags_UseTexForRoundCorners); ImGui::PopID(); ImGui::Spacing(); @@ -10485,7 +10483,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) for (int side = 0; side < 4; side++) { float t = (float)ImGui::GetTime() * 0.1f + side * pi * 0.5f; - rotating_square[side] = { (float)cosf(t) * half_sz, (float)sin(t) * half_sz }; + rotating_square[side] = { (float)cosf(t) * half_sz, (float)sinf(t) * half_sz }; } float x = start_pos.x; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a696fade0..b92af6f37 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1997,6 +1997,9 @@ void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float th _AddLine(p1, p2, col, thickness, flags); } +// AddLineH(10, 20, 5, col, 1.0f) == AddLine( {10,5.5}, {20,5.5}, col, 1.0f) +// == AddLine( {10,5}, {20,5}, col, 1.0f, ImDrawFlags_StrokeLegacy); // or before 1.93.0 +// Thickness extend inside/bottom by default. Faster than equivalent AddLine() call. void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) @@ -2043,6 +2046,9 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th } } +// AddLineV(5, 10, 20, col, 1.0f) == AddLine( {5.5,10}, {5.5,20}, col, 1.0f) +// == AddLine( {5,10}, {5,20}, col, 1.0f, ImDrawFlags_StrokeLegacy); // or before 1.93.0 +// Thickness extend inside/right by default. Faster than equivalent AddLine() call. void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) @@ -4834,7 +4840,7 @@ static void ImFontAtlasBuildUpdateTexDataBasic(ImFontAtlas* atlas) static int InitCornerGeometry(float cx, float cy, float rounding, float circle_segment_max_error, ImVec2* line_normals, float* line_distances) { - // This tries to quite faithfully replication how we render the corners using tessellation. + // This tries to quite faithfully replicate how we render the corners using tessellation. // Older code sampled a circle SDF directly, but it had clearly visible discrepancy between the baked corners // and tessellated corners due to circle_segment_max_error. @@ -5083,9 +5089,9 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) } { - // Calculate super sampled lin textures for smaller line widths to make transition between sizes smoother. + // Calculate super sampled line textures for smaller line widths to make transition between sizes smoother. - // Calc ramp used for all the textures. + // Calculate ramp used for all the textures. ImU8 ramp[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]; for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; n++) ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.0f); @@ -5102,7 +5108,7 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) // To super 2x sample that signal, we end up with following texture: // [ 0 | .5 | 1 | .5 | 0 ] // :.......................: - // One might think that there should be 2 opaque pixels the the middle section, but no singe we're super sampling the triangle signal. + // One might think that there should be 2 opaque pixels in the middle section, but no since we're super sampling the triangle signal. const int line_width = 1 + n; IM_ASSERT(IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + line_width + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT <= r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels diff --git a/imgui_internal.h b/imgui_internal.h index 1f2e26268..74d91a7d4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -506,7 +506,7 @@ inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } #ifdef IMGUI_ENABLE_SSE inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } -// Converge to more precise solution using single step of Newton-Raphson method, repeating increase precision +// Converge to more precise solution using single step of Newton-Raphson method, repeating increases precision inline float ImRsqrtPrecise(float x) { const float r = _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); return r * (1.5f - x * 0.5f * r * r); } #else inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } @@ -924,7 +924,7 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag #define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) // The maximum line width to bake anti-aliased textures for. #endif #ifndef IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH #define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] From 7bccc3bc1e738d141f9cb2ec16378d9881d422eb Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Aug 2026 16:55:48 +0200 Subject: [PATCH 152/245] DrawList: AddCircle, AddCircleFilled: fixed large circles being under-tessellated (when above ~140 with default CircleTessellationMaxError). --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 12 ++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70a89b246..56be6b6eb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -255,6 +255,8 @@ Other Changes: round corners in font atlas. - Added `ImDrawFlags_UseTexForRoundCorners` flag to enable in scope or per-shape. Added for consistency and debugging, not really needed in practice. + - AddCircle, AddCircleFilled: fixed large circles being under-tessellated + (when above ~140 with default CircleTessellationMaxError). - Improved debug-build performance in various locations. - Improved minor mismatches when overlapping strokes and filled shapes. For example, when using inside strokes, diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b92af6f37..515816da9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2714,7 +2714,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu return; } - if (num_segments <= 0) + if (num_segments <= 0 && outer_radius <= _Data->ArcFastRadiusCutoff) { // Use arc with automatic segment count const int a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(outer_radius); // Use outer_radius for segment count to be consistent with rounded rect. @@ -2723,7 +2723,9 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu } else { - // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + // Explicit segment count or above fast arc cutoff (still clamp to avoid drawing insanely tessellated shapes) + if (num_segments <= 0) + num_segments = _CalcCircleAutoSegmentCount(outer_radius); num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); // Because we are filling a closed shape we remove 1 from the count of segments/points @@ -2756,7 +2758,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, radius = _FringeScale * 0.5f; } - if (num_segments <= 0) + if (num_segments <= 0 && radius <= _Data->ArcFastRadiusCutoff) { // Use arc with automatic segment count _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); @@ -2764,7 +2766,9 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, } else { - // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + // Explicit segment count or above cutoff (still clamp to avoid drawing insanely tessellated shapes) + if (num_segments <= 0) + num_segments = _CalcCircleAutoSegmentCount(radius); num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); // Because we are filling a closed shape we remove 1 from the count of segments/points From cb66fcdaac0a6ca6a904406018529424c585caa9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 5 Aug 2026 23:05:42 +0200 Subject: [PATCH 153/245] DrawList: rename ImDrawFlags_MiterOnly->ImDrawFlags_JoinMiter, ImDrawFlags_SquareCap->ImDrawFlags_CapSquare. --- docs/CHANGELOG.txt | 6 +++--- imgui.h | 6 +++--- imgui_demo.cpp | 4 ++-- imgui_draw.cpp | 44 ++++++++++++++++++++++---------------------- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 56be6b6eb..8b7f2d6a7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -235,18 +235,18 @@ Other Changes: to not enable it by default. This keeps situations such as "throw tens of thousands of lines at ImDrawList" optimal. You can opt-in for a given shape or in a scope using `PushDrawFlag()`. - - Added `ImDrawFlags_MiterOnly` flag to disable using beveled corner. + - Added `ImDrawFlags_JoinMiter` flag to disable using beveled corner. - Closer to legacy rendering and slightly faster, but corners sharper than 90 degrees may expand far out. - Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() functions since we know that the input path does not contain sharper corners. - - Added `ImDrawFlags_SquareCap` flag to extend lines ends using square caps. (#9360) + - Added `ImDrawFlags_CapSquare` flag to extend lines ends using square caps. (#9360) - AddConvexPolyFilled()/PathFillConvex(): improved to handle input geometry more robustly. The rendering of sharp corners was improved. Earlier there were issues with sharp corners either creating long spikes, or messing up the adjacent edge's anti-aliasing. Now the anti-aliasing fringe calculation is more consistent, and sharp corners get bevelled to avoid spikes. There might still be issues when the smallest extent of a long thin polygon - is less than a pixel. Also supports `ImDrawFlags_MiterOnly`, to facilitate matching + is less than a pixel. Also supports `ImDrawFlags_JoinMiter`, to facilitate matching a stroke using the same flag. - AddRect(), AddRectFilled(): various optimizations for rounded rectangles. (#1962, #9504) - Integer-aligned coordinates and thicknesses will automatically use baked textures, diff --git a/imgui.h b/imgui.h index 8296daa49..5c47d94e1 100644 --- a/imgui.h +++ b/imgui.h @@ -3333,8 +3333,8 @@ enum ImDrawFlags_ // Stroke Options ----------------------------- // Prim/Scope? ImDrawFlags_Closed = 1 << 9, // OK -- // PathStroke(), AddPolyline(): specify that shape should be closed. - ImDrawFlags_MiterOnly = 1 << 10, // OK -- // PathStroke(), AddPolyline(): use miter corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. - ImDrawFlags_SquareCap = 1 << 11, // OK -- // PathStroke(), AddPolyline(): use square cap line ends. + ImDrawFlags_JoinMiter = 1 << 10, // OK -- // PathStroke(), AddPolyline(): use miter joins/corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. + ImDrawFlags_CapSquare = 1 << 11, // OK -- // PathStroke(), AddPolyline(): use square cap line ends. // About Stroke Ends: // - Rendering is optimized for fast pixel-perfect UI, so line ends are not anti-aliased by default. It's cheaper (we can emit less vertices). @@ -3356,7 +3356,7 @@ enum ImDrawFlags_ ImDrawFlags_StrokeCenter = 2 << 17, // OK -- // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) ImDrawFlags_StrokeCenterBiased = 3 << 17, // OK -- // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and the rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! ImDrawFlags_StrokeOutside = 4 << 17, // OK -- // Draw stroke outside of the shape outline - ImDrawFlags_StrokeLegacy = 7 << 17, // OK OK(0) // Use legacy positioning + enable MiterOnly + disable AALineEnds. Must be all bits set. + ImDrawFlags_StrokeLegacy = 7 << 17, // OK OK(0) // Use legacy positioning + enable JoinMiter + disable AALineEnds. Must be all bits set. // Other Options ------------------------------ // Prim/Scope? ImDrawFlags_TextNoPixelSnap = 1 << 20, // OK OK(0) // Disable automatically snapping AddText() calls to pixel boundaries. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 29dcb7f91..f1a66034a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10449,8 +10449,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::CheckboxFlags("AAFill", &prim_other_flags, ImDrawFlags_AAFill); ImGui::SameLine(); // Note: Only for functions taking flags. ImGui::CheckboxFlags("AALines", &prim_other_flags, ImDrawFlags_AALines); ImGui::SameLine(); // Note: Only for functions taking flags. ImGui::CheckboxFlags("AALineEnds", &prim_other_flags, ImDrawFlags_AALineEnds); ImGui::SameLine(); - ImGui::CheckboxFlags("MiterOnly", &prim_other_flags, ImDrawFlags_MiterOnly); ImGui::SameLine(); - ImGui::CheckboxFlags("SquareCap", &prim_other_flags, ImDrawFlags_SquareCap); + ImGui::CheckboxFlags("JoinMiter", &prim_other_flags, ImDrawFlags_JoinMiter); ImGui::SameLine(); + ImGui::CheckboxFlags("CapSquare", &prim_other_flags, ImDrawFlags_CapSquare); //ImGui::CheckboxFlags("UseTexForRoundCorners", &prim_other_flags, ImDrawFlags_UseTexForRoundCorners); static ImDrawFlags scope_flags = draw_list->Flags & ImDrawFlags_AllowInPushScope_; // First init copy current state. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 515816da9..76918f2e5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1007,10 +1007,10 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AALineEnds; + flags = (flags | ImDrawFlags_JoinMiter) & ~ImDrawFlags_AALineEnds; const bool closed = (flags & ImDrawFlags_Closed) != 0; - const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; + const bool miters_only = (flags & ImDrawFlags_JoinMiter) != 0; const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) @@ -1076,7 +1076,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 dir.x = n1.y; dir.y = -n1.x; - if (flags & ImDrawFlags_SquareCap) + if (flags & ImDrawFlags_CapSquare) { p1.x -= dir.x * half_thickness; p1.y -= dir.y * half_thickness; @@ -1262,7 +1262,7 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 // End cap dir.x = n1.y; dir.y = -n1.x; - if (flags & ImDrawFlags_SquareCap) + if (flags & ImDrawFlags_CapSquare) { p1.x += dir.x * half_thickness; p1.y += dir.y * half_thickness; @@ -1330,7 +1330,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun { const float half_aa = _FringeScale * 0.5f; ImU32 col_trans = col & ~IM_COL32_A_MASK; - const bool miters_only = (flags & ImDrawFlags_MiterOnly) != 0; + const bool miters_only = (flags & ImDrawFlags_JoinMiter) != 0; const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; const int idx_count = ((points_count - 2) + points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) * 3; @@ -1885,7 +1885,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags = (flags | ImDrawFlags_MiterOnly) & ~ImDrawFlags_AALineEnds; + flags = (flags | ImDrawFlags_JoinMiter) & ~ImDrawFlags_AALineEnds; float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) if (stroke_pos == ImDrawFlags_StrokeOutside) @@ -1914,7 +1914,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t float p1_y = p1.y; float p2_x = p2.x; float p2_y = p2.y; - if (flags & ImDrawFlags_SquareCap) + if (flags & ImDrawFlags_CapSquare) { p1_x -= dir_x * half_thickness; p1_y -= dir_y * half_thickness; @@ -2022,7 +2022,7 @@ void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float th top_y -= thickness; const bool is_truncated = IM_IS_TRUNCATED4(min_x, max_x, top_y, thickness); - if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_SquareCap) == 0) + if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_CapSquare) == 0) { if (thickness < _FringeScale) IM_UNLIKELY { @@ -2071,7 +2071,7 @@ void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float th left_x -= thickness; const bool is_truncated = IM_IS_TRUNCATED4(left_x, min_y, max_y, thickness); - if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_SquareCap) == 0) + if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_CapSquare) == 0) { if (thickness < _FringeScale) IM_UNLIKELY { @@ -2352,7 +2352,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.50f, p_max.y - 0.50f), rounding, flags); else PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.49f, p_max.y - 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeCenter | (flags & ~ImDrawFlags_StrokeMask_)); + PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | ImDrawFlags_StrokeCenter | (flags & ~ImDrawFlags_StrokeMask_)); return; } @@ -2452,7 +2452,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if (!has_rounding || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) { const ImVec2 points[4] = { outer_min, ImVec2(outer_max.x, outer_min.y), outer_max, ImVec2(outer_min.x, outer_max.y) }; - _AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside, half_min_dim); + _AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | ImDrawFlags_StrokeInside, half_min_dim); _Path.Size = 0; } else @@ -2474,7 +2474,7 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl PathArcToFast(ImVec2(outer_max.x - rounding_br, outer_max.y - rounding_br), rounding_br, 0, 3); PathArcToFast(ImVec2(outer_min.x + rounding_bl, outer_max.y - rounding_bl), rounding_bl, 3, 6); - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_), half_min_dim); + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_), half_min_dim); _Path.Size = 0; } } @@ -2553,7 +2553,7 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c height = _FringeScale; } const ImVec2 points[4] = { p_min, ImVec2(p_min.x + width, p_min.y), ImVec2(p_min.x + width, p_min.y + height), ImVec2(p_min.x, p_min.y + height) }; - AddConvexPolyFilled(points, 4, col, ImDrawFlags_MiterOnly); + AddConvexPolyFilled(points, 4, col, ImDrawFlags_JoinMiter); return; } @@ -2605,12 +2605,12 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c if (!has_rounding) { const ImVec2 points[4] = { p_min, ImVec2(p_max.x, p_min.y), p_max, ImVec2(p_min.x, p_max.y) }; - AddConvexPolyFilled(points, 4, col, ImDrawFlags_MiterOnly); + AddConvexPolyFilled(points, 4, col, ImDrawFlags_JoinMiter); } else { PathRect(p_min, p_max, rounding, flags); - PathFillConvex(col, ImDrawFlags_MiterOnly); + PathFillConvex(col, ImDrawFlags_JoinMiter); } } @@ -2740,7 +2740,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu // This will be used by _AddPolyline() to clamp the inner stroke expansion, to avoid creating rendering artifacts. const float unit_apothem = ApproxApothem(_Path.Size); const float edge_dist = radius * unit_apothem; - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos, edge_dist); + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, edge_dist); _Path.Size = 0; } @@ -2776,7 +2776,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); } - PathFillConvex(col, ImDrawFlags_MiterOnly); + PathFillConvex(col, ImDrawFlags_JoinMiter); } // Guaranteed to honor 'num_segments' @@ -2822,7 +2822,7 @@ void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_ // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos, edge_dist); + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, edge_dist); _Path.Size = 0; } @@ -2844,7 +2844,7 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); - PathFillConvex(col, ImDrawFlags_MiterOnly); + PathFillConvex(col, ImDrawFlags_JoinMiter); } // Ellipse @@ -2872,7 +2872,7 @@ void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 co // Prevent the inside part of the stroke to be expanded too much to prevent some rendering artifacts. const float max_inner_offset = ImMin(rad.x, rad.y); - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_MiterOnly | stroke_pos, max_inner_offset); + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, max_inner_offset); _Path.Size = 0; } @@ -3019,7 +3019,7 @@ void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, cons int vert_start_idx = VtxBuffer.Size; PathRect(p_min, p_max, rounding, flags); - PathFillConvex(col, ImDrawFlags_MiterOnly); + PathFillConvex(col, ImDrawFlags_JoinMiter); int vert_end_idx = VtxBuffer.Size; ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); @@ -7679,7 +7679,7 @@ void ImGui::RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e); // BR } } - draw_list->PathFillConvex(col, ImDrawFlags_MiterOnly); + draw_list->PathFillConvex(col, ImDrawFlags_JoinMiter); } void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding) From f84d77c424249b9d3438aa8cca0b57f11b5f0450 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Aug 2026 18:09:43 +0200 Subject: [PATCH 154/245] DrawList: changed _GetStrokePos() to a macro. --- imgui_draw.cpp | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 76918f2e5..0562635d7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -936,12 +936,7 @@ void ImDrawList::_SelectLineTexture(float screen_thickness, ImVec2* out_uv0, ImV } } -static inline ImDrawFlags _GetStrokePos(ImDrawFlags flags, ImDrawFlags default_stroke_pos) -{ - if (flags & ImDrawFlags_StrokeMask_) - return (flags & ImDrawFlags_StrokeMask_); - return default_stroke_pos; -} +#define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) (((_FLAGS) & ImDrawFlags_StrokeMask_) ? ((_FLAGS) & ImDrawFlags_StrokeMask_) : _DEFAULT_STROKE_POS) IM_MSVC_RUNTIME_CHECKS_RESTORE @@ -1052,7 +1047,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 } const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. - const float half_thickness = thickness * 0.5f; const bool use_aa_ends = (flags & (ImDrawFlags_AALines | ImDrawFlags_AALineEnds)) == (ImDrawFlags_AALines | ImDrawFlags_AALineEnds); const int first_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); @@ -1078,8 +1072,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 dir.y = -n1.x; if (flags & ImDrawFlags_CapSquare) { - p1.x -= dir.x * half_thickness; - p1.y -= dir.y * half_thickness; + p1.x -= dir.x * thickness * 0.5f; + p1.y -= dir.y * thickness * 0.5f; } if (!use_aa_ends) @@ -1245,7 +1239,6 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 // Connect prev to next IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - base_idx = next_base_idx; } @@ -1264,8 +1257,8 @@ void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU3 dir.y = -n1.x; if (flags & ImDrawFlags_CapSquare) { - p1.x += dir.x * half_thickness; - p1.y += dir.y * half_thickness; + p1.x += dir.x * thickness * 0.5f; + p1.y += dir.y * thickness * 0.5f; } if (!use_aa_ends) @@ -1894,13 +1887,12 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t thickness0 = _CalculateCenterBiasedOffset(thickness) + fringe * 0.5f; else if (stroke_pos == ImDrawFlags_StrokeInside) thickness0 = fringe * 0.5f; - float thickness1 = (thickness + fringe) - thickness0; + const float thickness1 = (thickness + fringe) - thickness0; - const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offets. + const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offsets. const ImVec2 uv2(uv0.x + (uv1.x - uv0.x) * ratio, uv0.y); const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. - const float half_thickness = thickness * 0.5f; const bool use_aa_ends = (flags & (ImDrawFlags_AALines | ImDrawFlags_AALineEnds)) == (ImDrawFlags_AALines | ImDrawFlags_AALineEnds); if (!use_aa_ends) @@ -1916,6 +1908,7 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t float p2_y = p2.y; if (flags & ImDrawFlags_CapSquare) { + const float half_thickness = thickness * 0.5f; p1_x -= dir_x * half_thickness; p1_y -= dir_y * half_thickness; p2_x += dir_x * half_thickness; @@ -1928,7 +1921,6 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(p1_x - norm_x * thickness0, p1_y - norm_y * thickness0, uv0, col); IM_APPEND_VTX(p1_x + norm_x * thickness1, p1_y + norm_y * thickness1, uv1, col); - IM_APPEND_VTX(p2_x - norm_x * thickness0, p2_y - norm_y * thickness0, uv0, col); IM_APPEND_VTX(p2_x + norm_x * thickness1, p2_y + norm_y * thickness1, uv1, col); @@ -1966,7 +1958,6 @@ void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float t next_base_idx = (int)_VtxCurrentIdx; IM_APPEND_VTX(pa_x - norm_x * thickness0, pa_y - norm_y * thickness0, uv0, col); IM_APPEND_VTX(pa_x + norm_x * thickness1, pa_y + norm_y * thickness1, uv1, col); - IM_APPEND_VTX(pb_x - norm_x * thickness0, pb_y - norm_y * thickness0, uv0, col_trans); IM_APPEND_VTX(pb_x + norm_x * thickness1, pb_y + norm_y * thickness1, uv1, col_trans); From d23a638613a5ab23fae38b595aadc2983c736eab Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 6 Aug 2026 15:58:15 +0200 Subject: [PATCH 155/245] Demo: Custom Rendering: added zig-zag concave shape, tweak color, tidy up section. Demo: Custom Rendering: tweak animated rounding. --- imgui_demo.cpp | 196 ++++++++++++++++++++++++++----------------------- 1 file changed, 106 insertions(+), 90 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f1a66034a..5078c11d7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -10338,13 +10338,10 @@ static void ShowExampleAppWindowTitles(bool*) // [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() //----------------------------------------------------------------------------- -// Add a |_| looking shape -static void PathConcaveShape(ImDrawList* draw_list, float x, float y, float sz) -{ - const ImVec2 pos_norms[] = { { 0.0f, 0.0f }, { 0.3f, 0.0f }, { 0.3f, 0.7f }, { 0.7f, 0.7f }, { 0.7f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; - for (const ImVec2& p : pos_norms) - draw_list->PathLineTo(ImVec2(x + 0.5f + (int)(sz * p.x), y + 0.5f + (int)(sz * p.y))); -} +// See our Wiki guides: +// - ImDrawList Vector Rendering Reference: https://github.com/ocornut/imgui/wiki/Draw-List +// - Pixel Perfect Anti-aliased Rendering: https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering +// - How Anti-aliased Polyline Rendering is Implemented: https://github.com/ocornut/imgui/wiki/Polyline-Rendering // Demonstrate using the low-level ImDrawList to draw custom shapes. static void ShowExampleAppCustomRendering(bool* p_open) @@ -10376,20 +10373,16 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Text("Gradients"); ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); { - ImVec2 p0 = ImGui::GetCursorScreenPos(); - ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); + ImGui::InvisibleButton("##gradient1", gradient_size); ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255)); ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255)); - draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); - ImGui::InvisibleButton("##gradient1", gradient_size); + draw_list->AddRectFilledMultiColor(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), col_a, col_b, col_b, col_a); } { - ImVec2 p0 = ImGui::GetCursorScreenPos(); - ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); + ImGui::InvisibleButton("##gradient2", gradient_size); ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255)); ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255)); - draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); - ImGui::InvisibleButton("##gradient2", gradient_size); + draw_list->AddRectFilledMultiColor(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), col_a, col_b, col_b, col_a); } // Draw a bunch of primitives @@ -10404,36 +10397,32 @@ static void ShowExampleAppCustomRendering(bool* p_open) static int circle_segments_override_v = 12; static bool curve_segments_override = false; static int curve_segments_override_v = 8; - static ImVec4 colf_stroke = ImVec4(1.00f, 1.00f, 0.40f, 1.0f); - static ImVec4 colf_fill = ImVec4(0.70f, 0.18f, 0.62f, 1.0f); + static ImVec4 colf_stroke = ImVec4(1.000f, 0.384f, 0.169f, 1.000f); + static ImVec4 colf_fill = ImVec4(0.416f, 0.378f, 0.420f, 1.000f); ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); - const float rounding_anim_period = 8.0f; + const float rounding_anim_period = 3.0f; const float rounding_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), rounding_anim_period) * (2.0f / rounding_anim_period) - 1.0f); - const float rounding = animate_rounding ? (float)((int)(rounding_wave * base_rounding * 10.0f)) / 10.0f : base_rounding; - ImGui::DragFloat("Rounding", &base_rounding, 0.02f, 0.0f, 30.0f, "%.02f"); - ImGui::SameLine(); - ImGui::Checkbox("Animate##rounding", &animate_rounding); - ImGui::SameLine(); + const float rounding = animate_rounding ? (float)(int)(rounding_wave * base_rounding * 10.0f) / 10.0f : base_rounding; // Sub-integer rounding works but has discontinuities in small values, so best disable we + ImGui::DragFloat("Rounding", &base_rounding, 0.02f, 0.0f, 32.0f, "%.1f"); ImGui::SameLine(); + ImGui::Checkbox("Animate##rounding", &animate_rounding); ImGui::SameLine(); ImGui::Text("%.2f", rounding); const float thickness_anim_period = 5.0f; const float thickness_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), thickness_anim_period) * (2.0f / thickness_anim_period) - 1.0f); const float thickness = animate_thickness ? thickness_wave * base_thickness : base_thickness; - ImGui::DragFloat("Thickness", &base_thickness, 0.02f, 0.0f, 30.0f, "%.02f"); - ImGui::SameLine(); - ImGui::Checkbox("Animate##thickness", &animate_thickness); - ImGui::SameLine(); + ImGui::DragFloat("Thickness", &base_thickness, 0.02f, 0.0f, 32.0f, "%.02f"); ImGui::SameLine(); + ImGui::Checkbox("Animate##thickness", &animate_thickness); ImGui::SameLine(); ImGui::Text("%.2f", thickness); ImGui::SliderInt("N-gon sides", &ngon_segments, 3, 12); - ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); + ImGui::Checkbox("##CircleSegmentOverride", &circle_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); - circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 40); - ImGui::Checkbox("##curvessegmentoverride", &curve_segments_override); + circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 30); + ImGui::Checkbox("##CurvesSegmentOverride", &curve_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); - curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); + curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 30); ImGui::ColorEdit4("Stroke Color", &colf_stroke.x); ImGui::ColorEdit4("Fill Color", &colf_fill.x); @@ -10467,18 +10456,18 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->PushDrawFlag(ImDrawFlags_AllowInPushScope_, false); // Reset all existing (very unusual: done for this demo) draw_list->PushDrawFlag(scope_flags, true); const ImDrawFlags flags = prim_stroke_flags | prim_other_flags; - const ImDrawFlags fill_flags = flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners); - ImVec2 start_pos = ImGui::GetCursorScreenPos(); + const ImVec2 start_pos = ImGui::GetCursorScreenPos(); const float pi = 3.141592f; - const float spacing = 10.0f; + const float step = sz + 10.0f; const ImDrawFlags corners_tl_br = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundBottomRight; const float half_sz = sz * 0.5f; - const float half_szi = (float)(int)(sz * 0.5f); const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; - const ImVec2 cp3[3] = { ImVec2(0.0f, sz * 0.6f), ImVec2(sz * 0.5f, -sz * 0.4f), ImVec2(sz, sz) }; // Control points for curves - const ImVec2 cp4[4] = { ImVec2(0.0f, 0.0f), ImVec2(sz * 1.3f, sz * 0.3f), ImVec2(sz - sz * 1.3f, sz - sz * 0.3f), ImVec2(sz, sz) }; + const ImVec2 cp3[3] = { { 0.0f, sz * 0.6f }, { sz * 0.5f, -sz * 0.4f }, { sz, sz } }; // Control points for curves + const ImVec2 cp4[4] = { { 0.0f, 0.0f }, { sz * 1.3f, sz * 0.3f }, { sz - sz * 1.3f, sz - sz * 0.3f }, { sz, sz } }; + const ImVec2 concave_shape[] = { { 0.0f, 0.0f }, { 0.3f, 0.0f }, { 0.3f, 0.7f }, { 0.7f, 0.7f }, { 0.7f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; // |_| looking shape. Normalized. + const ImVec2 zigzag_shape[] = { { 0.0f, 0.0f }, { 0.9f, 0.0f }, { 1.0f, 0.1f }, { 1.0f, 0.9f }, { 0.9f, 1.0f }, { 0.3f, 1.0f }, { 0.3f, 0.4f }, { 0.9f, 0.4f } }; ImVec2 rotating_square[4]; for (int side = 0; side < 4; side++) { @@ -10497,46 +10486,57 @@ static void ShowExampleAppCustomRendering(bool* p_open) { // FILLED SHAPES const ImU32 col = ImColor(colf_fill); - draw_list->AddNgonFilled({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments); x += sz + spacing; // N-gon - draw_list->AddCircleFilled({ x + half_sz, y + half_sz }, half_sz, col, circle_segments); x += sz + spacing; // Circle - draw_list->AddEllipseFilled({ x + half_sz, y + half_sz }, { sz * 0.5f, sz * 0.3f }, col, -0.3f, circle_segments); x += sz + spacing;// Ellipse - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, 0.0f, fill_flags); x += sz + spacing; // Square - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, fill_flags); x += sz + spacing; // Square with all rounded corners - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, corners_tl_br | fill_flags); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangleFilled({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col); x += sz + spacing; // Triangle - draw_list->AddTriangleFilled({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col); x += (float)(int)(sz * 0.4f) + spacing; // Thin triangle - PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape - draw_list->AddRectFilled({ x, y }, { x + sz, y + thickness }, col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled({ x, y }, { x + thickness, y + sz }, col); x += half_szi + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) + draw_list->AddNgonFilled({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments); x += step; // N-gon + draw_list->AddCircleFilled({ x + half_sz, y + half_sz }, half_sz, col, circle_segments); x += step; // Circle + draw_list->AddEllipseFilled({ x + half_sz, y + half_sz }, { half_sz, sz * 0.3f }, col, -0.3f, circle_segments); x += step;// Ellipse + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, 0.0f, flags); x += step; // Square + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, flags); x += step; // Square with all rounded corners + draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, flags | corners_tl_br); x += step; // Square with two rounded corners + draw_list->AddTriangleFilled({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col); x += step; // Triangle + draw_list->AddTriangleFilled({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col); x += step - (float)(int)(sz * 0.6f); // Thin triangle + + // Concave shape: U + for (const ImVec2& p : concave_shape) + draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); + draw_list->PathFillConcave(col); + x += step; + + // Concave shape: Zig-Zag with sharp angles (see difference with/without JoinMiter) + for (const ImVec2& p : zigzag_shape) + draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); + draw_list->PathFillConcave(col); + x += step; + + // Horizontal/Vertical lines + // (here for consistency with the strokes section. AddRectFilled() is roughly close to AddLineH(), AddLineV() + draw_list->AddRectFilled({ x, y }, { x + sz, y + thickness }, col); x += step; + draw_list->AddRectFilled({ x, y }, { x + thickness, y + sz }, col); x += step - (float)(int)half_sz; if (!(draw_fill && draw_strokes)) //-V560 - { - draw_list->AddRectFilled({ x + 0, y }, { x + 0 + 1, y + 1 }, col); // Pixels (faster than AddLine) - draw_list->AddRectFilled({ x + 2, y }, { x + 2 + 2, y + 2 }, col); - draw_list->AddRectFilled({ x + 5, y }, { x + 5 + 3, y + 3 }, col); - } - x += spacing + sz; + for (int block_sz = 1, off = 0; block_sz < 16 && off + block_sz <= sz; off += block_sz + 1, block_sz++) + draw_list->AddRectFilled({ x, y + off }, { x + block_sz, y + off + block_sz }, col); + x += step - (float)(int)half_sz; // Rotating square for (int n = 0; n < 4; n++) draw_list->PathLineTo({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }); draw_list->PathFillConvex(col, flags); - x += sz + spacing; + x += step; // Path - draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi); + draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi * 1.1f); draw_list->PathFillConvex(col); - x += sz + spacing; + x += step; // Quadratic Bezier Curve (3 control points) draw_list->PathLineTo({ x + cp3[0].x, y + cp3[0].y }); draw_list->PathBezierQuadraticCurveTo({ x + cp3[1].x, y + cp3[1].y }, { x + cp3[2].x, y + cp3[2].y }, curve_segments); draw_list->PathFillConvex(col); - x += sz + spacing; + x += step; if (!(draw_fill && draw_strokes)) //-V560 { draw_list->AddRectFilledMultiColor({ x, y }, { x + sz, y + sz }, IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); - x += sz + spacing; + x += step; } } if (draw_fill && draw_strokes) @@ -10547,28 +10547,41 @@ static void ShowExampleAppCustomRendering(bool* p_open) // First row uses a thickness of 1.0f, second row uses the configurable thickness const ImU32 col = ImColor(colf_stroke); float th = (row == 0) ? 1.0f : thickness; - draw_list->AddNgon({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments, th, flags); x += sz + spacing; // N-gon - draw_list->AddCircle({ x + half_sz, y + half_sz }, half_sz, col, circle_segments, th, flags); x += sz + spacing; // Circle - draw_list->AddEllipse({ x + half_sz, y + half_sz }, { sz * 0.5f, sz * 0.3f }, col, -0.3f, circle_segments, th, flags); x += sz + spacing; // Ellipse - draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, 0.0f, th, flags); x += sz + spacing; // Square - draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags); x += sz + spacing; // Square with all rounded corners - draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags | corners_tl_br); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangle({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col, th, flags); x += sz + spacing; // Triangle - draw_list->AddTriangle({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col, th, flags); x += (float)(int)(sz * 0.4f) + spacing; // Thin triangle - PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); x += sz + spacing; // Concave Shape - //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); + draw_list->AddNgon({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments, th, flags); x += step; // N-gon + draw_list->AddCircle({ x + half_sz, y + half_sz }, half_sz, col, circle_segments, th, flags); x += step; // Circle + draw_list->AddEllipse({ x + half_sz, y + half_sz }, { half_sz, sz * 0.3f }, col, -0.3f, circle_segments, th, flags); x += step; // Ellipse + draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, 0.0f, th, flags); x += step; // Square + draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags); x += step; // Square with all rounded corners + draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags | corners_tl_br); x += step; // Square with two rounded corners + draw_list->AddTriangle({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col, th, flags); x += step; // Triangle + draw_list->AddTriangle({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col, th, flags); x += step - (float)(int)(sz * 0.6f); // Thin triangle - draw_list->AddLineH(x, x + sz, y, col, th, flags); // Horizontal line - draw_list->AddLine({ x, y + half_szi }, { x + sz, y + half_szi }, col, th, flags); - x += sz + spacing; + // Concave shape: U + for (const ImVec2& p : concave_shape) + draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); + draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); + x += step; - draw_list->AddLineV(x, y, y + sz, col, th, flags); // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine({ x + half_szi, y + sz }, { x + half_szi, y }, col, th, flags); - x += half_sz + spacing; + // Concave shape: Zig-Zag with sharp angles (see difference with/without JoinMiter) + for (const ImVec2& p : zigzag_shape) + draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); + draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); + x += step; + // Horizontal/Vertical/Diagonal lines + const float off = (float)(int)(sz * 0.4f); + draw_list->AddLineH(x, x + sz, y, col, th, flags); + draw_list->AddLine({ x, y + off }, { x + sz, y + off }, col, th, flags); + x += step; + draw_list->AddLineV(x, y, y + sz, col, th, flags); + draw_list->AddLine({ x + off, y + sz }, { x + off, y }, col, th, flags); + x += step - (float)(int)half_sz; if (!(draw_fill && draw_strokes)) //-V560 - draw_list->AddLine({ x, y }, { x + sz, y + sz }, col, th, flags); // Diagonal line - x += sz + spacing; + { + draw_list->AddLine({ x, y }, { x + half_sz, y + sz }, col, th, flags); + draw_list->AddLine({ x, y + sz }, { x + half_sz, y }, col, th, flags); + } + x += step - (float)(int)half_sz; // Rotating square for (int n = 0; n < 4; n++) @@ -10576,31 +10589,34 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); //for (int n = 0; n < 4; n++) // ...made of individual line // draw_list->AddLine({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }, { x + half_sz + rotating_square[(n + 1) & 3].x, y + half_sz + rotating_square[(n + 1) & 3].y }, col, th, flags); - x += sz + spacing; + x += step; // Path - draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi); + draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi * 1.1f); draw_list->PathStroke(col, th, flags); - x += sz + spacing; + x += step; // Quadratic Bezier Curve (3 control points) draw_list->AddBezierQuadratic({ x + cp3[0].x, y + cp3[0].y }, { x + cp3[1].x, y + cp3[1].y }, { x + cp3[2].x, y + cp3[2].y }, col, th, curve_segments, flags); - x += sz + spacing; + x += step; // Cubic Bezier Curve (4 control points) if (!(draw_fill && draw_strokes)) //-V560 { draw_list->AddBezierCubic({ x + cp4[0].x, y + cp4[0].y }, { x + cp4[1].x, y + cp4[1].y }, { x + cp4[2].x, y + cp4[2].y }, { x + cp4[3].x, y + cp4[3].y }, col, th, curve_segments, flags); - x += sz + spacing; + x += step; } } - y += sz + spacing; + y += step; } - ImGui::Dummy(ImVec2((sz + spacing) * 15.0f, (sz + spacing) * 4.0f)); + ImGui::Dummy(ImVec2(step * 15.5f, step * 4.0f)); draw_list->PopDrawFlag(); draw_list->PopDrawFlag(); + ImGui::Text("ImDrawList Vector Rendering Reference:"); + ImGui::TextLinkOpenURL("https://github.com/ocornut/imgui/wiki/Draw-List"); + ImGui::PopItemFlag(); ImGui::PopItemWidth(); ImGui::EndTabItem(); @@ -10734,9 +10750,9 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Text("Blue shape is drawn first: appears in back"); ImGui::Text("Red shape is drawn after: appears in front"); ImVec2 p0 = ImGui::GetCursorScreenPos(); - draw_list->AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)); // Blue - draw_list->AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)); // Red - ImGui::Dummy(ImVec2(75, 75)); + draw_list->AddRectFilled({ p0.x, p0.y }, { p0.x + 50, p0.y + 50 }, IM_COL32(0, 0, 255, 255)); // Blue + draw_list->AddRectFilled({ p0.x + 25, p0.y + 25 }, { p0.x + 75, p0.y + 75 }, IM_COL32(255, 0, 0, 255)); // Red + ImGui::Dummy({ 75, 75 }); } ImGui::Separator(); { @@ -10748,14 +10764,14 @@ static void ShowExampleAppCustomRendering(bool* p_open) // You can create any number of channels. Tables API use 1 channel per column in order to better batch draw calls. draw_list->ChannelsSplit(2); draw_list->ChannelsSetCurrent(1); - draw_list->AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)); // Blue + draw_list->AddRectFilled({ p1.x, p1.y }, { p1.x + 50, p1.y + 50 }, IM_COL32(0, 0, 255, 255)); // Blue draw_list->ChannelsSetCurrent(0); - draw_list->AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)); // Red + draw_list->AddRectFilled({ p1.x + 25, p1.y + 25 }, { p1.x + 75, p1.y + 75 }, IM_COL32(255, 0, 0, 255)); // Red // Flatten/reorder channels. Red shape is in channel 0 and it appears below the Blue shape in channel 1. // This works by copying draw indices only (vertices are not copied). draw_list->ChannelsMerge(); - ImGui::Dummy(ImVec2(75, 75)); + ImGui::Dummy({ 75, 75 }); ImGui::Text("After reordering, contents of channel 0 appears below channel 1."); } ImGui::EndTabItem(); From 9e5e0bf9b258d40669617028107d5eaac5ca4306 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Thu, 6 Aug 2026 19:52:54 +0300 Subject: [PATCH 156/245] DrawList: added explanation for IM_POLYLINE_CONVEX_POLY_MAX_BEVELS. --- imgui_draw.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0562635d7..db3d003d9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -880,9 +880,20 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE #define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) #define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0 +// - The miter limit describes how much the miter cross section can be scaled before we turn it into a bevel instead. +// The minimum value of miter limit is 1.0, which translates to 180 (all corners are bevels), the higher the number, +// the closer to zero the angle is (never bevel a corner). The miter limit angle can be calculated as: +// miter_limit_angle = 2 * acos(1 / miter_limit) +// - We can use the miter limit angle to figure maximum number of beveled corners in a convex polygon, +// to prevent having allocate much extra memory (for a reasonable miter limit). +// (n - 2) * 360 > k * miter_limit_angle + (n - k) * 360 +// Where, n = number of corners in a polygon, k = beveled corners. Solved for k, simplifies to: +// k < 360 / (180 - miter_limit_angle) +// To find value strictly less than: +// max_bevels = k = floor(360/(180-miter_limit_angle)) #define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // Safeguard for miter corner calculation to avoid div by zero. cos(179.5) -#define IM_POLYLINE_MITER_LIMIT (4.0f) // How much the miter can be scaled before we turn it into a bevel instead. (equals ~29 deg corner) -#define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // How many bevels there can be in a convex polygon. (int)(360/floor(180-29)) +#define IM_POLYLINE_MITER_LIMIT (4.0f) // (~29 deg corner) +#define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // For miter value 4.0 // In debug builds the functions are likely not inlined, so inlined check is cheaper. #if defined(DEBUG) || defined(_DEBUG) From cbf4f054197ed439c7010bec62dedeff3c96cc87 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 2 Oct 2026 13:04:33 +0200 Subject: [PATCH 157/245] DrawList: added io.ConfigDebugDrawListDefaultsToStrokeLegacy. (#9504) --- docs/CHANGELOG.txt | 12 ++++++++++++ imgui.cpp | 8 +++++++- imgui.h | 5 +++++ imgui_demo.cpp | 4 ++++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8b7f2d6a7..63c7ed07b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,12 @@ While the current version doesn't make lots of visible use of the new features a facilities, they are among the pillars that will make it easier to create prettier contents, both for custom rendering and future versions of the library. +Use `ImDrawFlags_StrokeLegacy` mode to emulate old rendering: +- Per-primitive: draw_list->AddLine(..., ..., ImDrawFlags_StrokeLegacy); +- For a given scope: draw_list->PushDrawFlag(ImDrawFlags_StrokeLegacy, true); draw_list->AddLine(...); draw_list->PopDrawFlag(); +- Globally: ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); // Map to a checkbox +- Globally: io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on Shift + Main work courtesy of @memononen. Additional work/reviewing/guidance by @ocornut. With legacy bits from @thedmd, @potocpav. @@ -224,6 +230,12 @@ Other Changes: - All functions: new rendering code fixes some inconsistencies between graphics APIs (e.g. DirectX vs OpenGL) which are using different diamond exits rules. New code should work precisely the same regardless of graphics API. (#3116, #3258, #2441) [@memononen] + - Debug: added `io.ConfigDebugDrawListDefaultsToStrokeLegacy` to facilitate comparing old/new + behaviors. This is equivalent to calling `PushDrawFlag(ImDrawFlags_StrokeLegacy, true)` + on every drawlist. + Suggested uses, e.g. + - `io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on holding Shift` + - `ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy);` - Added `ImDrawFlags_AALineEnds` flag to enable anti-aliased line ends. - Most noticeable for thick lines. - Also helps fill minor gaps if combining multiple individual lines. For best looking diff --git a/imgui.cpp b/imgui.cpp index ddef7ec4d..5b7d0c068 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -401,7 +401,11 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - ImDrawList 1.92.9 <> 1.93 Interactive Testbed: https://www.dearimgui.com/docs/drawlist_v193 (<-- you can download this locally) - ImDrawList Wiki Reference: https://github.com/ocornut/imgui/wiki/Draw-List - Discussion thread: https://github.com/ocornut/imgui/issues/9504 - - Use ImDrawFlags_StrokeLegacy mode to emulate old rendering per-primitive or per-scope. + - use ImDrawFlags_StrokeLegacy mode to emulate old rendering: + - Per-primitive: draw_list->AddLine(..., ..., ImDrawFlags_StrokeLegacy); + - For a given scope: draw_list->PushDrawFlag(ImDrawFlags_StrokeLegacy, true); draw_list->AddLine(...); draw_list->PopDrawFlag(); + - Globally: ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); // Map to a checkbox + - Globally: io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on Shift - AddLine: removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates by this function, and led to lots of inconsistencies. - This fixes inconsistencies in the API and matches the PathXXX API. - By default, stroke thickness extends on both side of the given segment. e.g for a "pixel-perfect" looking line with thickness=1.0f, coords should be passed as center of each ends of the line. @@ -5663,6 +5667,8 @@ static void SetupDrawListSharedData() g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALines; if (g.Style.AntiAliasedLineEnds) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALineEnds; + if (g.IO.ConfigDebugDrawListDefaultsToStrokeLegacy) + g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_StrokeLegacy; if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) diff --git a/imgui.h b/imgui.h index 5c47d94e1..acce04d3f 100644 --- a/imgui.h +++ b/imgui.h @@ -2559,6 +2559,11 @@ struct ImGuiIO // - Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. + // Option to compare < 1.93.0 rendering details vs 1.93.0 rendering details. (#9504) + // - Equivalent to calling PushDrawFlag(ImDrawList_StrokeLegacy,true) on every draw list instances. + // - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier + bool ConfigDebugDrawListDefaultsToStrokeLegacy; // false // Default all ImDrawList to ImDrawList_StrokeLegacy mode, mimicking pre-1.93.0 rendering. + //------------------------------------------------------------------ // Platform Identifiers // (the imgui_impl_xxxx backend files are setting those up for you) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5078c11d7..97038f1e0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -576,6 +576,8 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SameLine(); HelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running."); ImGui::Checkbox("io.ConfigDebugIgnoreFocusLoss", &io.ConfigDebugIgnoreFocusLoss); ImGui::SameLine(); HelpMarker("Option to deactivate io.AddFocusEvent(false) handling. May facilitate interactions with a debugger when focus loss leads to clearing inputs data."); + ImGui::Checkbox("io.ConfigDebugDrawListDefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); + ImGui::SameLine(); HelpMarker("Option to default all ImDrawList to ImDrawFlags_StrokeLegacy mode, mimicking pre-1.93.0 rendering."); ImGui::Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings); ImGui::SameLine(); HelpMarker("Option to save .ini data with extra comments (particularly helpful for Docking, but makes saving slower)."); @@ -8924,6 +8926,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) #endif Checkbox("Anti-aliased fill", &style.AntiAliasedFill); + Checkbox("Debug: DrawList Defaults to _StrokeLegacy", &ImGui::GetIO().ConfigDebugDrawListDefaultsToStrokeLegacy); + PushItemWidth(GetFontSize() * 8); DragFloat("Curve Tessellation Max Error", &style.CurveTessellationMaxError, 0.02f, 0.10f, 10.0f, "%.2f"); if (style.CurveTessellationMaxError < 0.10f) From 75ac1ab2c36c988f86067434fd3f178fe0fb4097 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 6 Oct 2026 20:36:23 +0200 Subject: [PATCH 158/245] DrawList: AddCircle: fixed issue not clearing path in unlikely case where Path.Size<3. --- imgui_draw.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index db3d003d9..4cf094c57 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2735,14 +2735,14 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); } - if (_Path.Size < 3) - return; - - // Calculate distance to the edge of the polygon describing the circle. - // This will be used by _AddPolyline() to clamp the inner stroke expansion, to avoid creating rendering artifacts. - const float unit_apothem = ApproxApothem(_Path.Size); - const float edge_dist = radius * unit_apothem; - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, edge_dist); + if (_Path.Size >= 3) + { + // Calculate distance to the edge of the polygon describing the circle. + // This will be used by _AddPolyline() to clamp the inner stroke expansion, to avoid creating rendering artifacts. + const float unit_apothem = ApproxApothem(_Path.Size); + const float edge_dist = radius * unit_apothem; + _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, edge_dist); + } _Path.Size = 0; } From b2ade5f3ada2091a7b01d93e3ddaf238a5d9247e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 6 Oct 2026 18:02:37 +0200 Subject: [PATCH 159/245] DrawList: AddRectFilled: add support for ImDrawFlags_StrokeLegacy to handle inverted coordinates + non-AA path. Fix cases 207 and 251 in testbed. + add braces near an IM_APPEND_TRI() to silence PVS-Studio reasonable warning "V640 The code's operational logic does not correspond with its formatting" --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 63c7ed07b..f93dfe8d6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -146,6 +146,7 @@ Breaking Changes: - Legacy `AddRect()` rounding on -> visible but very glitchy. - Legacy `AddRectFilled()` rounding off -> visible and correct. - Legacy `AddRectFilled()` rounding on -> visible but very glitchy. + - Use `ImDrawFlags_StrokeLegacy` to use old rendering for cases without rounding, or fix coordinates. - Merged `ImDrawListFlags` into `ImDrawFlags`. `ImDrawListFlags` was rarely used directly and generally setup by the ImGui context. Keep inline redirection enums (will obsolete). - `ImDrawListFlags_AntiAliasedLines` -> `ImDrawFlags_AALines` diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 4cf094c57..83ceaddc0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -871,6 +871,7 @@ float ImDrawList::_CalculateCenterBiasedOffset(float thickness) IM_MSVC_RUNTIME_CHECKS_RESTORE // Check if R is considered to be worthy rounding. Can be only used within ImDrawList due to use of _FringeScale. +// FIXME-OPT: Given unused padding space in ImDrawList would it make sense to store 0.25f * _FringeScale? #define IM_HAS_ROUNDING(RAD) ((RAD) >= (0.25f * _FringeScale)) // On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. @@ -2306,7 +2307,9 @@ void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, // Arc if (is_rounded) for (int i = 0; i < arc_point_count - 1; i++) + { IM_APPEND_TRI(stem_idx, arc_idx + i, arc_idx + i + 1); + } // Connect with previous IM_APPEND_TRI(base_idx + 0, arc_idx, stem_idx); @@ -2539,6 +2542,13 @@ void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 c const float min_dim = ImMin(width, height); flags |= Flags; + if ((flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy && rounding < 0.5f) IM_UNLIKELY + { + PrimReserve(6, 4); + PrimRect(p_min, p_max, col); + return; + } + // The rect is smaller than pixel in one dimension. if (min_dim < _FringeScale) IM_UNLIKELY { From 2859f6723c13de3a9661b8087fb7919fa3796813 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Oct 2026 19:50:23 +0200 Subject: [PATCH 160/245] Docs: fixed various comments. --- docs/CHANGELOG.txt | 25 ++++++++++++++----------- imgui.cpp | 6 +++--- imgui.h | 5 +++-- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f93dfe8d6..5d01ea9ad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -73,6 +73,9 @@ Use `ImDrawFlags_StrokeLegacy` mode to emulate old rendering: - Globally: ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); // Map to a checkbox - Globally: io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on Shift +Don't panic! Many applications will not notice any difference! You will more likely +see differences if you used lots of direct `ImDrawList` calls for custom rendering. + Main work courtesy of @memononen. Additional work/reviewing/guidance by @ocornut. With legacy bits from @thedmd, @potocpav. @@ -85,7 +88,7 @@ Refer to our guides: - ImDrawList 1.92.9 vs 1.93.0 Interactive Testbed https://www.dearimgui.com/docs/drawlist_v193 - (interactively discuss and compare differences between 1.92.9 and 1.93.9) + (interactively discuss and compare differences between 1.92.9 and 1.93.0) (downloadable HTML file, may be used offline) - Pixel Perfect Anti-aliased Rendering @@ -100,7 +103,7 @@ Refer to our guides: Breaking Changes: -- DrawList: +- ImDrawList: - AddLine(): removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates. (#9504) - This fixes inconsistencies in the API and matches the PathXXX API. - By default, stroke thickness extends on both side of the given segment. @@ -134,21 +137,21 @@ Breaking Changes: - All closed shapes with thickness=1.0f will appear identical. - The difference for thickness>1.0f shapes may be minimal since very large strokes were not well supported for widgets, but stroke will default inside widgets. - - AddCircle(), AddNgon(): removed +0.5f offset added to radius. + - AddCircle(), AddNgon(): removed -0.5f offset added to radius. - This fixes inconsistencies in the API. - Use `ImDrawFlags_StrokeLegacy` to use old method if required. Or you can apply the offset manually! - AddRectFilled(): non-integer coordinates will now display anti-aliased edges. Previously, non-integer coordinates rendered with aliased edges snapped by the rasterizer. (#6971) - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible - unless using ImDrawList_StrokeLegacy mode. With inverted coordinates (min > max): + unless using ImDrawFlags_StrokeLegacy mode. With inverted coordinates (min > max): - Legacy `AddRect()` rounding off -> visible but incorrect outer size. - Legacy `AddRect()` rounding on -> visible but very glitchy. - Legacy `AddRectFilled()` rounding off -> visible and correct. - Legacy `AddRectFilled()` rounding on -> visible but very glitchy. - Use `ImDrawFlags_StrokeLegacy` to use old rendering for cases without rounding, or fix coordinates. - Merged `ImDrawListFlags` into `ImDrawFlags`. `ImDrawListFlags` was rarely used directly - and generally setup by the ImGui context. Keep inline redirection enums (will obsolete). + and generally setup by the ImGui context. - `ImDrawListFlags_AntiAliasedLines` -> `ImDrawFlags_AALines` - `ImDrawListFlags_AntiAliasedFill` -> `ImDrawFlags_AAFill` - `ImDrawListFlags_AllowVtxOffset` -> `ImDrawFlags_UseVtxOffset` @@ -171,10 +174,10 @@ Breaking Changes: obsolete, as the new line rendering code always uses textures. - Enabling `ImFontAtlasFlags_NoBakedLines` in the font atlas will now disable support for anti-aliased lines by clearing `style.AntiAliasedLines`/`style.AntiAliasedLineEnds`. -- Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in - favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. It is +- Style: obsoleted `style.CurveTessellationTol` (default 1.25) which was in Pixels² unit in + favor of `style.CurveTessellationMaxError` (default 1.12) which is in Pixels unit. It is easier to tweak + this allows us to easily scale error threshold on high density screens. - - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). + - style.CurveTessellationMaxError == sqrtf(style.CurveTessellationTol). - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - Fonts: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). @@ -221,7 +224,7 @@ Other Changes: (#9504, #2183, #2964, #7972 + #9360, #6331, #4250, #4091) [@memononen] - Generally fixed rendering of thick strokes/paths. - The new stroke expansion now uses corner miter calculation, which keeps thickness along - the line segments consistent. If the corner becomes too sharp, it will be bevelled to + the line segments consistent. If the corner becomes too sharp, it will be beveled to avoid long spikes at corners. - There are also some robustness measures for the case where the line thickness is larger than the features being drawn. @@ -233,7 +236,7 @@ Other Changes: work precisely the same regardless of graphics API. (#3116, #3258, #2441) [@memononen] - Debug: added `io.ConfigDebugDrawListDefaultsToStrokeLegacy` to facilitate comparing old/new behaviors. This is equivalent to calling `PushDrawFlag(ImDrawFlags_StrokeLegacy, true)` - on every drawlist. + on every drawlists. Suggested uses, e.g. - `io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on holding Shift` - `ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy);` @@ -292,7 +295,7 @@ Other Changes: which may make them appear as protruding a little more. - About disabling anti-aliasing: - Disabling anti-aliasing is now emulated by applying different UV coordinates. - - It does not result in a performance increase or vertex/index data decrease any more. + - It does not result in a performance increase or vertex/index data decrease any more (however the tendency is that the new code behaves better than old code). - But may be a useful stylistic choice in some circumstances. - Many thick shapes had broken corners with old no-AA code, and the old no-AA code diff --git a/imgui.cpp b/imgui.cpp index 5b7d0c068..5bf2ec239 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -415,7 +415,7 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - AddRect(), AddCircle(), AddNgon(), AddEllipse(), AddTriangle(), AddQuad(): defaulting to "inside" stroke. All closed shapes with thickness=1.0f will appear identical. The difference for thickness>1.0f shapes may be minimal since very large strokes were not well supported for widgets, but stroke will default inside widgets. - AddCircle(), AddNgon(): removed +0.5f offset added to radius. This fixes inconsistencies in the API. Use `ImDrawFlags_StrokeLegacy` to use old method if required. Or you can apply the offset manually! - AddRectFilled(): non-integer coordinates will now display anti-aliased edges. Previously, non-integer coordinates rendered with aliased edges snapped by the rasterizer. - - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible unless using ImDrawList_StrokeLegacy mode. + - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible unless using ImDrawFlags_StrokeLegacy mode. With inverted coordinates: - Legacy `AddRect()` rounding off -> visible but incorrect outer size. - Legacy `AddRect()` rounding on -> visible but very glitchy. @@ -438,8 +438,8 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - obsoleted style.AntiAliasedLinesUseTex and ImDrawListFlags_AntiAliasedLinesUseTex, as the new line rendering code always uses textures. - 2026/09/30 (1.93.0) - ImFont: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). (#609, #5748) - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. - - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). + - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol` (default 1.25) which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12) which is in Pixels unit. + - style.CurveTessellationMaxError == sqrtf(style.CurveTessellationTol). - 2026/07/20 (1.92.9) - DragXXX, SliderXXX, InputScalar: with `ImGuiItemFlags_LiveEditOnInputScalar` now defaulting to being disabled: inputting a value with the keyboard doesn't write intermediate values to backing variable. (#9476) - Before: DragFloat() with user typing "123" --> write back 1, then 12, then 123. diff --git a/imgui.h b/imgui.h index acce04d3f..22a8b6da1 100644 --- a/imgui.h +++ b/imgui.h @@ -2560,9 +2560,10 @@ struct ImGuiIO bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. // Option to compare < 1.93.0 rendering details vs 1.93.0 rendering details. (#9504) - // - Equivalent to calling PushDrawFlag(ImDrawList_StrokeLegacy,true) on every draw list instances. + // - Equivalent to calling PushDrawFlag(ImDrawFlags_StrokeLegacy,true) on every draw list instances. // - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier - bool ConfigDebugDrawListDefaultsToStrokeLegacy; // false // Default all ImDrawList to ImDrawList_StrokeLegacy mode, mimicking pre-1.93.0 rendering. + // - Also see our interactive testbed: https://www.dearimgui.com/docs/drawlist_v193 + bool ConfigDebugDrawListDefaultsToStrokeLegacy; // false // Default all ImDrawList to ImDrawFlags_StrokeLegacy mode, mimicking pre-1.93.0 rendering. //------------------------------------------------------------------ // Platform Identifiers From 906c6838ad97ebe87d61110593e28f29fdb211c2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2026 12:56:19 +0200 Subject: [PATCH 161/245] Debug: fixed DebugNodeTexture()->FormatTextureRefForDebugDisplay() truncating displayed value to 32-bits. (#9578) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 5bf2ec239..76d1be2ac 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -16737,7 +16737,7 @@ static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTe char* buf_end = buf + buf_size; if (tex_ref._TexData != NULL) buf_p += ImFormatString(buf_p, buf_end - buf_p, "#%03d: ", tex_ref._TexData->UniqueID); - ImFormatString(buf_p, buf_end - buf_p, "0x%X", ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); + ImFormatString(buf_p, buf_end - buf_p, "0x%" IM_PRIX64, ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); return buf; } From dc09bbee1e0fe88caa20c352b8defea3c72d24bc Mon Sep 17 00:00:00 2001 From: Yan Pujante Date: Mon, 12 Oct 2026 13:11:36 +0200 Subject: [PATCH 162/245] Examples: GLFW/SDL2/SDL3+WebGPU: better select surface format instead of using surface_capabilities.formats[0]. (#9576) --- docs/CHANGELOG.txt | 1 + examples/example_glfw_wgpu/main.cpp | 16 ++++++++++++---- examples/example_sdl2_wgpu/main.cpp | 16 ++++++++++++---- examples/example_sdl3_wgpu/main.cpp | 16 ++++++++++++---- 4 files changed, 37 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5d01ea9ad..070283aa0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -435,6 +435,7 @@ Other Changes: - Examples: - MSVC: disabled /JMC in Visual Studio projects (unnecessary overhead). - GLFW/SDL2/SDL3+WebGPU: fixed running with wgpu-native missing `wgpuInstanceWaitAny()`. (#9377) + - GLFW/SDL2/SDL3+WebGPU: better select surface format. (#9576) [@ypujante] - GLFW+Metal: fixed mistakenly calling `ImGui_ImplGlfw_InitForOpenGL()`, which broke multi-viewport support. (#9564) [@ypujante] - SDL2+Metal: create Metal context without using a `SDL_Renderer`. diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index fe8b3de49..b84641b0d 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -290,6 +290,16 @@ int main(int, char**) return 0; } +static WGPUTextureFormat SelectSurfaceFormat(const WGPUSurfaceCapabilities& capabilities) +{ + const WGPUTextureFormat preferredFormats[] = { WGPUTextureFormat_BGRA8Unorm, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_BGRA8UnormSrgb, WGPUTextureFormat_RGBA8UnormSrgb }; + for (WGPUTextureFormat preferredFormat : preferredFormats) + for (size_t n = 0; n < capabilities.formatCount; n++) + if (capabilities.formats[n] == preferredFormat) + return preferredFormat; + return capabilities.formatCount > 0 ? capabilities.formats[0] : WGPUTextureFormat_Undefined; +} + #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -440,8 +450,7 @@ static bool InitWGPU(GLFWwindow* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); - - preferred_fmt = surface_capabilities.formats[0]; + preferred_fmt = SelectSurfaceFormat(surface_capabilities); // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK) @@ -470,8 +479,7 @@ static bool InitWGPU(GLFWwindow* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); - - preferred_fmt = surface_capabilities.formats[0]; + preferred_fmt = SelectSurfaceFormat(surface_capabilities); #endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index b0fa54179..9ed5b57c0 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -276,6 +276,16 @@ int main(int, char**) return 0; } +static WGPUTextureFormat SelectSurfaceFormat(const WGPUSurfaceCapabilities& capabilities) +{ + const WGPUTextureFormat preferredFormats[] = { WGPUTextureFormat_BGRA8Unorm, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_BGRA8UnormSrgb, WGPUTextureFormat_RGBA8UnormSrgb }; + for (WGPUTextureFormat preferredFormat : preferredFormats) + for (size_t n = 0; n < capabilities.formatCount; n++) + if (capabilities.formats[n] == preferredFormat) + return preferredFormat; + return capabilities.formatCount > 0 ? capabilities.formats[0] : WGPUTextureFormat_Undefined; +} + #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -427,8 +437,7 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); - - preferred_fmt = surface_capabilities.formats[0]; + preferred_fmt = SelectSurfaceFormat(surface_capabilities); // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK) @@ -457,8 +466,7 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); - - preferred_fmt = surface_capabilities.formats[0]; + preferred_fmt = SelectSurfaceFormat(surface_capabilities); #endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index c66748f80..8a61d69e3 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -287,6 +287,16 @@ int main(int, char**) return 0; } +static WGPUTextureFormat SelectSurfaceFormat(const WGPUSurfaceCapabilities& capabilities) +{ + const WGPUTextureFormat preferredFormats[] = { WGPUTextureFormat_BGRA8Unorm, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_BGRA8UnormSrgb, WGPUTextureFormat_RGBA8UnormSrgb }; + for (WGPUTextureFormat preferredFormat : preferredFormats) + for (size_t n = 0; n < capabilities.formatCount; n++) + if (capabilities.formats[n] == preferredFormat) + return preferredFormat; + return capabilities.formatCount > 0 ? capabilities.formats[0] : WGPUTextureFormat_Undefined; +} + #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -438,8 +448,7 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); - - preferred_fmt = surface_capabilities.formats[0]; + preferred_fmt = SelectSurfaceFormat(surface_capabilities); // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK) @@ -468,8 +477,7 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); - - preferred_fmt = surface_capabilities.formats[0]; + preferred_fmt = SelectSurfaceFormat(surface_capabilities); #endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; From 6aa6626f29227dd4b998c458cee52e41ba7fdf83 Mon Sep 17 00:00:00 2001 From: Mikko Mononen Date: Wed, 7 Oct 2026 20:48:27 +0200 Subject: [PATCH 163/245] DrawList: improved handling of very small circles. See testbed case 354. --- imgui_draw.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 83ceaddc0..163022f1b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2761,13 +2761,14 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, if ((col & IM_COL32_A_MASK) == 0) return; - const float diameter = radius * 2.0f; - if (diameter < _FringeScale) IM_UNLIKELY + // Minimum radius, before the edge-AA will overlap. + const float min_radius = _FringeScale * 1.41421356f * 0.5f; + if (radius < min_radius) IM_UNLIKELY { - if (diameter < (1.0f / 255.0f) * _FringeScale) + if (radius < (1.0f / 255.0f) * min_radius) return; - col = ImAlphaMultiply(col, diameter * _InvFringeScale); - radius = _FringeScale * 0.5f; + col = ImAlphaMultiply(col, radius / min_radius); + radius = min_radius; } if (num_segments <= 0 && radius <= _Data->ArcFastRadiusCutoff) From 42a22377a4d0ba92a7155c7bc961bf85acbe24b3 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Mon, 12 Oct 2026 23:07:30 +0200 Subject: [PATCH 164/245] Demo: Mixed Values: added IMGUI_DEMO_MARKER(). (#9582) --- imgui_demo.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 97038f1e0..25a8a1429 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2062,6 +2062,7 @@ static void DemoWindowWidgetsMixedValues() { if (ImGui::TreeNode("Mixed Values")) { + IMGUI_DEMO_MARKER("Widgets/Mixed Values"); // This is designed for advanced property editors which are generally reusable and data-driven. HelpMarker("Using ImGuiItemFlags_MixedValue."); From 09cd4416e85c0ccbe882e9e7c860e1b324cc4d71 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 Oct 2026 16:20:43 +0200 Subject: [PATCH 165/245] PlotHistogram: fixed passing inverted coordinates to AddRectFilled(). --- imgui_widgets.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 287d94062..00129d7c5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -9144,7 +9144,7 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) ); - // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + // We could render lower-level to save a bit of CPU. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t)); if (plot_type == ImGuiPlotType_Lines) @@ -9155,6 +9155,8 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get { if (pos1.x >= pos0.x + 2.0f) pos1.x -= 1.0f; + if (pos0.y > pos1.y) + ImSwap(pos0.y, pos1.y); window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base); } From 098c71133c32b7b946ae2b6db27fc8a4d0629d68 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 Oct 2026 16:14:30 +0200 Subject: [PATCH 166/245] Demo: Plot, Vertical Sliders, Colors: better scaling. + enforce some rounding in vertical slider demo. --- imgui_demo.cpp | 64 +++++++++++++++++++++++++++++++------------------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 25a8a1429..66ab70299 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1261,6 +1261,7 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::OpenPopup("mypicker"); backup_color = color; } + float ref_sz = ImGui::GetFrameHeight(); if (ImGui::BeginPopup("mypicker")) { ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); @@ -1268,11 +1269,12 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::ColorPicker4("##picker", (float*)&color, base_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); ImGui::SameLine(); + ImVec2 color_button_sz(ref_sz * 3.0f, ref_sz * 2.0f); ImGui::BeginGroup(); // Lock X position ImGui::Text("Current"); - ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); + ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, color_button_sz); ImGui::Text("Previous"); - if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) + if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, color_button_sz)) color = backup_color; ImGui::Separator(); ImGui::Text("Palette"); @@ -1283,7 +1285,7 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; - if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags)) color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! // Allow user to drop colors into each palette entry. Note that ColorButton() is already a @@ -1306,8 +1308,9 @@ static void DemoWindowWidgetsColorAndPickers() IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (simple)"); ImGui::Text("Color button only:"); static bool no_border = false; + const ImVec2 color_button_sz(ref_sz * 2.0f, ref_sz * 2.0f); ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); - ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), color_button_sz); IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker"); ImGui::SeparatorText("Color picker"); @@ -1682,12 +1685,13 @@ static void DemoWindowWidgetsDragAndDrop() "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }; + float sz = ImGui::GetFrameHeight() * 3.0f; for (int n = 0; n < IM_COUNTOF(names); n++) { ImGui::PushID(n); if ((n % 3) != 0) ImGui::SameLine(); - ImGui::Button(names[n], ImVec2(60, 60)); + ImGui::Button(names[n], ImVec2(sz, sz)); // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) @@ -2183,10 +2187,12 @@ static void DemoWindowWidgetsPlotting() static bool animate = true; ImGui::Checkbox("Animate", &animate); + ImVec2 plot_sz(0.0f, ImGui::GetFrameHeight() * 4.0f); + // Plot as lines and plot as histogram static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; ImGui::PlotLines("Frame Times", arr, IM_COUNTOF(arr)); - ImGui::PlotHistogram("Histogram", arr, IM_COUNTOF(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); + ImGui::PlotHistogram("Histogram", arr, IM_COUNTOF(arr), 0, NULL, 0.0f, 1.0f, plot_sz); //ImGui::SameLine(); HelpMarker("Consider using ImPlot instead!"); // Fill an array of contiguous float values to plot @@ -2215,7 +2221,7 @@ static void DemoWindowWidgetsPlotting() average /= (float)IM_COUNTOF(values); char overlay[32]; sprintf(overlay, "avg %f", average); - ImGui::PlotLines("Lines", values, IM_COUNTOF(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); + ImGui::PlotLines("Lines", values, IM_COUNTOF(values), values_offset, overlay, -1.0f, 1.0f, plot_sz); } // Use functions to generate output @@ -2233,8 +2239,8 @@ static void DemoWindowWidgetsPlotting() ImGui::SameLine(); ImGui::SliderInt("Sample count", &display_count, 1, 400); float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; - ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); - ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, plot_sz); + ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, plot_sz); ImGui::TreePop(); } @@ -4493,27 +4499,34 @@ static void DemoWindowWidgetsVerticalSliders() if (ImGui::TreeNode("Vertical Sliders")) { IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); - const float spacing = 4; - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + ImGuiStyle& style = ImGui::GetStyle(); + ImVec2 slider_sz(ImGui::GetFrameHeight(), ImGui::GetFrameHeight() * 9); + + ImGui::PushStyleVarX(ImGuiStyleVar_ItemSpacing, (float)(int)(style.ItemSpacing.x * 0.5f)); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, (float)(int)(slider_sz.x * 0.25f)); + ImGui::PushStyleVar(ImGuiStyleVar_GrabRounding, (float)(int)(slider_sz.x * 0.25f)); + float spacing = style.ItemSpacing.x; static int int_value = 0; - ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); + ImGui::VSliderInt("##int", slider_sz, &int_value, 0, 5); ImGui::SameLine(); static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; ImGui::PushID("set1"); for (int i = 0; i < 7; i++) { - if (i > 0) ImGui::SameLine(); + if (i > 0)ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); - ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", slider_sz, &values[i], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values[i]); - ImGui::PopStyleColor(4); + ImGui::PopStyleColor(5); ImGui::PopID(); } ImGui::PopID(); @@ -4522,15 +4535,15 @@ static void DemoWindowWidgetsVerticalSliders() ImGui::PushID("set2"); static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; const int rows = 3; - const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows)); + const ImVec2 slider_size_small(slider_sz.x, (float)(int)((slider_sz.y - (rows - 1) * spacing) / rows)); for (int nx = 0; nx < 4; nx++) { - if (nx > 0) ImGui::SameLine(); + if (nx > 0)ImGui::SameLine(); ImGui::BeginGroup(); for (int ny = 0; ny < rows; ny++) { ImGui::PushID(nx * rows + ny); - ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + ImGui::VSliderFloat("##v", slider_size_small, &values2[nx], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values2[nx]); ImGui::PopID(); @@ -4543,15 +4556,17 @@ static void DemoWindowWidgetsVerticalSliders() ImGui::PushID("set3"); for (int i = 0; i < 4; i++) { - if (i > 0) ImGui::SameLine(); + if (i > 0) + ImGui::SameLine(); ImGui::PushID(i); - ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); - ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, slider_sz.y * 0.25f); + ImGui::VSliderFloat("##v", ImVec2(slider_sz.x * 2.0f, slider_sz.y), &values[i], 0.0f, 1.0f, "%.2f\nsec"); ImGui::PopStyleVar(); ImGui::PopID(); } ImGui::PopID(); - ImGui::PopStyleVar(); + + ImGui::PopStyleVar(3); ImGui::TreePop(); } } @@ -8164,7 +8179,8 @@ static void DemoWindowInputs() ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15); ImGui::SliderInt("SetNextFrameWantCaptureKeyboard() on hover", &capture_override_keyboard, -1, +1, capture_override_desc[capture_override_keyboard + 1], ImGuiSliderFlags_AlwaysClamp); - ImGui::ColorButton("##panel", ImVec4(0.7f, 0.1f, 0.7f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, ImVec2(128.0f, 96.0f)); // Dummy item + float ref_sz = ImGui::GetFrameHeight() * 4.0f; + ImGui::ColorButton("##panel", ImVec4(0.7f, 0.1f, 0.7f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, ImVec2(ref_sz, ref_sz)); // Dummy item if (ImGui::IsItemHovered() && capture_override_mouse != -1) ImGui::SetNextFrameWantCaptureMouse(capture_override_mouse == 1); if (ImGui::IsItemHovered() && capture_override_keyboard != -1) From a536894821ce7358ebab622ac8a357ad4f9a93f3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 Oct 2026 18:07:54 +0200 Subject: [PATCH 167/245] Examples: all examples now default to use a little bit of rounding (`FrameRounding` and `GrabRounding`). --- docs/CHANGELOG.txt | 1 + examples/example_allegro5/main.cpp | 7 +++++-- examples/example_android_opengl3/main.cpp | 8 +++++--- examples/example_apple_metal/main.mm | 7 +++++-- examples/example_apple_metal4/main.mm | 7 +++++-- examples/example_apple_opengl2/main.mm | 7 +++++-- examples/example_apple_opengl3/main.mm | 7 +++++-- examples/example_glfw_metal/main.mm | 8 +++++--- examples/example_glfw_opengl2/main.cpp | 8 +++++--- examples/example_glfw_opengl3/main.cpp | 8 +++++--- examples/example_glfw_vulkan/main.cpp | 8 +++++--- examples/example_glfw_wgpu/main.cpp | 8 +++++--- examples/example_glut_opengl2/main.cpp | 7 +++++-- examples/example_null/main.cpp | 8 ++++++++ examples/example_qnx_opengl3/main.cpp | 8 +++++--- examples/example_qnx_vulkan/main.cpp | 8 +++++--- examples/example_sdl2_directx11/main.cpp | 8 +++++--- examples/example_sdl2_metal/main.mm | 8 +++++--- examples/example_sdl2_opengl2/main.cpp | 8 +++++--- examples/example_sdl2_opengl3/main.cpp | 8 +++++--- examples/example_sdl2_sdlrenderer2/main.cpp | 8 +++++--- examples/example_sdl2_vulkan/main.cpp | 8 +++++--- examples/example_sdl2_wgpu/main.cpp | 8 +++++--- examples/example_sdl3_directx11/main.cpp | 8 +++++--- examples/example_sdl3_metal/main.mm | 8 +++++--- examples/example_sdl3_metal4/main.mm | 8 +++++--- examples/example_sdl3_opengl3/main.cpp | 8 +++++--- examples/example_sdl3_sdlgpu3/main.cpp | 8 +++++--- examples/example_sdl3_sdlrenderer3/main.cpp | 8 +++++--- examples/example_sdl3_vulkan/main.cpp | 8 +++++--- examples/example_sdl3_wgpu/main.cpp | 8 +++++--- examples/example_win32_directx10/main.cpp | 8 +++++--- examples/example_win32_directx11/main.cpp | 8 +++++--- examples/example_win32_directx12/main.cpp | 8 +++++--- examples/example_win32_directx9/main.cpp | 8 +++++--- examples/example_win32_opengl3/main.cpp | 10 ++++++---- examples/example_win32_vulkan/main.cpp | 8 +++++--- 37 files changed, 185 insertions(+), 100 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 070283aa0..3f70c1583 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -433,6 +433,7 @@ Other Changes: when `FramebufferScale` is >1.0f. (#9515, #8628) [@WayU] - WebGPU: update to build with wgpu-native 29.0+. (#9377, #9532, #9530) [@lucascompython, @ivan-enzhaev] - Examples: + - All: all examples now default to use a little bit of rounding (`FrameRounding` and `GrabRounding`). - MSVC: disabled /JMC in Visual Studio projects (unnecessary overhead). - GLFW/SDL2/SDL3+WebGPU: fixed running with wgpu-native missing `wgpuInstanceWaitAny()`. (#9377) - GLFW/SDL2/SDL3+WebGPU: better select surface format. (#9576) [@ypujante] diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index ebb6d76b0..577f09911 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -42,21 +42,24 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup Platform/Renderer backends ImGui_ImplAllegro5_Init(display); // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp index 382006fa0..edd654feb 100644 --- a/examples/example_android_opengl3/main.cpp +++ b/examples/example_android_opengl3/main.cpp @@ -144,8 +144,12 @@ void Init(struct android_app* app) io.IniFilename = g_IniFilename.c_str();; // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup Platform/Renderer backends ImGui_ImplAndroid_Init(g_App->window); @@ -153,20 +157,18 @@ void Init(struct android_app* app) // Setup scaling float main_scale = 2.0f; - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them. - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index b8edbd2d1..cddc1093c 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -62,21 +62,24 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup Renderer backend ImGui_ImplMetal_Init(_device); // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_apple_metal4/main.mm b/examples/example_apple_metal4/main.mm index 1102e41f8..553eeb34c 100644 --- a/examples/example_apple_metal4/main.mm +++ b/examples/example_apple_metal4/main.mm @@ -66,8 +66,12 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. @@ -76,13 +80,12 @@ // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 7cdc38f20..67b546ead 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -50,8 +50,12 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup Platform/Renderer backends ImGui_ImplOSX_Init(self); @@ -59,13 +63,12 @@ // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_apple_opengl3/main.mm b/examples/example_apple_opengl3/main.mm index 241aa1332..7cb2e2a33 100644 --- a/examples/example_apple_opengl3/main.mm +++ b/examples/example_apple_opengl3/main.mm @@ -49,8 +49,12 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup Platform/Renderer backends [[self openGLContext] makeCurrentContext]; // ImGui_ImplOpenGL3_Init() requires a current GL context. @@ -59,13 +63,12 @@ // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index a3671e4e6..d398adc6b 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -46,11 +46,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -63,13 +66,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 48584eaf8..454849c5e 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -55,11 +55,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -69,13 +72,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index fbcc3e595..5abf4654d 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -83,11 +83,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -100,14 +103,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index f2139cef7..e5f4d7560 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -392,11 +392,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -422,13 +425,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index b84641b0d..441da4a4a 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -89,11 +89,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -111,14 +114,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index ca8017f5b..227dad48a 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -63,8 +63,12 @@ int main(int argc, char** argv) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup Platform/Renderer backends // FIXME: Consider reworking this example to install our own GLUT funcs + forward calls ImGui_ImplGLUT_XXX ones, instead of using ImGui_ImplGLUT_InstallFuncs(). @@ -80,13 +84,12 @@ int main(int argc, char** argv) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index eba675670..ee6319fdc 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -16,6 +16,14 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); + // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; + ImGui_ImplNullPlatform_Init(); ImGui_ImplNullRender_Init(); diff --git a/examples/example_qnx_opengl3/main.cpp b/examples/example_qnx_opengl3/main.cpp index d78bee90c..f7f3f4ac7 100644 --- a/examples/example_qnx_opengl3/main.cpp +++ b/examples/example_qnx_opengl3/main.cpp @@ -63,11 +63,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -77,13 +80,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_qnx_vulkan/main.cpp b/examples/example_qnx_vulkan/main.cpp index ae309ad15..1d596d72e 100644 --- a/examples/example_qnx_vulkan/main.cpp +++ b/examples/example_qnx_vulkan/main.cpp @@ -471,11 +471,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -501,13 +504,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index cf3971646..c5bbc3baf 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -77,11 +77,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -91,13 +94,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index edd436aca..344310a3d 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -68,11 +68,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -82,13 +85,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index 3b3412b14..081874aaa 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -66,11 +66,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -80,13 +83,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index e7b101087..c1bc268fa 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -103,11 +103,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -117,14 +120,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index b69867354..9916dd85d 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -68,11 +68,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -82,13 +85,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 45a5a6de5..7c9af9eef 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -398,11 +398,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -428,13 +431,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index 9ed5b57c0..abc7be29c 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -74,11 +74,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -93,14 +96,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index 4337d4e2d..8b28d1302 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -68,11 +68,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -82,13 +85,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index e6e306624..8edd50c09 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -64,11 +64,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -78,13 +81,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_metal4/main.mm b/examples/example_sdl3_metal4/main.mm index 6debb5133..b2807935f 100644 --- a/examples/example_sdl3_metal4/main.mm +++ b/examples/example_sdl3_metal4/main.mm @@ -80,11 +80,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -94,13 +97,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index e7d22a40c..819d9bd1c 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -93,11 +93,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -107,14 +110,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 8edbbbbad..6caa71c1a 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -70,11 +70,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -90,13 +93,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 88f9ac7fb..8fbd6a972 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -58,11 +58,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -72,13 +75,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index 0073b37c5..b0474e635 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -397,11 +397,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -427,13 +430,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index 8a61d69e3..42053f0fb 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -81,11 +81,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -101,14 +104,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 2c3420709..b68ba06fe 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -59,11 +59,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -73,13 +76,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 524538ac1..5f3af383f 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -59,11 +59,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -73,13 +76,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 0d8bb20b1..5fb0ed788 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -139,11 +139,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -168,13 +171,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index fbe4c3983..f0711698e 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -57,11 +57,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -71,13 +74,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index cba8301f8..28c92a677 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -68,11 +68,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -82,13 +85,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index cbdbdb830..4c66a5422 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -385,11 +385,14 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style + ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); + //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. + style.FrameRounding = 3.0f; + style.GrabRounding = 3.0f; // Setup scaling - ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -415,13 +418,12 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); From a6fad9bbda027c7a2a207ee67fb4791217fe5493 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 13 Oct 2026 18:05:27 +0200 Subject: [PATCH 168/245] Style: update StyleColorsDark() for 1.93: greyer WindowBg, dark FrameBg. --- docs/CHANGELOG.txt | 10 +++++++--- imgui_demo.cpp | 3 ++- imgui_draw.cpp | 16 ++++++++-------- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3f70c1583..0ed9ea57f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -193,6 +193,13 @@ Breaking Changes: Other Changes: +- Style: + - StyleColorsDark(): minor refresh of the default style to look more modern: + - Changed WindowBg to use a slightly greyer value and removed opacity. + - Changed FrameBg values to use a dark black to make frames stand out better. + - Tweak TextDisabled, TableHeaderBg, TableBorders to match altered WindowBg. + - StyleColorsLight(): inverted `ImGuiCol_TitleBgXXX` colors so that the selected + window title bar appears brighter. - DrawList: - Added flags to specify stroke position in all `ImDrawList` stroking functions: (#9504) [@memononen] - `ImDrawFlags_StrokeInside` (default for Rect, Circle/Ellipse, Triangle, Quad, Ngon + AddLineH, AddLineV) @@ -368,9 +375,6 @@ Other Changes: match always filters out. (#2435) [@kudaba, @ocornut] - Added `DrawWithHint()` function. (#6206, #6395, #6447) - Added a "incl -excl" hint by default when the search field is empty. (#6206, #6395, #6447) -- Style: - - Inverted `ImGuiCol_TitleBgXXX` colors for `StyleColorsLight()` so that the selected - window title bar appears brighter. - Misc: - Added `ImGuiItemFlags_MixedValue` flag for representing mixed/indeterminate values. Supported by: Checkbox(), RadioButton(), DragXXX(), SliderXXX(), InputXXX(), ColorXXX() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 66ab70299..aa1b78509 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -965,8 +965,9 @@ static void DemoWindowWidgetsBasic() ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); ImGui::Button("Click"); - ImGui::PopStyleColor(3); + ImGui::PopStyleColor(4); ImGui::PopID(); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 163022f1b..d33cff20d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -190,15 +190,15 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); - colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.58f, 0.58f, 0.58f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.18f, 0.18f, 0.18f, 1.00f); colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f); - colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); - colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); + colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.10f, 0.10f, 1.00f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.19f, 0.25f, 0.31f, 1.00f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.21f, 0.33f, 0.47f, 1.00f); colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); @@ -235,9 +235,9 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); - colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); - colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); // Prefer using Alpha=1.0 here - colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.28f, 0.28f, 0.29f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.40f, 0.40f, 0.45f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.32f, 0.32f, 0.34f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; From c1aaac65e896a45f81f47a4d68f9959e0f86c859 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Oct 2026 16:46:54 +0200 Subject: [PATCH 169/245] Version 1.93.0 --- docs/CHANGELOG.txt | 105 ++++++++++++++++++++++----------------------- imgui.cpp | 2 +- imgui.h | 8 ++-- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 62 insertions(+), 63 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0ed9ea57f..b5d983005 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,9 +36,11 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.93.0 WIP (In Progress) + VERSION 1.93.0 (Released 2026-10-14) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.93.0 + In 1.93.0, the `ImDrawList` rendering API has been improved to be more robust and more consistent over the whole range of shapes. The rendering now matches much closer to common vector drawing APIs, like html canvas. Improvements, like anti-aliased line @@ -55,10 +57,10 @@ The rendering of common shapes was optimized when the shapes fall on integer coo using textures instead of tessellated geometry to draw round corners. The varying code-paths are designed to look indistinguishable from each others. -New rendering code fixes some inconsistencies between graphics APIs (e.g. DirectX vs OpenGL) -which are using different diamond exits rules. -New code should work precisely the same regardless of graphics API. -(note that using _StrokeLegacy mode can lead to similar inconsistencies) +New rendering code fixes some inconsistencies between graphics APIs +(e.g. DirectX vs OpenGL) which are using different diamond exits rules. +New code should work precisely the same regardless of which graphics API is used +(note that using _StrokeLegacy mode can lead to the same old inconsistencies). New rendering code also deals better with animating thickness and rounding (integer values are recommended). @@ -73,31 +75,29 @@ Use `ImDrawFlags_StrokeLegacy` mode to emulate old rendering: - Globally: ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); // Map to a checkbox - Globally: io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on Shift -Don't panic! Many applications will not notice any difference! You will more likely -see differences if you used lots of direct `ImDrawList` calls for custom rendering. +Don't panic! +Many applications will not notice any difference! You will more likely see +differences if you used lots of direct `ImDrawList` calls for custom rendering. -Main work courtesy of @memononen. -Additional work/reviewing/guidance by @ocornut. -With legacy bits from @thedmd, @potocpav. +Credits for ImDrawList changes in 1.93.0: +- main work courtesy of @memononen. +- additional work/reviewing/guidance by @ocornut. +- with legacy bits from @thedmd, @potocpav. +Other credits marked below, or @ocornut when omitted. Refer to our guides: - - ImDrawList Vector Rendering Reference https://github.com/ocornut/imgui/wiki/Draw-List (includes a precise list of differences between 1.92.9 and 1.93.0). - - ImDrawList 1.92.9 vs 1.93.0 Interactive Testbed https://www.dearimgui.com/docs/drawlist_v193 - (interactively discuss and compare differences between 1.92.9 and 1.93.0) + (interactively compare differences between 1.92.9 and 1.93.0 + commentary) (downloadable HTML file, may be used offline) - - Pixel Perfect Anti-aliased Rendering https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering - - How Anti-aliased Polyline Rendering is Implemented https://github.com/ocornut/imgui/wiki/Polyline-Rendering - -- Main topic: +- Discussion topic: https://github.com/ocornut/imgui/issues/9504 (if you have a problem to discuss, please open a new issue) @@ -124,8 +124,8 @@ Breaking Changes: - Your lines will appear offset by -0.5f pixels on each axis. Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. - - Old `AddLine({x1, y1}, {x2, y2}, col)` --> `AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col);` // Same - or use `ImDrawFlags_StrokeLegacy` --> `AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy); // Offset by +0.5f + disable AA ends. + - Old `AddLine({x1, y1}, {x2, y2}, col)` --> `AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col);` // Same + or use `ImDrawFlags_StrokeLegacy` --> `AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy);` // Offset by +0.5f + disable AA ends. This reapplies the old offset, and should get you exactly the same result you previously got for thickness=1.0f lines. But said result were previously sometimes ambiguous and renderer-dependent. (#3116, #3258, #2441) @@ -144,7 +144,7 @@ Breaking Changes: Previously, non-integer coordinates rendered with aliased edges snapped by the rasterizer. (#6971) - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible - unless using ImDrawFlags_StrokeLegacy mode. With inverted coordinates (min > max): + unless using `ImDrawFlags_StrokeLegacy` mode. With inverted coordinates (min > max): - Legacy `AddRect()` rounding off -> visible but incorrect outer size. - Legacy `AddRect()` rounding on -> visible but very glitchy. - Legacy `AddRectFilled()` rounding off -> visible and correct. @@ -188,8 +188,7 @@ Breaking Changes: for `ImGuiBackendFlags_RendererHasTextures`. Use the new signature! (#9487) - OpenGL3: Does not attempt to read `GL_CLIP_ORIGIN` by default as the detection is sub-optimal and not reliable on some setup. Use `ImGui_ImplOpenGL3_SetClipOrigin(0)` - to enable auto-detection, or e.g. `ImGui_ImplOpenGL3_SetClipOrigin(GL_UPPER_LEFT)`. - + to enable auto-detection, or e.g. `ImGui_ImplOpenGL3_SetClipOrigin(GL_UPPER_LEFT)`. Other Changes: @@ -200,7 +199,7 @@ Other Changes: - Tweak TextDisabled, TableHeaderBg, TableBorders to match altered WindowBg. - StyleColorsLight(): inverted `ImGuiCol_TitleBgXXX` colors so that the selected window title bar appears brighter. -- DrawList: +- ImDrawList: - Added flags to specify stroke position in all `ImDrawList` stroking functions: (#9504) [@memononen] - `ImDrawFlags_StrokeInside` (default for Rect, Circle/Ellipse, Triangle, Quad, Ngon + AddLineH, AddLineV) - `ImDrawFlags_StrokeCenter` (default for Line, Polyline, Beziers, Paths function) @@ -267,25 +266,25 @@ Other Changes: - AddConvexPolyFilled()/PathFillConvex(): improved to handle input geometry more robustly. The rendering of sharp corners was improved. Earlier there were issues with sharp corners either creating long spikes, or messing up the adjacent edge's anti-aliasing. Now the - anti-aliasing fringe calculation is more consistent, and sharp corners get bevelled to + anti-aliasing fringe calculation is more consistent, and sharp corners get beveled to avoid spikes. There might still be issues when the smallest extent of a long thin polygon is less than a pixel. Also supports `ImDrawFlags_JoinMiter`, to facilitate matching a stroke using the same flag. - - AddRect(), AddRectFilled(): various optimizations for rounded rectangles. (#1962, #9504) + - `AddRect()`, `AddRectFilled()`: various optimizations for rounded rectangles. (#1962, #9504) - Integer-aligned coordinates and thicknesses will automatically use baked textures, saving on both CPU and vertex/index data. - Enabled by default. Use `ImFontAtlasFlags_NoBakedRoundCorners` to disable baking round corners in font atlas. - Added `ImDrawFlags_UseTexForRoundCorners` flag to enable in scope or per-shape. Added for consistency and debugging, not really needed in practice. - - AddCircle, AddCircleFilled: fixed large circles being under-tessellated + - `AddCircle()`, `AddCircleFilled()`: fixed large circles being under-tessellated (when above ~140 with default CircleTessellationMaxError). - Improved debug-build performance in various locations. - Improved minor mismatches when overlapping strokes and filled shapes. For example, when using inside strokes, - `AddRect()` and `AddRectFilled()` with rounding now overlap better. (#3656) - `AddCircle()` and `AddCircleFilled()` now overlap better. - - Added ImDrawList::PushDrawFlag()/PopDrawFlag() to alter certain flags for a + - Added `ImDrawList::PushDrawFlag()`/`PopDrawFlag()` to alter certain flags for a scope and a given `ImDrawList`. (#9489) - e.g. `PushDrawFlag(ImDrawFlags_StrokeLegacy, true);` enforce legacy tweaks. - About `ImDrawFlags_StrokeLegacy`: @@ -308,21 +307,25 @@ Other Changes: - Many thick shapes had broken corners with old no-AA code, and the old no-AA code was wildly different from the AA code. Not the case any more. (#288) - Per-viewport FramebufferScale for Apple/Retina screen is applied to draw lists: - - AA Fringe is scaled accordingly. + - AA Fringe is scaled accordingly. (#9577) - Circle and Curves tessellation error are scaled accordingly. - - Reworked assert in PushTexture() to allow convenience grace period of using a + - Reworked assert in `PushTexture()` to allow convenience grace period of using a texture that was queue for destroy during the frame. Make it safe to stick to an existing texture during the frame. (#9528, #8465) - Added optional `platform_io.DrawCallback_SetSamplerFromTex` standard backend-agnostic draw callback for requesting to use the sampler associated already associated to a texture. Currently only supported by the OpenGL2/3 and SDLRenderer3 backend. (#9378) - - Fixed dangling ImDrawList::_OwnerName when using animated label. (#9552) [@ubi-dcastonguay] - + - Fixed dangling `ImDrawList::_OwnerName` when using animated label. (#9552) [@ubi-dcastonguay] +- Mixed Values: + - Added `ImGuiItemFlags_MixedValue` flag for representing mixed/indeterminate values. + Supported by: Checkbox(), RadioButton(), DragXXX(), SliderXXX(), InputXXX(), ColorXXX() + and Combo() functions. + The scoped flag is designed for usage by advanced property editors. (#5518, #5677, #6865) - Drags, Sliders: - - Fixed an overflow using `ImGuiSliderFlags_Logarithmic` with S32/S64 types which - leads to clamped interactions. (#9526, #3361, #1823, #1316, #642) [@lailoken] - Ongoing drags may be cancelled using Right-Click, Escape or Gamepad Triangle. Cancelling reverts to the initial value. (#8564, #9534) + - Fixed an overflow using `ImGuiSliderFlags_Logarithmic` with S32/S64 types which + leads to clamped interactions. (#9526, #3361, #1823, #1316, #642) [@lailoken] - TreeNode: - Fixed issues/asserts with 32+ deep trees when using ImGuiTreeNodeFlags_DrawLinesXXX features or other features requiring stack storage. (#9509) [@lasrod] @@ -331,14 +334,14 @@ Other Changes: section width. - Using <> scrolling buttons while the selected Tab is at either end of the section mid-section but not fully visible always makes it fully visible - (before eventually selecting a Tab in the leading/trailing section) + (before eventually selecting a Tab in the leading/trailing section). - Tables: - Fixed a bug restoring correct .ini columns order when table use is Sortable but had no user changes. (regression from 1.92.9). (#9519, #9108) - Fixed a bug tracking topology changes (insert new columns in the middle) when the table is not _Reorderable: new columns would be ordered incorrectly. (#9570, #9108, #9572) [@lailoken] -- InpuText: +- InputText: - Fixed a crash in some cases when using Home key in a WordWrap+ReadOnly field. (#9561) - Selectable: - Fixed `ImGuiSelectableFlags_SelectOnNav` triggering during NavInit. @@ -346,9 +349,9 @@ Other Changes: - Reworked `AddFontDefault()` to use `io.DisplayFrameBufferScale` as part of the heuristic to select `AddFontDefaultVector()` by default, effectively using ProggyForever instead of ProggyClean on most Apple/Retina setups by default. - - Added ImFont::AddRemapCodepointToGlyphIndex() allowing to access glyphs that are not + - Added `ImFont::AddRemapCodepointToGlyphIndex()` allowing to access glyphs that are not mapped to codepoints. (#9559, #5647, #609, #5748, #8466) - - imgui_freetype: Fixed blurryness rendering `AddFontDefaultVector()`. Caused by a + - imgui_freetype: Fixed blurriness rendering `AddFontDefaultVector()`. Caused by a non-pixel aligned offset caused by `ExtraSizeScale`. (#9348, #9233) [@redpartizan, @RDMCz] - (Internal) ImFontLoader: reworked `FontSrcContainsGlyph`, `FontBakedLoadGlyph` signatures to take raw glyph index instead of codepoint. Added `FontSrcGetGlyphIndexFromCodepoint`. @@ -356,7 +359,7 @@ Other Changes: - Added `IMGUI_DISABLE_STB_TRUETYPE` to completely omit the stb_truetype loader code + stb_truetype.h code. (#9573) - ColorEdit: - - ColorButton, ColorEdit, ColorPicker: cancel-out alpha caused by BeginDisabled() so + - ColorButton, ColorEdit, ColorPicker: cancel-out alpha caused by `BeginDisabled()` so disabled color buttons have the same color as non-disabled oness. (#9511) - ColorButton: fixed issues/inconsistencies with checkerboard rendering when combining color alpha and global style alpha. (#9511) [@enjmiah, @ocornut] @@ -375,13 +378,17 @@ Other Changes: match always filters out. (#2435) [@kudaba, @ocornut] - Added `DrawWithHint()` function. (#6206, #6395, #6447) - Added a "incl -excl" hint by default when the search field is empty. (#6206, #6395, #6447) +- Widgets: + - Checkbox, Menus: check marks use anti-aliased ends. + - Tweaked rendering in various locations to avoid blurriness: + - Windows: title-bar and menu-bar border (when thickness>1.0f). + - SeparatorText: border (when thickness>1.0f). + - Tree: hierarchy lines (when thickness>1.0f). + - InputText: input caret (when thickness>1.0f). + - TabBar: selected overline border (when thickness>1.0f). - Misc: - - Added `ImGuiItemFlags_MixedValue` flag for representing mixed/indeterminate values. - Supported by: Checkbox(), RadioButton(), DragXXX(), SliderXXX(), InputXXX(), ColorXXX() - and Combo() functions. - The scoped flag is designed for usage by advanced property editors. (#5518, #5677, #6865) - Fixed `GetBackgroundDrawList()`/`GetForegroundDrawList()` not being properly reset - every frame when cumulated session time is very large (e.g. a few days). [@lailoken] + every frame when accumulated session time is very large (e.g. a few days). [@lailoken] - Added `IM_NODEBUGSTEP` helper to tag functions with `__declspec(non_user_code)` (MSVC) or `[[gnu::artificial]]` (Clang/GCC) in order to provide a hint to debuggers to skip trivial functions when stepping into. @@ -390,16 +397,8 @@ Other Changes: - Fixed strict aliasing violation in `ImHashData()` affecting Clang 23 + SSE 4.2 + -flto. Could manifest as `ImFontAtlasBakedGetId()` computation omitting font size from the hashed data. (#9557, #9560) [@sthalik] - - IO: restore default clipboard/ime/shell platform handlers on ClearPlatformHandlers(), fixing + - IO: restore default clipboard/ime/shell platform handlers on `ClearPlatformHandlers()`, fixing issues switching backends mid-session to one relying on default. (#9537, #8945, #2769) [@lstalmir] -- Widgets: - - Checkbox, Menus: check marks use anti-aliased ends. - - Tweaked rendering in various locations to avoid blurryness: - - Windows: title-bar and menu-bar border (when thickness>1.0f). - - SeparatorText: border (when thickness>1.0f). - - Tree: hierarchy lines (when thickness>1.0f). - - InputText: input caret (when thickness>1.0f). - - TabBar: selected overline border (when thickness>1.0f). - Demo: - Added `Widgets->Mixed Values` section. (#5518, #5677, #6865) - Custom Rendering section: exposed new flags; showcasing overlapping strokes @@ -413,7 +412,7 @@ Other Changes: and leave the other ones untouched. (#9574) [@tqjxlm] - OpenGL2, OpenGL3: added support for `platform_io.DrawCallback_SetSamplerFromTex` draw callback to request using the sampler associated already associated to a texture. (#9378) - - OpenGL2, OpenGL3: fixed `DrawCallback_ResetRenderState` handler not reseting all states + - OpenGL2, OpenGL3: fixed `DrawCallback_ResetRenderState` handler not resetting all states in the glTexParameter() path. (#9378) - OpenGL3: added `ImGui_ImplOpenGL3_SetClipOrigin()` to specify origin between `GL_LOWER_LEFT` (new default), `GL_UPPER_LEFT` and `0` (autodetect, old default). diff --git a/imgui.cpp b/imgui.cpp index 76d1be2ac..3705e7262 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 WIP +// dear imgui, v1.93.0 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 22a8b6da1..df2d42675 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 WIP +// dear imgui, v1.93.0 // (headers) // Help: @@ -29,8 +29,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.93.0 WIP" -#define IMGUI_VERSION_NUM 19298 +#define IMGUI_VERSION "1.93.0" +#define IMGUI_VERSION_NUM 19300 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -992,7 +992,7 @@ namespace ImGui IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. returns NULL when drag and drop is finished or inactive. use ImGuiPayload::IsDataType() to test for the payload type. - // Disabling [BETA API] + // Disabling // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) // - Tooltips windows are automatically opted out of disabling. Note that IsItemHovered() by default returns false on disabled items, unless using ImGuiHoveredFlags_AllowWhenDisabled. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index aa1b78509..13734d316 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 WIP +// dear imgui, v1.93.0 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d33cff20d..0d54ee8ad 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 WIP +// dear imgui, v1.93.0 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 74d91a7d4..420f070e8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 WIP +// dear imgui, v1.93.0 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0391bf735..a1757ed3f 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 WIP +// dear imgui, v1.93.0 // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 00129d7c5..821b15f44 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 WIP +// dear imgui, v1.93.0 // (widgets code) /* From 6d32174508fb8c518e7a832cc1d571fadd5cba76 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 14:03:51 +0200 Subject: [PATCH 170/245] Allow IM_NODEBUGSTEP to be defined by user. (#9584) Amend e2e9533991 --- imgui.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui.h b/imgui.h index df2d42675..a7b071dab 100644 --- a/imgui.h +++ b/imgui.h @@ -130,6 +130,7 @@ Index of this file: // Alternative to using a .natstepfilter file or other scripts in misc/debuggers/ to skip debug-stepping selected trivial functions. // If you get a compiler error or warning related to use, please report it to us! +#ifndef IM_NODEBUGSTEP #if (defined(__clang__) && (__clang_major__ >= 7)) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) #define IM_NODEBUGSTEP [[gnu::artificial]] #elif defined(_MSC_VER) && (_MSC_VER >= 1915) @@ -137,6 +138,7 @@ Index of this file: #else #define IM_NODEBUGSTEP #endif +#endif // Warnings #ifdef _MSC_VER From f9961262498b3a2606fefb1ef23d02412f7bb582 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Thu, 15 Oct 2026 14:28:13 +0200 Subject: [PATCH 171/245] Demo: correct demo markers wordings (#9586) --- imgui_demo.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 13734d316..1337d60ba 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1651,10 +1651,10 @@ static void DemoWindowWidgetsDragAndDrop() { if (ImGui::TreeNode("Drag and Drop")) { - IMGUI_DEMO_MARKER("Widgets/Drag and drop"); + IMGUI_DEMO_MARKER("Widgets/Drag and Drop"); if (ImGui::TreeNode("Drag and drop in standard widgets")) { - IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Standard widgets"); // ColorEdit widgets automatically act as drag source and drag target. // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F // to allow your own widgets to use colors in their drag and drop interaction. @@ -1669,7 +1669,7 @@ static void DemoWindowWidgetsDragAndDrop() if (ImGui::TreeNode("Drag and drop to copy/swap items")) { - IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); + IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Copy-swap items"); enum Mode { Mode_Copy, From cbe3d5fb887c3c5ab2949fc0762e7c4e97adeca7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 14:34:31 +0200 Subject: [PATCH 172/245] Version 1.93.1 WIP --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- misc/freetype/imgui_freetype.cpp | 3 ++- misc/freetype/imgui_freetype.h | 4 +++- 10 files changed, 23 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b5d983005..7389bba68 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.93.1 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.93.0 (Released 2026-10-14) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 3705e7262..4a4e1fe61 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 +// dear imgui, v1.93.1 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index a7b071dab..3e9a75715 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 +// dear imgui, v1.93.1 WIP // (headers) // Help: @@ -29,8 +29,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.93.0" -#define IMGUI_VERSION_NUM 19300 +#define IMGUI_VERSION "1.93.1 WIP" +#define IMGUI_VERSION_NUM 19301 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1337d60ba..14da0ee79 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 +// dear imgui, v1.93.1 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0d54ee8ad..9e4b1400e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 +// dear imgui, v1.93.1 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 420f070e8..14b8ce158 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 +// dear imgui, v1.93.1 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index a1757ed3f..ee208d160 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 +// dear imgui, v1.93.1 WIP // (tables and columns code) /* diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 821b15f44..3efccab30 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.0 +// dear imgui, v1.93.1 WIP // (widgets code) /* diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 375863fdf..975374554 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -1,5 +1,6 @@ -// dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder) +// dear imgui: FreeType font builder // (code) +// (used as a replacement for the stb_truetype builder) // Get the latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype // Original code by @vuhdo (Aleksei Skriabin) in 2017, with improvements by @mikesart. diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 85313699d..d271d49da 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -1,5 +1,6 @@ -// dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder) +// dear imgui: FreeType font builder // (headers) +// (used as a replacement for the stb_truetype builder) #pragma once #include "imgui.h" // IMGUI_API @@ -40,6 +41,7 @@ enum ImGuiFreeTypeLoaderFlags_ ImGuiFreeTypeLoaderFlags_Bitmap = 1 << 9, // Enable FreeType bitmap glyphs #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // Renamed in 1.92.0 (June 2025) ImGuiFreeTypeBuilderFlags_NoHinting = ImGuiFreeTypeLoaderFlags_NoHinting, ImGuiFreeTypeBuilderFlags_NoAutoHint = ImGuiFreeTypeLoaderFlags_NoAutoHint, ImGuiFreeTypeBuilderFlags_ForceAutoHint = ImGuiFreeTypeLoaderFlags_ForceAutoHint, From 93a14c8fda0068cc93f726719422dc319bdbb5e7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 14:51:48 +0200 Subject: [PATCH 173/245] (Breaking) Commented out legacy names/functions which were obsoleted from 1.90.7 (May 2024) to 1.91.0 (Sept 2024). --- docs/CHANGELOG.txt | 16 ++++++++++++++++ imgui.cpp | 10 ++++++++++ imgui.h | 25 +++++++++++++------------ 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7389bba68..52e22d779 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,22 @@ HOW TO UPDATE? Breaking Changes: +Autumn cleanup of stuff marked obsolete more than two years ago: + +- Commented out legacy names/functions which were obsoleted in 1.90.7 (May 2024); + - `ImGuiMod_Shortcut` --> `ImGuiMod_Ctrl` (since 1.90.7 it maps to Cmd on macOS) +- Commented out legacy names/functions which were obsoleted in 1.90.9 (July 2024); + - `ImGuiCol_TabActive` --> `ImGuiCol_TabSelected` + - `ImGuiCol_TabUnfocused` --> `ImGuiCol_TabDimmed` + - `ImGuiCol_TabUnfocusedActive` --> `ImGuiCol_TabDimmedSelected` +- Commented out legacy names/functions which were obsoleted in 1.91.0 (July 2024); + - `ImGuiSelectableFlags_DontClosePopups` --> `ImGuiSelectableFlags_NoAutoClosePopups` + - `PushButtonRepeat(bool repeat)` --> `PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat)` + - `PopButtonRepeat()` --> `PopItemFlag()` + - `PushTabStop(bool tab_stop)` --> `PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);` + - `PopTabStop()` --> `PopItemFlag()` + + Other Changes: diff --git a/imgui.cpp b/imgui.cpp index 4a4e1fe61..7947d5b72 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -395,6 +395,16 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + 2026/10/15 (1.93.1) - commented out legacy names/functions which were obsoleted from 1.90.7 (May 2024) to 1.91.1 (Sept 2024): + - `ImGuiMod_Shortcut` --> `ImGuiMod_Ctrl` (since 1.90.7 it maps to Cmd on macOS) + - `ImGuiCol_TabActive` --> `ImGuiCol_TabSelected` + - `ImGuiCol_TabUnfocused` --> `ImGuiCol_TabDimmed` + - `ImGuiCol_TabUnfocusedActive` --> `ImGuiCol_TabDimmedSelected` + - `ImGuiSelectableFlags_DontClosePopups`-> `ImGuiSelectableFlags_NoAutoClosePopups` + - `PushButtonRepeat(bool repeat)` --> `PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat)` + - `PopButtonRepeat()` --> `PopItemFlag()` + - `PushTabStop(bool tab_stop)` --> `PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);` + - `PopTabStop()` --> `PopItemFlag()` 2026/10/07 (1.93.0) - large cleanup/refactor of ImDrawList. many issues and inconsistencies fixed! (#9504) BELOW IS A SIMPLIFIED/SHORTENED RECAP OF CHANGES. READ CHANGELOG AND LINKS ABOVE FOR MORE DETAILS! useful links: diff --git a/imgui.h b/imgui.h index 3e9a75715..c9db02149 100644 --- a/imgui.h +++ b/imgui.h @@ -1409,7 +1409,7 @@ enum ImGuiSelectableFlags_ ImGuiSelectableFlags_SelectOnNav = 1 << 6, // Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 + //ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 //ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 #endif }; @@ -1712,7 +1712,7 @@ enum ImGuiKey : int #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was misleading (since named keys don't start at 0 anymore) - ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl + //ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl (will auto map to Cmd on Mac) //ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 #endif @@ -1841,10 +1841,10 @@ enum ImGuiCol_ ImGuiCol_COUNT, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] - ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] - ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] - ImGuiCol_NavHighlight = ImGuiCol_NavCursor, // [renamed in 1.91.4] + ImGuiCol_NavHighlight = ImGuiCol_NavCursor, // [renamed in 1.91.4] + //ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] + //ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] + //ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] #endif }; @@ -2680,7 +2680,7 @@ struct ImGuiIO #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS float FontGlobalScale; // Moved io.FontGlobalScale to style.FontScaleMain in 1.92.0 (June 2025) - // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. + // [Moved in 1.91.1] Clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). const char* (*GetClipboardTextFn)(void* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); @@ -3599,7 +3599,7 @@ struct ImDrawData ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overridden or set to NULL if you want to manually update textures. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - int CmdListsCount; // Use CmdLists.Size instead. Number of ImDrawList* to render. + int CmdListsCount; // [OBSOLETED in 1.92.9] Use CmdLists.Size instead. Number of ImDrawList* to render. #endif // Functions @@ -4231,16 +4231,17 @@ namespace ImGui // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) - inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } - inline void PopButtonRepeat() { PopItemFlag(); } - inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - inline void PopTabStop() { PopItemFlag(); } // You do not need those functions! See #7838 on GitHub for more info. IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + // OBSOLETED in 1.91.0 (from July 2024) + //inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } + //inline void PopButtonRepeat() { PopItemFlag(); } + //inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + //inline void PopTabStop() { PopItemFlag(); } // OBSOLETED in 1.90.0 (from September 2023) //IMGUI_API bool Combo(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. //IMGUI_API bool ListBox(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. From 1ff218165d71800455a1e8432bada8266f6d5cca Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 14:52:02 +0200 Subject: [PATCH 174/245] (Breaking) Commented out legacy names/functions which were obsoleted in 1.91.1 (Sept 2024). --- docs/CHANGELOG.txt | 7 +++++++ imgui.cpp | 11 +++++++---- imgui.h | 6 +++--- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 52e22d779..50b16b595 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,13 @@ Autumn cleanup of stuff marked obsolete more than two years ago: - `PopButtonRepeat()` --> `PopItemFlag()` - `PushTabStop(bool tab_stop)` --> `PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);` - `PopTabStop()` --> `PopItemFlag()` +- Commented out legacy names/functions which were obsoleted in 1.91.1 (Sept 2024); + - `io.GetClipboardTextFn` --> `platform_io.Platform_GetClipboardTextFn` + - `io.SetClipboardTextFn` --> `platform_io.Platform_SetClipboardTextFn` + - `io.ClipboardUserData` --> `platform_io.Platform_ClipboardUserData` + +Please also try to get rid of calls to `GetContentRegionMax()`, `GetWindowContentRegionMin()` +and `GetWindowContentRegionMax()`: you do NOT need those functions. See #7838. Other Changes: diff --git a/imgui.cpp b/imgui.cpp index 7947d5b72..256486f6b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -405,6 +405,9 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: - `PopButtonRepeat()` --> `PopItemFlag()` - `PushTabStop(bool tab_stop)` --> `PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);` - `PopTabStop()` --> `PopItemFlag()` + - `io.GetClipboardTextFn` --> `platform_io.Platform_GetClipboardTextFn` + - `io.SetClipboardTextFn` --> `platform_io.Platform_SetClipboardTextFn` + - `io.ClipboardUserData` --> `platform_io.Platform_ClipboardUserData` 2026/10/07 (1.93.0) - large cleanup/refactor of ImDrawList. many issues and inconsistencies fixed! (#9504) BELOW IS A SIMPLIFIED/SHORTENED RECAP OF CHANGES. READ CHANGELOG AND LINKS ABOVE FOR MORE DETAILS! useful links: @@ -11254,10 +11257,10 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() } // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024) - if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl)) - g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); }; - if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl)) - g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); }; + //if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl)) + // g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); }; + //if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl)) + // g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); }; // Remap legacy CurveTessellationTol into CurveTessellationMaxError (OBSOLETED in 1.93.0, August 2026) if (g.Style.CurveTessellationTol != 0.0f) diff --git a/imgui.h b/imgui.h index c9db02149..18ca1a33d 100644 --- a/imgui.h +++ b/imgui.h @@ -2682,9 +2682,9 @@ struct ImGuiIO // [Moved in 1.91.1] Clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). - const char* (*GetClipboardTextFn)(void* user_data); - void (*SetClipboardTextFn)(void* user_data, const char* text); - void* ClipboardUserData; + //const char* (*GetClipboardTextFn)(void* user_data); // --> `platform_io.Platform_GetClipboardTextFn` + //void (*SetClipboardTextFn)(void* user_data, const char* text); // --> `platform_io.Platform_SetClipboardTextFn` + //void* ClipboardUserData; // --> `platform_io.Platform_ClipboardUserData` //void ClearInputCharacters() { InputQueueCharacters.resize(0); } // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue. #endif From 4c9c888fc5f5fec3de99de61e05dcfc86259394a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 15:39:58 +0200 Subject: [PATCH 175/245] Build: warning fixes for VS2015 and Size; - bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size); + bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size) != 0; memcpy(p_v, &g.ActiveIdValueOnActivation, data_size); ClearActiveID(); return value_changed; @@ -3322,7 +3322,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type { // Canceling action reverts to initial value size_t data_size = DataTypeGetInfo(data_type)->Size; - bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size); + bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size) != 0; memcpy(p_v, &g.ActiveIdValueOnActivation, data_size); ClearActiveID(); return value_changed; From 145a2fbab64b320f8755f299eeb305c9d5e43c18 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 16:24:58 +0200 Subject: [PATCH 176/245] Docs: update binaries. --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index 91bc92cde..517f32a9f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -113,7 +113,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas - [imgui_explorer](https://pthom.github.io/imgui_explorer): Web version of the demo w/ source code browser, courtesy of [@pthom](https://github.com/pthom). You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: -- [imgui-demo-binaries-20260225.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20260225.zip) (Windows, 1.92.6, built 2026/02/25, master) or [older binaries](https://www.dearimgui.com/binaries). +- [imgui-demo-binaries-20261015.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20261015.zip) (Win32, 1.93.0, built 2026/10/15, master) or [older binaries](https://www.dearimgui.com/binaries). ### Gallery From f5d2b7dd01205b0f389ee26d11aa1b767ee87c94 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 16:32:52 +0200 Subject: [PATCH 177/245] CI: fixes for macOS. --- .github/workflows/build.yml | 2 +- docs/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4e276e1de..0dcab4688 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -523,7 +523,7 @@ jobs: - name: Install Dependencies run: | - brew install glfw3 sdl2 sdl3 + brew install glfw sdl2 sdl3 - name: Build example_null (extra warnings, clang 64-bit) run: make -C examples/example_null WITH_EXTRA_WARNINGS=1 diff --git a/docs/README.md b/docs/README.md index 517f32a9f..1dea58176 100644 --- a/docs/README.md +++ b/docs/README.md @@ -113,7 +113,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas - [imgui_explorer](https://pthom.github.io/imgui_explorer): Web version of the demo w/ source code browser, courtesy of [@pthom](https://github.com/pthom). You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: -- [imgui-demo-binaries-20261015.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20261015.zip) (Win32, 1.93.0, built 2026/10/15, master) or [older binaries](https://www.dearimgui.com/binaries). +- [imgui-demo-binaries-20261015-win32.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20261015-win32.zip) (Win32, 1.93.0, built 2026/10/15, master) or [older binaries](https://www.dearimgui.com/binaries). ### Gallery From c7d17f01cd3e14bbc9b33cee44e0a2d6f3a2a524 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 17:56:20 +0200 Subject: [PATCH 178/245] ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2 --- docs/CHANGELOG.txt | 10 +++++++--- imgui.cpp | 9 +++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 50b16b595..0576968ca 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,13 +59,17 @@ Autumn cleanup of stuff marked obsolete more than two years ago: - `io.GetClipboardTextFn` --> `platform_io.Platform_GetClipboardTextFn` - `io.SetClipboardTextFn` --> `platform_io.Platform_SetClipboardTextFn` - `io.ClipboardUserData` --> `platform_io.Platform_ClipboardUserData` - -Please also try to get rid of calls to `GetContentRegionMax()`, `GetWindowContentRegionMin()` -and `GetWindowContentRegionMax()`: you do NOT need those functions. See #7838. +- Please also try to get rid of calls to `GetContentRegionMax()`, `GetWindowContentRegionMin()` + and `GetWindowContentRegionMax()` will may be removed soon-ish: you should not + ever need those functions. See #7838. Other Changes: +- ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro + adds an extra `operator=` to ImVec2. This isn't supported but should not + be needed as you should have a constructor to convert from your type to ImVec2. + ----------------------------------------------------------------------- VERSION 1.93.0 (Released 2026-10-14) diff --git a/imgui.cpp b/imgui.cpp index 256486f6b..a970e92ca 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11208,6 +11208,15 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct! if (true) IM_ASSERT(1); else IM_ASSERT(0); + // Check user IM_VEC2_CLASS_EXTRA macro + // (IF YOU GET A "ambiguous overload" COMPILE ERROR HERE: does your IM_VEC2_CLASS_EXTRA macro contains an operator=? + // e.g. ImVec2& operator=(const MyPoint & p) { x = p.x; y = p.y; return *this; } + // You should be able to remove it if you have the corresponding constructor: + // e.g. IM_NODEBUGSTEP constexpr inline ImVec2(const MyPoint& f) : x(f.x), y(f.y) {} + // Allowing you to add this extra operator to ImVec2 would prevent our whole codebase from using v = {x,y} assignment style. + // PLEASE GET IN TOUCH IF REMOVING THE operator= IS A PROBLEM TO YOU) + ImVec2 v; v = { 1.0f, 2.0f }; + // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644) // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it. #ifdef __EMSCRIPTEN__ From 49a14503601b08c23ea137944cdb293a4ff08a2e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 18:53:04 +0200 Subject: [PATCH 179/245] DrawList: added missing ImDrawFlags_RoundCornersMask_ -> ImDrawFlags_RoundMask_ legacy redirect. Amend 0e756a6. --- docs/CHANGELOG.txt | 1 + imgui.h | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0576968ca..609b3ba60 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -205,6 +205,7 @@ Breaking Changes: - `ImDrawFlags_RoundCornersBottom` -> `ImDrawFlags_RoundBottom` - `ImDrawFlags_RoundCornersLeft` -> `ImDrawFlags_RoundLeft` - `ImDrawFlags_RoundCornersRight` -> `ImDrawFlags_RoundRight` + - `ImDrawFlags_RoundCornersMask_` -> `ImDrawFlags_RoundMask_` Kept redirection enums (will obsolete). - Marked `ImDrawListFlags_AntiAliasedLinesUseTex` and `style.AntiAliasedLinesUseTex` as obsolete, as the new line rendering code always uses textures. diff --git a/imgui.h b/imgui.h index 18ca1a33d..fdbcf80ba 100644 --- a/imgui.h +++ b/imgui.h @@ -3391,7 +3391,8 @@ enum ImDrawFlags_ ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundTop, ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundBottom, ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundLeft, - ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundRight, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundRight, + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundMask_, #endif }; From 9d9a621f339460e8a9dc49b2ad164d6acade1aff Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 19:41:17 +0200 Subject: [PATCH 180/245] Fonts: expose ImFontBaked_BuildLoadGlyphAdvanceX() in imgui_internal.h. --- imgui_draw.cpp | 2 +- imgui_internal.h | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2c197dacc..f5ea37700 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -6156,7 +6156,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep return NULL; } -static float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) +float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) { if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE || baked->LoadNoRenderOnLayout) { diff --git a/imgui_internal.h b/imgui_internal.h index 14b8ce158..875c51f42 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -4132,6 +4132,8 @@ IMGUI_API void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* a IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); +IMGUI_API float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint); + IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); From 4be0b47ecc0edd535a40a79f6ceb6f1ac5936483 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 16 Oct 2026 16:43:40 +0200 Subject: [PATCH 181/245] (Breaking) Internals: ImStricmp/ImStrnicmp returned opposite sign when strings were different + ones in Demo. Main functions unused by core imgui, so not strictly changing anything. Demo functions were only comparing to 0. --- imgui.cpp | 4 ++-- imgui_demo.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a970e92ca..7ee86218e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2265,14 +2265,14 @@ ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, int ImStricmp(const char* str1, const char* str2) { int d; - while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; } + while ((d = ImToUpper(*str1) - ImToUpper(*str2)) == 0 && *str1) { str1++; str2++; } return d; } int ImStrnicmp(const char* str1, const char* str2, size_t count) { int d = 0; - while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; } + while (count > 0 && (d = ImToUpper(*str1) - ImToUpper(*str2)) == 0 && *str1) { str1++; str2++; count--; } return d; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 14da0ee79..ede2eeb07 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -9211,8 +9211,8 @@ struct ExampleAppConsole } // Portable helpers - static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; } - static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; } + static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s1) - toupper(*s2)) == 0 && *s1) { s1++; s2++; } return d; } + static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s1) - toupper(*s2)) == 0 && *s1) { s1++; s2++; n--; } return d; } static char* Strdup(const char* s) { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = ImGui::MemAlloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); } static void Strtrimblanks(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; } From 7bd38119c7288d77de31cde9a7eeb568405090c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Cicho=C5=84?= Date: Fri, 23 Oct 2026 14:22:52 +0200 Subject: [PATCH 182/245] Internals: CallContextHooks(): fixed iterating a reallocated array when a hook callback adds a hook. (#9590) Note that Test Engine GuiFunc code is called within a hook anyhow. --- imgui.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7ee86218e..585e8a9b2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4740,12 +4740,13 @@ void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id) // Call context hooks (used by e.g. test engine) // We assume a small number of hooks so all stored in same array +// Iterate by index: a callback may add a hook, which reallocates the array. Hooks added here are called from the next call. void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type) { ImGuiContext& g = *ctx; - for (ImGuiContextHook& hook : g.Hooks) - if (hook.Type == hook_type) - hook.Callback(&g, &hook); + for (int n = 0, hooks_count = g.Hooks.Size; n < hooks_count; n++) + if (g.Hooks[n].Type == hook_type) + g.Hooks[n].Callback(&g, &g.Hooks[n]); } //----------------------------------------------------------------------------- From 2b7a9dcca44011a1ff82833bfeab6a66b8213a71 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Oct 2026 14:41:01 +0200 Subject: [PATCH 183/245] Examples: remove references to DXSDK_DIR which is for DX9. (realized this while reviewing #9593) --- examples/example_null/example_null.vcxproj | 20 +++++++++++-------- .../example_sdl2_directx11/build_win32.bat | 4 ++-- .../example_sdl2_directx11.vcxproj | 10 +++++----- .../example_sdl3_directx11/build_win32.bat | 4 ++-- .../example_sdl3_directx11.vcxproj | 10 +++++----- .../example_win32_directx10/build_win32.bat | 4 ++-- .../example_win32_directx10.vcxproj | 10 +++++----- .../example_win32_directx11/build_win32.bat | 4 ++-- .../example_win32_directx11.vcxproj | 10 +++++----- 9 files changed, 40 insertions(+), 36 deletions(-) diff --git a/examples/example_null/example_null.vcxproj b/examples/example_null/example_null.vcxproj index 61e388f96..1353fc0b3 100644 --- a/examples/example_null/example_null.vcxproj +++ b/examples/example_null/example_null.vcxproj @@ -92,8 +92,9 @@ true - d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + + + %(AdditionalLibraryDirectories) Console @@ -107,8 +108,9 @@ true - d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + + + %(AdditionalLibraryDirectories) Console @@ -126,8 +128,9 @@ true true true - d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + + + %(AdditionalLibraryDirectories) Console @@ -145,8 +148,9 @@ true true true - d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + + + %(AdditionalLibraryDirectories) Console diff --git a/examples/example_sdl2_directx11/build_win32.bat b/examples/example_sdl2_directx11/build_win32.bat index f0b485ca6..135c3bb50 100644 --- a/examples/example_sdl2_directx11/build_win32.bat +++ b/examples/example_sdl2_directx11/build_win32.bat @@ -1,8 +1,8 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_sdl2_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" @set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib shell32.lib +@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib d3d11.lib d3dcompiler.lib shell32.lib mkdir %OUT_DIR% cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj index afa9d5de4..4ba9ac321 100644 --- a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj +++ b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj @@ -97,7 +97,7 @@ true - %SDL2_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x86;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -113,7 +113,7 @@ true - %SDL2_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x64;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -133,7 +133,7 @@ true true true - %SDL2_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x86;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -154,7 +154,7 @@ true true true - %SDL2_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x64;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -186,4 +186,4 @@ - \ No newline at end of file + diff --git a/examples/example_sdl3_directx11/build_win32.bat b/examples/example_sdl3_directx11/build_win32.bat index b84b01f1a..41bb8449b 100644 --- a/examples/example_sdl3_directx11/build_win32.bat +++ b/examples/example_sdl3_directx11/build_win32.bat @@ -1,8 +1,8 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_sdl3_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" @set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib shell32.lib +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib d3d11.lib d3dcompiler.lib shell32.lib mkdir %OUT_DIR% cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj index 057874196..8729480a5 100644 --- a/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj +++ b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj @@ -97,7 +97,7 @@ true - %SDL3_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -113,7 +113,7 @@ true - %SDL3_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -133,7 +133,7 @@ true true true - %SDL3_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -154,7 +154,7 @@ true true true - %SDL3_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -186,4 +186,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx10/build_win32.bat b/examples/example_win32_directx10/build_win32.bat index 78a6e374d..b65d31ab2 100644 --- a/examples/example_win32_directx10/build_win32.bat +++ b/examples/example_win32_directx10/build_win32.bat @@ -1,8 +1,8 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_win32_directx10 -@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" @set SOURCES=main.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\backends\imgui_impl_dx10.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d10.lib d3dcompiler.lib +@set LIBS=d3d10.lib d3dcompiler.lib mkdir %OUT_DIR% cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index add37ed97..89e9393ab 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -93,7 +93,7 @@ true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -108,7 +108,7 @@ true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -127,7 +127,7 @@ true true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -146,7 +146,7 @@ true true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -175,4 +175,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx11/build_win32.bat b/examples/example_win32_directx11/build_win32.bat index c9a717c60..fb4c09cf2 100644 --- a/examples/example_win32_directx11/build_win32.bat +++ b/examples/example_win32_directx11/build_win32.bat @@ -1,9 +1,9 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_win32_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" @set SOURCES=main.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib +@set LIBS=d3d11.lib d3dcompiler.lib mkdir %OUT_DIR% cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index ed0b509a8..ace899cb5 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -93,7 +93,7 @@ true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -108,7 +108,7 @@ true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -127,7 +127,7 @@ true true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -146,7 +146,7 @@ true true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) + %(AdditionalLibraryDirectories) Console @@ -175,4 +175,4 @@ - \ No newline at end of file + From 6dd654f27a8dbfe8c81b7ed98a5e16539da68e74 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Oct 2026 15:08:53 +0200 Subject: [PATCH 184/245] Examples: renamed various helper batch files from build_win32.bat to build_win.bat. (also came to this while reviewing #9593) --- .github/workflows/build.yml | 2 +- docs/CHANGELOG.txt | 3 +++ examples/example_null/{build_win32.bat => build_win.bat} | 2 +- .../example_win32_directx10/{build_win32.bat => build_win.bat} | 2 +- .../example_win32_directx11/{build_win32.bat => build_win.bat} | 2 +- .../example_win32_directx12/{build_win32.bat => build_win.bat} | 2 +- .../example_win32_opengl3/{build_win32.bat => build_win.bat} | 2 +- 7 files changed, 9 insertions(+), 6 deletions(-) rename examples/example_null/{build_win32.bat => build_win.bat} (74%) rename examples/example_win32_directx10/{build_win32.bat => build_win.bat} (88%) rename examples/example_win32_directx11/{build_win32.bat => build_win.bat} (88%) rename examples/example_win32_directx12/{build_win32.bat => build_win.bat} (88%) rename examples/example_win32_opengl3/{build_win32.bat => build_win.bat} (86%) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0dcab4688..fa3496d83 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -77,7 +77,7 @@ jobs: run: | cd examples\example_null call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" - .\build_win32.bat /W4 + .\build_win.bat /W4 - name: Build example_null (single file build) shell: bash diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 609b3ba60..c05cb8961 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,9 @@ Other Changes: - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. +- Examples: renamed various helper batch files from build_win32.bat to build_win.bat + to reflect that they can also build X64 or ARM64, given the right environment. + Kept both build_win32.bat and build_win64.bat for examples needing them. ----------------------------------------------------------------------- diff --git a/examples/example_null/build_win32.bat b/examples/example_null/build_win.bat similarity index 74% rename from examples/example_null/build_win32.bat rename to examples/example_null/build_win.bat index be81d8093..6c4d4e036 100644 --- a/examples/example_null/build_win32.bat +++ b/examples/example_null/build_win.bat @@ -1,3 +1,3 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat, or vcvarsall.bat to setup command-line compiler. mkdir Debug cl /nologo /Zi /MD /utf-8 /I ..\.. %* *.cpp ..\..\*.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib diff --git a/examples/example_win32_directx10/build_win32.bat b/examples/example_win32_directx10/build_win.bat similarity index 88% rename from examples/example_win32_directx10/build_win32.bat rename to examples/example_win32_directx10/build_win.bat index b65d31ab2..d7d2f5a6a 100644 --- a/examples/example_win32_directx10/build_win32.bat +++ b/examples/example_win32_directx10/build_win.bat @@ -1,4 +1,4 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_win32_directx10 @set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" diff --git a/examples/example_win32_directx11/build_win32.bat b/examples/example_win32_directx11/build_win.bat similarity index 88% rename from examples/example_win32_directx11/build_win32.bat rename to examples/example_win32_directx11/build_win.bat index fb4c09cf2..78758193d 100644 --- a/examples/example_win32_directx11/build_win32.bat +++ b/examples/example_win32_directx11/build_win.bat @@ -1,4 +1,4 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat, or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_win32_directx11 @set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" diff --git a/examples/example_win32_directx12/build_win32.bat b/examples/example_win32_directx12/build_win.bat similarity index 88% rename from examples/example_win32_directx12/build_win32.bat rename to examples/example_win32_directx12/build_win.bat index cb5e8e273..d609c7203 100644 --- a/examples/example_win32_directx12/build_win32.bat +++ b/examples/example_win32_directx12/build_win.bat @@ -1,4 +1,4 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat, or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_win32_directx12 @set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" diff --git a/examples/example_win32_opengl3/build_win32.bat b/examples/example_win32_opengl3/build_win.bat similarity index 86% rename from examples/example_win32_opengl3/build_win32.bat rename to examples/example_win32_opengl3/build_win.bat index 48df08087..0bedfc19f 100644 --- a/examples/example_win32_opengl3/build_win32.bat +++ b/examples/example_win32_opengl3/build_win.bat @@ -1,4 +1,4 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug @set OUT_EXE=example_win32_opengl3 @set INCLUDES=/I..\.. /I..\..\backends From 20ba6c4a281fc7b21b7569c01b154b825153a123 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Oct 2026 16:09:45 +0200 Subject: [PATCH 185/245] Examples: refactored remaining batch files to detect architecture. (also came to this while reviewing #9593) --- docs/CHANGELOG.txt | 2 +- examples/example_glfw_opengl2/build_win.bat | 21 ++++++++++++++++ examples/example_glfw_opengl2/build_win32.bat | 8 ------ examples/example_glfw_opengl3/build_win.bat | 21 ++++++++++++++++ examples/example_glfw_opengl3/build_win32.bat | 8 ------ examples/example_glfw_vulkan/build_win.bat | 25 +++++++++++++++++++ examples/example_glfw_vulkan/build_win32.bat | 14 ----------- examples/example_glfw_vulkan/build_win64.bat | 14 ----------- examples/example_sdl2_directx11/build_win.bat | 21 ++++++++++++++++ .../example_sdl2_directx11/build_win32.bat | 8 ------ examples/example_sdl2_opengl2/build_win.bat | 21 ++++++++++++++++ examples/example_sdl2_opengl2/build_win32.bat | 8 ------ examples/example_sdl2_opengl3/README.md | 2 +- examples/example_sdl2_opengl3/build_win.bat | 21 ++++++++++++++++ examples/example_sdl2_opengl3/build_win32.bat | 8 ------ .../example_sdl2_sdlrenderer2/build_win.bat | 21 ++++++++++++++++ .../example_sdl2_sdlrenderer2/build_win32.bat | 8 ------ examples/example_sdl2_vulkan/build_win.bat | 25 +++++++++++++++++++ examples/example_sdl2_vulkan/build_win32.bat | 14 ----------- examples/example_sdl2_vulkan/build_win64.bat | 14 ----------- examples/example_sdl3_directx11/build_win.bat | 21 ++++++++++++++++ .../example_sdl3_directx11/build_win32.bat | 8 ------ examples/example_sdl3_opengl3/README.md | 2 +- examples/example_sdl3_opengl3/build_win.bat | 25 +++++++++++++++++++ examples/example_sdl3_opengl3/build_win32.bat | 14 ----------- examples/example_sdl3_opengl3/build_win64.bat | 14 ----------- .../example_sdl3_sdlrenderer3/build_win.bat | 21 ++++++++++++++++ .../example_sdl3_sdlrenderer3/build_win32.bat | 8 ------ examples/example_sdl3_vulkan/build_win.bat | 25 +++++++++++++++++++ examples/example_sdl3_vulkan/build_win32.bat | 14 ----------- examples/example_sdl3_vulkan/build_win64.bat | 14 ----------- examples/example_win32_directx9/build_win.bat | 21 ++++++++++++++++ .../example_win32_directx9/build_win32.bat | 8 ------ examples/example_win32_vulkan/build_win.bat | 21 ++++++++++++++++ examples/example_win32_vulkan/build_win32.bat | 9 ------- examples/example_win32_vulkan/build_win64.bat | 9 ------- 36 files changed, 313 insertions(+), 205 deletions(-) create mode 100644 examples/example_glfw_opengl2/build_win.bat delete mode 100644 examples/example_glfw_opengl2/build_win32.bat create mode 100644 examples/example_glfw_opengl3/build_win.bat delete mode 100644 examples/example_glfw_opengl3/build_win32.bat create mode 100644 examples/example_glfw_vulkan/build_win.bat delete mode 100644 examples/example_glfw_vulkan/build_win32.bat delete mode 100644 examples/example_glfw_vulkan/build_win64.bat create mode 100644 examples/example_sdl2_directx11/build_win.bat delete mode 100644 examples/example_sdl2_directx11/build_win32.bat create mode 100644 examples/example_sdl2_opengl2/build_win.bat delete mode 100644 examples/example_sdl2_opengl2/build_win32.bat create mode 100644 examples/example_sdl2_opengl3/build_win.bat delete mode 100644 examples/example_sdl2_opengl3/build_win32.bat create mode 100644 examples/example_sdl2_sdlrenderer2/build_win.bat delete mode 100644 examples/example_sdl2_sdlrenderer2/build_win32.bat create mode 100644 examples/example_sdl2_vulkan/build_win.bat delete mode 100644 examples/example_sdl2_vulkan/build_win32.bat delete mode 100644 examples/example_sdl2_vulkan/build_win64.bat create mode 100644 examples/example_sdl3_directx11/build_win.bat delete mode 100644 examples/example_sdl3_directx11/build_win32.bat create mode 100644 examples/example_sdl3_opengl3/build_win.bat delete mode 100644 examples/example_sdl3_opengl3/build_win32.bat delete mode 100644 examples/example_sdl3_opengl3/build_win64.bat create mode 100644 examples/example_sdl3_sdlrenderer3/build_win.bat delete mode 100644 examples/example_sdl3_sdlrenderer3/build_win32.bat create mode 100644 examples/example_sdl3_vulkan/build_win.bat delete mode 100644 examples/example_sdl3_vulkan/build_win32.bat delete mode 100644 examples/example_sdl3_vulkan/build_win64.bat create mode 100644 examples/example_win32_directx9/build_win.bat delete mode 100644 examples/example_win32_directx9/build_win32.bat create mode 100644 examples/example_win32_vulkan/build_win.bat delete mode 100644 examples/example_win32_vulkan/build_win32.bat delete mode 100644 examples/example_win32_vulkan/build_win64.bat diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c05cb8961..fd490de77 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,7 +71,7 @@ Other Changes: be needed as you should have a constructor to convert from your type to ImVec2. - Examples: renamed various helper batch files from build_win32.bat to build_win.bat to reflect that they can also build X64 or ARM64, given the right environment. - Kept both build_win32.bat and build_win64.bat for examples needing them. + Made the script detect the environment when needed (e.g. to specify library path). ----------------------------------------------------------------------- diff --git a/examples/example_glfw_opengl2/build_win.bat b/examples/example_glfw_opengl2/build_win.bat new file mode 100644 index 000000000..cca29d76f --- /dev/null +++ b/examples/example_glfw_opengl2/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_glfw_opengl2 +@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp +@set LIBS=glfw3.lib opengl32.lib gdi32.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-32 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_opengl2/build_win32.bat b/examples/example_glfw_opengl2/build_win32.bat deleted file mode 100644 index 24c0e08fd..000000000 --- a/examples/example_glfw_opengl2/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_glfw_opengl2 -@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_opengl3/build_win.bat b/examples/example_glfw_opengl3/build_win.bat new file mode 100644 index 000000000..a39236cdd --- /dev/null +++ b/examples/example_glfw_opengl3/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_glfw_opengl3 +@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp +@set LIBS=glfw3.lib opengl32.lib gdi32.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-32 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_opengl3/build_win32.bat b/examples/example_glfw_opengl3/build_win32.bat deleted file mode 100644 index b5979ad49..000000000 --- a/examples/example_glfw_opengl3/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_glfw_opengl3 -@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_vulkan/build_win.bat b/examples/example_glfw_vulkan/build_win.bat new file mode 100644 index 000000000..0366b1b5d --- /dev/null +++ b/examples/example_glfw_vulkan/build_win.bat @@ -0,0 +1,25 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_glfw_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp +@set LIBS=glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% + +@set OUT_DIR=Release +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_vulkan/build_win32.bat b/examples/example_glfw_vulkan/build_win32.bat deleted file mode 100644 index bb54a4210..000000000 --- a/examples/example_glfw_vulkan/build_win32.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_glfw_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% - -@set OUT_DIR=Release -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_vulkan/build_win64.bat b/examples/example_glfw_vulkan/build_win64.bat deleted file mode 100644 index ca9b788d8..000000000 --- a/examples/example_glfw_vulkan/build_win64.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup 64-bit command-line compiler. - -@set OUT_EXE=example_glfw_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% - -@set OUT_DIR=Release -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_sdl2_directx11/build_win.bat b/examples/example_sdl2_directx11/build_win.bat new file mode 100644 index 000000000..6b279b937 --- /dev/null +++ b/examples/example_sdl2_directx11/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl2_directx11 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp +@set LIBS=SDL2.lib SDL2main.lib d3d11.lib d3dcompiler.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_directx11/build_win32.bat b/examples/example_sdl2_directx11/build_win32.bat deleted file mode 100644 index 135c3bb50..000000000 --- a/examples/example_sdl2_directx11/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_sdl2_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib d3d11.lib d3dcompiler.lib shell32.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_opengl2/build_win.bat b/examples/example_sdl2_opengl2/build_win.bat new file mode 100644 index 000000000..945464c00 --- /dev/null +++ b/examples/example_sdl2_opengl2/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl2_opengl2 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp +@set LIBS=SDL2.lib SDL2main.lib opengl32.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_opengl2/build_win32.bat b/examples/example_sdl2_opengl2/build_win32.bat deleted file mode 100644 index 7543edafc..000000000 --- a/examples/example_sdl2_opengl2/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_sdl2_opengl2 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib shell32.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_opengl3/README.md b/examples/example_sdl2_opengl3/README.md index 81fd9fe7b..e62dec255 100644 --- a/examples/example_sdl2_opengl3/README.md +++ b/examples/example_sdl2_opengl3/README.md @@ -7,7 +7,7 @@ Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) i ## Windows with Visual Studio's CLI -Use build_win32.bat or directly: +Use build_win.bat or directly: ``` set SDL2_DIR=path_to_your_sdl2_folder cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl2_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console diff --git a/examples/example_sdl2_opengl3/build_win.bat b/examples/example_sdl2_opengl3/build_win.bat new file mode 100644 index 000000000..7d8dd115c --- /dev/null +++ b/examples/example_sdl2_opengl3/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl2_opengl3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp +@set LIBS=SDL2.lib SDL2main.lib opengl32.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_opengl3/build_win32.bat b/examples/example_sdl2_opengl3/build_win32.bat deleted file mode 100644 index 7b2fac922..000000000 --- a/examples/example_sdl2_opengl3/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_sdl2_opengl3 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib shell32.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_sdlrenderer2/build_win.bat b/examples/example_sdl2_sdlrenderer2/build_win.bat new file mode 100644 index 000000000..82bc8613b --- /dev/null +++ b/examples/example_sdl2_sdlrenderer2/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl2_sdlrenderer_ +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_sdlrenderer2.cpp ..\..\imgui*.cpp +@set LIBS=SDL2.lib SDL2main.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_sdlrenderer2/build_win32.bat b/examples/example_sdl2_sdlrenderer2/build_win32.bat deleted file mode 100644 index e311bfcd0..000000000 --- a/examples/example_sdl2_sdlrenderer2/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_sdl2_sdlrenderer_ -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_sdlrenderer2.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_vulkan/build_win.bat b/examples/example_sdl2_vulkan/build_win.bat new file mode 100644 index 000000000..2b2fedcaa --- /dev/null +++ b/examples/example_sdl2_vulkan/build_win.bat @@ -0,0 +1,25 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl2_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp +@set LIBS=SDL2.lib SDL2main.lib shell32.lib vulkan-1.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_vulkan/build_win32.bat b/examples/example_sdl2_vulkan/build_win32.bat deleted file mode 100644 index f634aba00..000000000 --- a/examples/example_sdl2_vulkan/build_win32.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_sdl2_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 SDL2.lib SDL2main.lib shell32.lib vulkan-1.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_vulkan/build_win64.bat b/examples/example_sdl2_vulkan/build_win64.bat deleted file mode 100644 index 5d315cca2..000000000 --- a/examples/example_sdl2_vulkan/build_win64.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_sdl2_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib SDL2.lib SDL2main.lib shell32.lib vulkan-1.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_directx11/build_win.bat b/examples/example_sdl3_directx11/build_win.bat new file mode 100644 index 000000000..a619de03f --- /dev/null +++ b/examples/example_sdl3_directx11/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl3_directx11 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp +@set LIBS=SDL3.lib d3d11.lib d3dcompiler.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_directx11/build_win32.bat b/examples/example_sdl3_directx11/build_win32.bat deleted file mode 100644 index 41bb8449b..000000000 --- a/examples/example_sdl3_directx11/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_sdl3_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib d3d11.lib d3dcompiler.lib shell32.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_opengl3/README.md b/examples/example_sdl3_opengl3/README.md index a032f8752..bc748afac 100644 --- a/examples/example_sdl3_opengl3/README.md +++ b/examples/example_sdl3_opengl3/README.md @@ -7,7 +7,7 @@ Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) i ## Windows with Visual Studio's CLI -Use build_win32.bat or directly: +Use build_win.bat or directly: ``` set SDL3_DIR=path_to_your_sdl3_folder cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL3_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL3_DIR%\lib\x86 SDL3.lib opengl32.lib /subsystem:console diff --git a/examples/example_sdl3_opengl3/build_win.bat b/examples/example_sdl3_opengl3/build_win.bat new file mode 100644 index 000000000..0eeef3e0c --- /dev/null +++ b/examples/example_sdl3_opengl3/build_win.bat @@ -0,0 +1,25 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl3_opengl3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp +@set LIBS=SDL3.lib opengl32.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_opengl3/build_win32.bat b/examples/example_sdl3_opengl3/build_win32.bat deleted file mode 100644 index 5bed40ac1..000000000 --- a/examples/example_sdl3_opengl3/build_win32.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_sdl3_opengl3 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib opengl32.lib shell32.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_opengl3/build_win64.bat b/examples/example_sdl3_opengl3/build_win64.bat deleted file mode 100644 index 87c6bb8b5..000000000 --- a/examples/example_sdl3_opengl3/build_win64.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_sdl3_opengl3 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 SDL3.lib opengl32.lib shell32.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_sdlrenderer3/build_win.bat b/examples/example_sdl3_sdlrenderer3/build_win.bat new file mode 100644 index 000000000..86c8bed44 --- /dev/null +++ b/examples/example_sdl3_sdlrenderer3/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl3_sdlrenderer3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlrenderer3.cpp ..\..\imgui*.cpp +@set LIBS=SDL3.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_sdlrenderer3/build_win32.bat b/examples/example_sdl3_sdlrenderer3/build_win32.bat deleted file mode 100644 index 7bc131a6a..000000000 --- a/examples/example_sdl3_sdlrenderer3/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_sdl3_sdlrenderer3 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlrenderer3.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_vulkan/build_win.bat b/examples/example_sdl3_vulkan/build_win.bat new file mode 100644 index 000000000..e1ad37988 --- /dev/null +++ b/examples/example_sdl3_vulkan/build_win.bat @@ -0,0 +1,25 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl3_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp +@set LIBS=SDL3.lib shell32.lib vulkan-1.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_vulkan/build_win32.bat b/examples/example_sdl3_vulkan/build_win32.bat deleted file mode 100644 index 3e26d3088..000000000 --- a/examples/example_sdl3_vulkan/build_win32.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_sdl3_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 SDL3.lib shell32.lib vulkan-1.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_vulkan/build_win64.bat b/examples/example_sdl3_vulkan/build_win64.bat deleted file mode 100644 index 5d038d1ee..000000000 --- a/examples/example_sdl3_vulkan/build_win64.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_sdl3_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib SDL3.lib shell32.lib vulkan-1.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_win32_directx9/build_win.bat b/examples/example_win32_directx9/build_win.bat new file mode 100644 index 000000000..4523769df --- /dev/null +++ b/examples/example_win32_directx9/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_win32_directx9 +@set INCLUDES=/I..\.. /I..\..\backends /I "%DXSDK_DIR%/Include" +@set SOURCES=main.cpp ..\..\backends\imgui_impl_dx9.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp +@set LIBS=d3d9.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:"%DXSDK_DIR%/Lib/x86" +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:"%DXSDK_DIR%/Lib/x64" + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_directx9/build_win32.bat b/examples/example_win32_directx9/build_win32.bat deleted file mode 100644 index ece5ea1ba..000000000 --- a/examples/example_win32_directx9/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_win32_directx9 -@set INCLUDES=/I..\.. /I..\..\backends /I "%DXSDK_DIR%/Include" -@set SOURCES=main.cpp ..\..\backends\imgui_impl_dx9.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d9.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_vulkan/build_win.bat b/examples/example_win32_vulkan/build_win.bat new file mode 100644 index 000000000..7e71881b3 --- /dev/null +++ b/examples/example_win32_vulkan/build_win.bat @@ -0,0 +1,21 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_win32_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp +@set LIBS=vulkan-1.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /libpath:%VULKAN_SDK%\lib32 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /libpath:%VULKAN_SDK%\lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_vulkan/build_win32.bat b/examples/example_win32_vulkan/build_win32.bat deleted file mode 100644 index 4bfb7cafc..000000000 --- a/examples/example_win32_vulkan/build_win32.bat +++ /dev/null @@ -1,9 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_win32_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp -@set LIBS=/libpath:%VULKAN_SDK%\lib32 vulkan-1.lib - -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_vulkan/build_win64.bat b/examples/example_win32_vulkan/build_win64.bat deleted file mode 100644 index f8c66f799..000000000 --- a/examples/example_win32_vulkan/build_win64.bat +++ /dev/null @@ -1,9 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_win32_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp -@set LIBS=/libpath:%VULKAN_SDK%\lib vulkan-1.lib - -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% From 09fe7b19d7b4e99132efe7410872a3c9281ad572 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Oct 2026 16:11:49 +0200 Subject: [PATCH 186/245] Examples: refactored remaining batch files to detect architecture. (Amend) Amend 20ba6c4 --- examples/example_sdl3_sdlgpu3/build_win.bat | 25 +++++++++++++++++++ examples/example_sdl3_sdlgpu3/build_win64.bat | 14 ----------- 2 files changed, 25 insertions(+), 14 deletions(-) create mode 100644 examples/example_sdl3_sdlgpu3/build_win.bat delete mode 100644 examples/example_sdl3_sdlgpu3/build_win64.bat diff --git a/examples/example_sdl3_sdlgpu3/build_win.bat b/examples/example_sdl3_sdlgpu3/build_win.bat new file mode 100644 index 000000000..ff56ee865 --- /dev/null +++ b/examples/example_sdl3_sdlgpu3/build_win.bat @@ -0,0 +1,25 @@ +@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). + +@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). +@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% +@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) +@if /I "%TARGET_ARCH%"=="x86" goto arch_ok +@if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). +@exit /b 1 + +:arch_ok +@set OUT_EXE=example_sdl3_sdlgpu3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlgpu3.cpp ..\..\imgui*.cpp +@set LIBS=SDL3.lib shell32.lib +@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 +@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_sdlgpu3/build_win64.bat b/examples/example_sdl3_sdlgpu3/build_win64.bat deleted file mode 100644 index ad7a2d603..000000000 --- a/examples/example_sdl3_sdlgpu3/build_win64.bat +++ /dev/null @@ -1,14 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. - -@set OUT_EXE=example_sdl3_sdlgpu3 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlgpu3.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 SDL3.lib shell32.lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console From 4e99c0ab1a28c2b3d1f250ec0266dbf1e455ef58 Mon Sep 17 00:00:00 2001 From: Harish Rajaselvan Date: Fri, 23 Oct 2026 07:37:24 -0700 Subject: [PATCH 187/245] CI: added Windows ARM64 build jobs. Examples: added ARM64 support in build_win.bat files. (#9593) --- .github/workflows/build.yml | 33 +++++++++++++++++++ docs/CHANGELOG.txt | 2 ++ examples/example_sdl3_directx11/build_win.bat | 2 ++ examples/example_sdl3_opengl3/build_win.bat | 2 ++ examples/example_sdl3_sdlgpu3/build_win.bat | 2 ++ .../example_sdl3_sdlrenderer3/build_win.bat | 2 ++ 6 files changed, 43 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fa3496d83..5717f5262 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -268,6 +268,39 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' + Build-Windows-ARM64: + runs-on: windows-11-arm + name: Build - Windows ARM64 + + defaults: + run: + working-directory: ${{ github.workspace }}/imgui + + env: + VS_PATH: C:\Program Files\Microsoft Visual Studio\18\Enterprise + steps: + - uses: actions/checkout@v6 + with: + path: ${{ github.workspace }}/imgui + + - name: Build example_null (extra warnings, msvc arm64) + shell: cmd + run: | + cd examples\example_null + call "%VS_PATH%\VC\Auxiliary\Build\vcvarsarm64.bat" + .\build_win.bat /W4 + + - name: Run example_null (msvc arm64) + shell: cmd + run: examples\example_null\Debug\example_null.exe + + - name: Build example_win32_directx11 (msvc arm64) + shell: cmd + run: | + cd examples\example_win32_directx11 + call "%VS_PATH%\VC\Auxiliary\Build\vcvarsarm64.bat" + .\build_win.bat + Build-Linux: runs-on: ubuntu-latest name: Build - Linux diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fd490de77..724e40f03 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,9 +69,11 @@ Other Changes: - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. +- CI: added some ARM64 builds. (#9593) [@Harishmcw] - Examples: renamed various helper batch files from build_win32.bat to build_win.bat to reflect that they can also build X64 or ARM64, given the right environment. Made the script detect the environment when needed (e.g. to specify library path). +- Examples: added support for ARM64 in selected build_win.bat helpers. (#9593) [@Harishmcw] ----------------------------------------------------------------------- diff --git a/examples/example_sdl3_directx11/build_win.bat b/examples/example_sdl3_directx11/build_win.bat index a619de03f..3eccbb2ed 100644 --- a/examples/example_sdl3_directx11/build_win.bat +++ b/examples/example_sdl3_directx11/build_win.bat @@ -5,6 +5,7 @@ @if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) @if /I "%TARGET_ARCH%"=="x86" goto arch_ok @if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok @echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). @exit /b 1 @@ -15,6 +16,7 @@ @set LIBS=SDL3.lib d3d11.lib d3dcompiler.lib shell32.lib @if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 @if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 +@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 @set OUT_DIR=Debug mkdir %OUT_DIR% diff --git a/examples/example_sdl3_opengl3/build_win.bat b/examples/example_sdl3_opengl3/build_win.bat index 0eeef3e0c..6ea3e3941 100644 --- a/examples/example_sdl3_opengl3/build_win.bat +++ b/examples/example_sdl3_opengl3/build_win.bat @@ -5,6 +5,7 @@ @if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) @if /I "%TARGET_ARCH%"=="x86" goto arch_ok @if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok @echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). @exit /b 1 @@ -15,6 +16,7 @@ @set LIBS=SDL3.lib opengl32.lib shell32.lib @if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 @if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 +@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 @set OUT_DIR=Debug mkdir %OUT_DIR% diff --git a/examples/example_sdl3_sdlgpu3/build_win.bat b/examples/example_sdl3_sdlgpu3/build_win.bat index ff56ee865..c71478b57 100644 --- a/examples/example_sdl3_sdlgpu3/build_win.bat +++ b/examples/example_sdl3_sdlgpu3/build_win.bat @@ -5,6 +5,7 @@ @if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) @if /I "%TARGET_ARCH%"=="x86" goto arch_ok @if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok @echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). @exit /b 1 @@ -15,6 +16,7 @@ @set LIBS=SDL3.lib shell32.lib @if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 @if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 +@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 @set OUT_DIR=Debug mkdir %OUT_DIR% diff --git a/examples/example_sdl3_sdlrenderer3/build_win.bat b/examples/example_sdl3_sdlrenderer3/build_win.bat index 86c8bed44..9014d76c2 100644 --- a/examples/example_sdl3_sdlrenderer3/build_win.bat +++ b/examples/example_sdl3_sdlrenderer3/build_win.bat @@ -5,6 +5,7 @@ @if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) @if /I "%TARGET_ARCH%"=="x86" goto arch_ok @if /I "%TARGET_ARCH%"=="x64" goto arch_ok +@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok @echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). @exit /b 1 @@ -15,6 +16,7 @@ @set LIBS=SDL3.lib @if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 @if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 +@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 @set OUT_DIR=Debug mkdir %OUT_DIR% From 717f68fefe31f4ed747aeeba12fa89fcd73ea99d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 Oct 2026 16:34:03 +0100 Subject: [PATCH 188/245] Style: StyleColorsDark(): tweaked WindowBg to be darker than in 1.93.0. --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 724e40f03..b0e396e4d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,7 @@ Autumn cleanup of stuff marked obsolete more than two years ago: Other Changes: +- Style: `StyleColorsDark()`: tweaked WindowBg to be darker than in 1.93.0. - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f5ea37700..e06a70e98 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -191,7 +191,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.58f, 0.58f, 0.58f, 1.00f); - colors[ImGuiCol_WindowBg] = ImVec4(0.18f, 0.18f, 0.18f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); From 4326411672bd57f3496a710b934ebcccabebc320 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 Oct 2026 16:01:38 +0100 Subject: [PATCH 189/245] Internals: removed RenderArrowPointingAt(), moved to ColorPicker4 color. --- imgui_draw.cpp | 14 -------------- imgui_internal.h | 2 +- imgui_widgets.cpp | 19 ++++++++++++++----- 3 files changed, 15 insertions(+), 20 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e06a70e98..84bc55832 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -7551,7 +7551,6 @@ begin: // - RenderArrow() // - RenderBullet() // - RenderCheckMark() -// - RenderArrowPointingAt() // - RenderRectFilledInRangeH() // - RenderRectFilledWithHole() //----------------------------------------------------------------------------- @@ -7613,19 +7612,6 @@ void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float draw_list->PathStroke(col, thickness, ImDrawFlags_AALineEnds); } -// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. -void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) -{ - switch (direction) - { - case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return; - case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return; - case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return; - case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return; - case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings - } -} - static inline float ImAcos01(float x) { if (x <= 0.0f) return IM_PI * 0.5f; diff --git a/imgui_internal.h b/imgui_internal.h index 875c51f42..eaeb52b31 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -549,6 +549,7 @@ inline ImVec2 ImFloor(const ImVec2& v) { return inline float ImTrunc64(float f) { return (float)(ImS64)(f); } inline float ImRoundPositive64(float f) { return (float)(ImS64)(f + 0.5f); } // Positive values only. inline float ImRoundSigned64(float f) { return (float)(ImS64)(f >= 0.0f ? f + 0.5f : f - 0.5f); } +inline ImVec2 ImRoundSigned64(const ImVec2& v) { return ImVec2((float)(ImS64)(v.x >= 0.0f ? v.x + 0.5f : v.x - 0.5f), (float)(ImS64)(v.y >= 0.0f ? v.y + 0.5f : v.y - 0.5f)); } inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the bit-hack version (search for "0x1p120f"). inline int ImModPositive(int a, int b) { return (a + b) % b; } inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } @@ -3804,7 +3805,6 @@ namespace ImGui IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); - IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); IMGUI_API void RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float fill_x0, float fill_x1, float rounding); IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4acdc0a6b..f355df040 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6176,14 +6176,23 @@ bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags fl return true; } +// Helper for RenderArrowsForVerticalBar(). 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. +static void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 p, ImVec2 half_sz, ImGuiDir direction, ImU32 col) +{ + if (direction == ImGuiDir_Left) { draw_list->AddTriangleFilled(ImVec2(p.x + half_sz.x, p.y - half_sz.y), ImVec2(p.x + half_sz.x, p.y + half_sz.y), p, col); } + if (direction == ImGuiDir_Right) { draw_list->AddTriangleFilled(ImVec2(p.x - half_sz.x, p.y + half_sz.y), ImVec2(p.x - half_sz.x, p.y - half_sz.y), p, col); } + //if (direction == ImGuiDir_Up) { draw_list->AddTriangleFilled(ImVec2(p.x + half_sz.x, p.y + half_sz.y), ImVec2(p.x - half_sz.x, p.y + half_sz.y), p, col); } + //if (direction == ImGuiDir_Down){ draw_list->AddTriangleFilled(ImVec2(p.x - half_sz.x, p.y - half_sz.y), ImVec2(p.x + half_sz.x, p.y - half_sz.y), p, col); } +} + // Helper for ColorPicker4() -static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha) +static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 p, ImVec2 half_sz, float bar_w, float alpha) { ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); + RenderArrowPointingAt(draw_list, ImVec2(p.x + half_sz.x + 1, p.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); + RenderArrowPointingAt(draw_list, ImVec2(p.x + half_sz.x, p.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); + RenderArrowPointingAt(draw_list, ImVec2(p.x + bar_w - half_sz.x - 1, p.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); + RenderArrowPointingAt(draw_list, ImVec2(p.x + bar_w - half_sz.x, p.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); } // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. From 726399ff76990f5c71290613c80cb6ba97bb658c Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 Oct 2026 16:47:08 +0100 Subject: [PATCH 190/245] Internals: RenderArrow: apply scale to horizontal offset. (#3895) In the absence of a better standardized symbol/icon design this seem more consistent. --- imgui_draw.cpp | 2 +- imgui_tables.cpp | 2 +- imgui_widgets.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 84bc55832..1b9af8822 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -7563,7 +7563,7 @@ void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir d { const float h = draw_list->_Data->FontSize * 1.00f; float r = h * 0.40f * scale; - ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); + ImVec2 center = pos + ImVec2(h * 0.50f * scale, h * 0.50f * scale); ImVec2 a, b, c; switch (dir) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ee208d160..e82c71dfb 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -3435,7 +3435,7 @@ void ImGui::TableHeader(const char* label) PopStyleColor(); x += w_sort_text; } - RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); + RenderArrow(window->DrawList, ImVec2(x + (g.FontSize * (1.0f - ARROW_SCALE) * 0.5f) , y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); } // Handle clicking on column header to adjust Sort Order diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f355df040..3a0259c71 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7281,7 +7281,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col); else if (!is_leaf) - RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f); + RenderArrow(window->DrawList, ImVec2(text_pos.x + g.FontSize * 0.15f - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f); if (g.LogEnabled) LogSetNextTextDecoration(">", NULL); } From 048d7e10b5bcc48e20850694d693fbad71c799b5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 27 Oct 2026 13:02:28 +0100 Subject: [PATCH 191/245] Style: made default arrow stroked. Added SymbolArrowSizeFactor, SymbolArrowThicknessFactor to style arrow. (#5233, #2431, #2235, #6730, #8243) Internal function takes a angle: #5812. This doesn't cover generic rendering override for symbols: #8243, #2431 (arrows, somehow less needed now), #3351 (checkmarks), #6730 (tree nodes) --- docs/CHANGELOG.txt | 4 +++ imgui.cpp | 4 +++ imgui.h | 4 +++ imgui_demo.cpp | 4 +++ imgui_draw.cpp | 67 +++++++++++++++++++++++++++------------------- imgui_internal.h | 1 + 6 files changed, 56 insertions(+), 28 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b0e396e4d..2cb513c3b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,10 @@ Autumn cleanup of stuff marked obsolete more than two years ago: Other Changes: - Style: `StyleColorsDark()`: tweaked WindowBg to be darker than in 1.93.0. +- Style: added `style.SymbolArrowSizeFactor`, `style.SymbolArrowThicknessFactor` to tweak + the shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) + Legacy arrow: size: (0.60f,0.70f), thickness: 0.0f + New arrow: size: (0.72f,0.40f), thickness: 0.30f - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui.cpp b/imgui.cpp index 585e8a9b2..f8a2def00 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1628,6 +1628,10 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. + // Symbols + SymbolArrowSizeFactor = ImVec2(0.72f,0.40f); // Width/height factor of arrows (0.0f..1.0f). Legacy arrows use (0.60f,0.70f) + SymbolArrowThicknessFactor = 0.30f; // Thickness factor of arrows (0.0f..0.5f). 0.0f=Fill. >0.0f=Stroke. Legacy arrows use 0.0f. + // Rendering & Tessellation AntiAliasedLines = true; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. AntiAliasedLineEnds = false; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. diff --git a/imgui.h b/imgui.h index fdbcf80ba..67e11d18c 100644 --- a/imgui.h +++ b/imgui.h @@ -2396,6 +2396,10 @@ struct ImGuiStyle ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured). float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. + // Symbols + ImVec2 SymbolArrowSizeFactor; // Width/height factor of arrows (0.0f..1.0f). + float SymbolArrowThicknessFactor; // Thickness factor of arrows (0.0f..0.5f). 0.0f=Fill. >0.0f=Stroke. + // Rendering & Tessellation bool AntiAliasedLines; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. bool AntiAliasedLineEnds; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ede2eeb07..aeb896305 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -8807,6 +8807,10 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("ImageRounding", &style.ImageRounding, 0.0f, 12.0f, "%.0f"); SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, max_border_size, "%.0f"); + SeparatorText("Symbols"); + DragFloat2("SymbolArrowSizeFactor", &style.SymbolArrowSizeFactor.x, 0.01f, 0.0f, 1.0f); + DragFloat("SymbolArrowThicknessFactor", &style.SymbolArrowThicknessFactor, 0.01f, 0.0f, 0.5f); + SeparatorText("Tooltips"); for (int n = 0; n < 2; n++) if (TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1b9af8822..6ab6c6c45 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -7558,36 +7558,47 @@ begin: // - RenderColorRectWithAlphaCheckerboard() //----------------------------------------------------------------------------- -// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state +static const ImVec2 g_ImGuiDirCosSin[4] = { { -1.0f, 0.0f }, { +1.0f, 0.0f }, { 0.0f, -1.0f }, { 0.0f, +1.0f } }; + +// arrow_h, arrow_w, arrow_th are normalized: 0.0f..1.0f +// arrow_th: 0.0f == fill, >0.0f == stroke weight. +void ImGui::RenderArrowEx(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float cos_a, float sin_a, float scale, ImVec2 arrow_sizes, float arrow_th) +{ + const bool is_fill = (arrow_th <= 0.0f); + const float r = draw_list->_Data->FontSize * 0.50f * scale; + const float thickness = is_fill ? 0.0f : IM_ROUND(ImClamp(r * arrow_th, 1.0f, r * 0.5f)); + + // Bias for shape to feel more centered + const float bias = is_fill ? (r * 0.05f) : (thickness * 0.8f * 0.7071f); + const ImVec2 center = ImVec2(pos.x + r + bias * cos_a, pos.y + r + bias * sin_a); + + const float arrow_h = arrow_sizes.y * r; + const float arrow_w = arrow_sizes.x * r; + ImVec2 p[3]; + p[0] = ImVec2(center.x - arrow_h * cos_a - arrow_w * -sin_a, center.y - arrow_h * sin_a - arrow_w * cos_a); + p[1] = ImVec2(center.x + arrow_h * cos_a, center.y + arrow_h * sin_a); + p[2] = ImVec2(center.x - arrow_h * cos_a + arrow_w * -sin_a, center.y - arrow_h * sin_a + arrow_w * cos_a); + + // Pixel align when at a right angle + if (is_fill && (cos_a * sin_a >= -FLT_EPSILON) && (cos_a * sin_a <= FLT_EPSILON)) + { + p[0] = ImRoundSigned64(p[0]); + p[1] = ImRoundSigned64(p[1]); + p[2] = ImRoundSigned64(p[2]); + } + + if (is_fill) + draw_list->AddConvexPolyFilled(p, 3, col); + else + draw_list->_AddPolyline(p, 3, col, thickness, ImDrawFlags_StrokeInside | ImDrawFlags_AALineEnds, FLT_MAX); // FIXME-OPT: baked filled shape? +} + +// Render an arrow aimed to be aligned with text. void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale) { - const float h = draw_list->_Data->FontSize * 1.00f; - float r = h * 0.40f * scale; - ImVec2 center = pos + ImVec2(h * 0.50f * scale, h * 0.50f * scale); - - ImVec2 a, b, c; - switch (dir) - { - case ImGuiDir_Up: - case ImGuiDir_Down: - if (dir == ImGuiDir_Up) r = -r; - a = ImVec2(+0.000f, +0.750f) * r; - b = ImVec2(-0.866f, -0.750f) * r; - c = ImVec2(+0.866f, -0.750f) * r; - break; - case ImGuiDir_Left: - case ImGuiDir_Right: - if (dir == ImGuiDir_Left) r = -r; - a = ImVec2(+0.750f, +0.000f) * r; - b = ImVec2(-0.750f, +0.866f) * r; - c = ImVec2(-0.750f, -0.866f) * r; - break; - case ImGuiDir_None: - case ImGuiDir_COUNT: - IM_ASSERT(0); - break; - } - draw_list->AddTriangleFilled(center + a, center + b, center + c, col); + ImGuiContext& g = *GImGui; + ImVec2 cos_sin = g_ImGuiDirCosSin[dir]; + RenderArrowEx(draw_list, pos, col, cos_sin.x, cos_sin.y, scale, g.Style.SymbolArrowSizeFactor, g.Style.SymbolArrowThicknessFactor); } void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) diff --git a/imgui_internal.h b/imgui_internal.h index eaeb52b31..9cc49e343 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3803,6 +3803,7 @@ namespace ImGui // Render helpers (those functions don't access any ImGui state!) IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); + IMGUI_API void RenderArrowEx(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float cos_a, float sin_a, float scale, ImVec2 arrow_sizes, float arrow_th); IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); IMGUI_API void RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float fill_x0, float fill_x1, float rounding); From 2f1552d4d58b8b443d70e27edddb92a3c3f68641 Mon Sep 17 00:00:00 2001 From: Yaki Blake Date: Tue, 27 Oct 2026 15:20:31 +0100 Subject: [PATCH 192/245] TreeNodeGetOpen(): added flags parameter. (#9569, #9592, #3823, #9251) --- docs/CHANGELOG.txt | 3 +++ imgui.h | 2 +- imgui_widgets.cpp | 10 ++++++---- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2cb513c3b..05604c48b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,9 @@ Other Changes: the shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) Legacy arrow: size: (0.60f,0.70f), thickness: 0.0f New arrow: size: (0.72f,0.40f), thickness: 0.30f +- TreeNode: + - TreeNodeGetOpen(): added flags parameter to allow passing `ImGuiTreeNodeFlags_DefaultOpen` + or `ImGuiTreeNodeFlags_Leaf`. (#9569, #9592, #3823, #9251) [@adalisk-emikhaylov, @Yaki-Blake] - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui.h b/imgui.h index 67e11d18c..04c25c98e 100644 --- a/imgui.h +++ b/imgui.h @@ -769,7 +769,7 @@ namespace ImGui IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. IMGUI_API void SetNextItemStorageID(ImGuiID storage_id); // set id to use for open/close storage (default to same as item id). - IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); // retrieve tree node open/close state. + IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags = 0); // retrieve tree node open/close state. // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3a0259c71..7acda6ce4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6931,13 +6931,15 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char return TreeNodeBehavior(id, flags, label, label_end); } -// The reason those two functions are not yet in public API is because I would like to design a more feature-full and generic API for this. -// They are otherwise function (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722) -bool ImGui::TreeNodeGetOpen(ImGuiID storage_id) +// I would like to design a more feature-full and generic API for this. +// (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722, #9569) +bool ImGui::TreeNodeGetOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) { + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; ImGuiContext& g = *GImGui; ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; - return storage->GetInt(storage_id, 0) != 0; + return storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool is_open) From 86b853ae8aacb6e1bc419ef402101bb01b5ebd57 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 27 Oct 2026 15:43:57 +0100 Subject: [PATCH 193/245] TabBar: rename VisibleTabId->VisibleTabContentsId for clarify and correctness. Toward #9581 --- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 19 ++++++++++--------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 9cc49e343..6e73dd3f5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2936,7 +2936,7 @@ struct ImGuiTabItem { ImGuiID ID; ImGuiTabItemFlags Flags; - int LastFrameVisible; + int LastFrameVisible; // TabItem visibility (not contents visibility) int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance float Offset; // Position relative to beginning of tab bar float Width; // Width currently displayed @@ -2960,7 +2960,7 @@ struct IMGUI_API ImGuiTabBar ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation ImGuiID NextScrollToTabId; - ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) + ImGuiID VisibleTabContentsId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7acda6ce4..40ee343a0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10069,7 +10069,7 @@ void ImGui::EndTabBar() // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); - if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) + if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabContentsId == 0 || tab_bar_appearing) { tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight); window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight; @@ -10117,7 +10117,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose) { // Remove tab - if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; } + if (tab_bar->VisibleTabContentsId == tab->ID) { tab_bar->VisibleTabContentsId = 0; } if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; } if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; } continue; @@ -10322,7 +10322,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID; // Lock in visible tab - tab_bar->VisibleTabId = tab_bar->SelectedTabId; + tab_bar->VisibleTabContentsId = tab_bar->SelectedTabId; tab_bar->VisibleTabWasSubmitted = false; // Apply request requests @@ -10436,9 +10436,9 @@ void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) { if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) tab_bar->Tabs.erase(tab); - if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; } - if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } - if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } + if (tab_bar->VisibleTabContentsId == tab_id){ tab_bar->VisibleTabContentsId = 0; } + if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } } // Called on manual closure attempt @@ -10452,7 +10452,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) // This will remove a frame of lag for selecting another tab on closure. // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure tab->WantClose = true; - if (tab_bar->VisibleTabId == tab->ID) + if (tab_bar->VisibleTabContentsId == tab->ID) { tab->LastFrameVisible = -1; tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; @@ -10461,7 +10461,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) else { // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) - if (tab_bar->VisibleTabId != tab->ID) + if (tab_bar->VisibleTabContentsId != tab->ID) TabBarQueueFocus(tab_bar, tab); } } @@ -10865,7 +10865,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Lock visibility // (Note: tab_contents_visible != tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) - bool tab_contents_visible = (tab_bar->VisibleTabId == id); + bool tab_contents_visible = (tab_bar->VisibleTabContentsId == id); if (tab_contents_visible) tab_bar->VisibleTabWasSubmitted = true; @@ -10878,6 +10878,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. if (tab_appearing && (!tab_bar_appearing || tab_is_new)) { + // This path doesn't render the tab. ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav); if (is_tab_button) return false; From 50ae760fcee04ba93e94539523e9a060beeb5b69 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 27 Oct 2026 15:50:22 +0100 Subject: [PATCH 194/245] TabBar: Internals: add tab_bar->VisibleTabContentsJustAppeared. (#9581) --- imgui_internal.h | 2 ++ imgui_widgets.cpp | 11 ++++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 6e73dd3f5..69acf63eb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2946,6 +2946,7 @@ struct ImGuiTabItem ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable ImS16 IndexDuringLayout; // Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. bool WantClose; // Marked as closed by SetTabItemClosed() + bool ContentsIsVisible; ImGuiTabItem() { memset((void*)this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } }; @@ -2982,6 +2983,7 @@ struct IMGUI_API ImGuiTabBar ImS8 BeginCount; bool WantLayout; bool VisibleTabWasSubmitted; + bool VisibleTabContentsJustAppeared; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame bool ScrollButtonEnabled; ImS16 TabsActiveCount; // Number of tabs submitted this frame. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 40ee343a0..22ffe8de5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10323,7 +10323,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Lock in visible tab tab_bar->VisibleTabContentsId = tab_bar->SelectedTabId; - tab_bar->VisibleTabWasSubmitted = false; + tab_bar->VisibleTabWasSubmitted = tab_bar->VisibleTabContentsJustAppeared = false; // Apply request requests if (scroll_to_tab_id != 0) @@ -10866,14 +10866,19 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Lock visibility // (Note: tab_contents_visible != tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) bool tab_contents_visible = (tab_bar->VisibleTabContentsId == id); - if (tab_contents_visible) - tab_bar->VisibleTabWasSubmitted = true; // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing) if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) tab_contents_visible = true; + if (tab_contents_visible) + { + tab_bar->VisibleTabWasSubmitted = true; + tab_bar->VisibleTabContentsJustAppeared = tab_contents_visible && !tab->ContentsIsVisible; + } + tab->ContentsIsVisible = tab_contents_visible; + // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. if (tab_appearing && (!tab_bar_appearing || tab_is_new)) From 1069a952e026f2640462ec6a5156c31d6b3f4030 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 27 Oct 2026 16:27:10 +0100 Subject: [PATCH 195/245] TabBar: Internals: added TabItemIsContentsAppearing() and reworked 50ae760. (#9581) --- imgui_internal.h | 3 ++- imgui_widgets.cpp | 25 ++++++++++++++----------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 69acf63eb..16743905c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2983,7 +2983,7 @@ struct IMGUI_API ImGuiTabBar ImS8 BeginCount; bool WantLayout; bool VisibleTabWasSubmitted; - bool VisibleTabContentsJustAppeared; + bool LastTabItemContentsAppearing; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame bool ScrollButtonEnabled; ImS16 TabsActiveCount; // Number of tabs submitted this frame. @@ -3778,6 +3778,7 @@ namespace ImGui IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImVec2 mouse_pos); IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar); IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window); + IMGUI_API bool TabItemIsContentsAppearing(); IMGUI_API void TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width); IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker); IMGUI_API ImVec2 TabItemCalcSize(ImGuiWindow* window); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 22ffe8de5..ea5871a51 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -10323,7 +10323,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Lock in visible tab tab_bar->VisibleTabContentsId = tab_bar->SelectedTabId; - tab_bar->VisibleTabWasSubmitted = tab_bar->VisibleTabContentsJustAppeared = false; + tab_bar->VisibleTabWasSubmitted = tab_bar->LastTabItemContentsAppearing = false; // Apply request requests if (scroll_to_tab_id != 0) @@ -10752,6 +10752,12 @@ void ImGui::EndTabItem() PopID(); } +bool ImGui::TabItemIsContentsAppearing() +{ + ImGuiContext& g = *GImGui; + return g.CurrentTabBar->LastTabItemContentsAppearing; +} + bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) { ImGuiContext& g = *GImGui; @@ -10863,20 +10869,17 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, TabBarQueueFocus(tab_bar, tab); } + // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches + if (tab_bar->VisibleTabContentsId == 0 && tab_bar->SelectedTabId == 0 && tab_bar_appearing) + if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) + tab_bar->VisibleTabContentsId = id; + // Lock visibility // (Note: tab_contents_visible != tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) - bool tab_contents_visible = (tab_bar->VisibleTabContentsId == id); - - // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches - if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing) - if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) - tab_contents_visible = true; - + const bool tab_contents_visible = (tab_bar->VisibleTabContentsId == id); if (tab_contents_visible) - { tab_bar->VisibleTabWasSubmitted = true; - tab_bar->VisibleTabContentsJustAppeared = tab_contents_visible && !tab->ContentsIsVisible; - } + tab_bar->LastTabItemContentsAppearing = tab_contents_visible && !tab->ContentsIsVisible; tab->ContentsIsVisible = tab_contents_visible; // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted From 80d572ce359e2a9ca0c4386ab9cf220d5c15ce0f Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 27 Oct 2026 18:10:59 +0100 Subject: [PATCH 196/245] TreeNode: minor tidying up. (should have no side-effect) --- imgui_demo.cpp | 1 + imgui_widgets.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index aeb896305..550e0d8da 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4430,6 +4430,7 @@ static void DemoWindowWidgetsTreeNodes() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_FramePadding", &base_flags, ImGuiTreeNodeFlags_FramePadding); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsToParent", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsToParent); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Bullet", &base_flags, ImGuiTreeNodeFlags_Bullet); HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ea5871a51..e1a884429 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7041,9 +7041,10 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l label_end = FindRenderedTextEnd(label); const ImVec2 label_size = CalcTextSize(label, label_end, false); - const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing + const float icon_width = g.FontSize + padding.x * 2; + const float text_offset_x = display_frame ? icon_width + padding.x : icon_width; // Collapsing arrow width + Spacing const float text_offset_y = use_frame_padding ? ImMax(style.FramePadding.y, window->DC.CurrLineTextBaseOffset) : window->DC.CurrLineTextBaseOffset; // Latch before ItemSize changes it - const float text_width = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow + const float text_width = icon_width + label_size.x; // Include collapsing arrow const float frame_height = label_size.y + padding.y * 2; const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL); @@ -7076,6 +7077,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (span_all_columns || span_all_columns_label) { // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. + // FIXME: Investigate moving this to an item flag, along duplicate code in Selectable(). How to do optimally? const float backup_clip_rect_min_x = window->ClipRect.Min.x; const float backup_clip_rect_max_x = window->ClipRect.Max.x; window->ClipRect.Min.x = window->ParentWorkRect.Min.x; From 2fb554b1c81e6a8efcb4e3c236649a46354aa9ba Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 28 Oct 2026 15:41:13 +0100 Subject: [PATCH 197/245] Modals: fixed an assert displaying a modal in an environment where io.DisplayFramebufferScale is not an integer. (#9598) --- docs/CHANGELOG.txt | 10 +++++++--- imgui.cpp | 3 ++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 05604c48b..ec2cc0763 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,14 +66,18 @@ Autumn cleanup of stuff marked obsolete more than two years ago: Other Changes: -- Style: `StyleColorsDark()`: tweaked WindowBg to be darker than in 1.93.0. -- Style: added `style.SymbolArrowSizeFactor`, `style.SymbolArrowThicknessFactor` to tweak - the shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) +- Style: + - `StyleColorsDark()`: tweaked WindowBg to be darker than in 1.93.0. + - Added `style.SymbolArrowSizeFactor`, `style.SymbolArrowThicknessFactor` to tweak the + shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) Legacy arrow: size: (0.60f,0.70f), thickness: 0.0f New arrow: size: (0.72f,0.40f), thickness: 0.30f - TreeNode: - TreeNodeGetOpen(): added flags parameter to allow passing `ImGuiTreeNodeFlags_DefaultOpen` or `ImGuiTreeNodeFlags_Leaf`. (#9569, #9592, #3823, #9251) [@adalisk-emikhaylov, @Yaki-Blake] +- Popups: + - Modals: fixed an assert displaying a modal in an environment where + `io.DisplayFramebufferScale` is not an integer (regression in 1.93.0). (#9598) - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui.cpp b/imgui.cpp index f8a2def00..67edfa37b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6122,7 +6122,8 @@ static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 if (draw_list->CmdBuffer.Size == 0) draw_list->AddDrawCmd(); draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to strictly ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that) - draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col); + draw_list->PrimReserve(6, 4); + draw_list->PrimRect(viewport_rect.Min, viewport_rect.Max, col); ImDrawCmd cmd = draw_list->CmdBuffer.back(); IM_ASSERT(cmd.ElemCount == 6); draw_list->CmdBuffer.pop_back(); From b87728bd2b2bdaa63efa13f390adb73ed3c40afd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Oct 2026 13:47:01 +0100 Subject: [PATCH 198/245] Tables: clamp vertical border Y2 position when not using scrolling table, so that ImDrawCmd AABB stays reasonable. This does not fix any screen visible issue, and should not be noticeable if correct. (context: investigated this while looking at #4678, but not actually directly related) --- docs/CHANGELOG.txt | 3 +++ imgui.h | 2 +- imgui_tables.cpp | 18 ++++++++++++------ 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ec2cc0763..d0704cac1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -78,6 +78,9 @@ Other Changes: - Popups: - Modals: fixed an assert displaying a modal in an environment where `io.DisplayFramebufferScale` is not an integer (regression in 1.93.0). (#9598) +- Tables: + - In non-scrolling tables, clamp lower border coordinates to stay within visible + range (no visible changes, but ImDrawCmd AABB becomes more sensible). - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui.h b/imgui.h index 04c25c98e..9a2313a59 100644 --- a/imgui.h +++ b/imgui.h @@ -30,7 +30,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.93.1 WIP" -#define IMGUI_VERSION_NUM 19301 +#define IMGUI_VERSION_NUM 19302 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e82c71dfb..a303760a0 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2951,19 +2951,24 @@ static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_ void ImGui::TableDrawBorders(ImGuiTable* table) { ImGuiWindow* inner_window = table->InnerWindow; - if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) + if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) // Note how OuterWindow->ClipRect == table->Bg0ClipRectForDrawCmd return; ImDrawList* inner_drawlist = inner_window->DrawList; table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0); - inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false); + inner_drawlist->PushClipRect(table->OuterWindow->ClipRect.Min, table->OuterWindow->ClipRect.Max, false); + + const float border_size = TABLE_BORDER_SIZE; + + // For e.g. non scrolling table we limit vertex coordinates in order to keep ImDrawCmd AABB roughly within visible range. + const float draw_y2_limit = table->OuterWindow->ClipRect.Max.y + (2.0f * ImMax(border_size, inner_drawlist->_FringeScale)); // Draw inner border and resizing feedback ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); - const float border_size = TABLE_BORDER_SIZE; const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f); - const float draw_y2_body = table->InnerRect.Max.y; - const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; + const float draw_y2_body = ImMin(table->InnerRect.Max.y, draw_y2_limit); + const float draw_y2_head = table->IsUsingHeaders ? ImMin(draw_y2_body, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; + if (table->Flags & ImGuiTableFlags_BordersInnerV) { for (int order_n = 0; order_n < table->ColumnsCount; order_n++) @@ -3009,7 +3014,8 @@ void ImGui::TableDrawBorders(ImGuiTable* table) // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part // of it in inner window, and the part that's over scrollbars in the outer window..) // Either solution currently won't allow us to use a larger border size: the border would clipped. - const ImRect outer_border = table->OuterRect; + ImRect outer_border = table->OuterRect; + outer_border.Max.y = ImMin(outer_border.Max.y, draw_y2_limit); // Clamp but keep bottom border non-visible. const ImU32 outer_col = table->BorderColorStrong; if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) { From d2ba763635a958fc5cbdab6139ffa739a7048722 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Oct 2026 18:29:27 +0100 Subject: [PATCH 199/245] Tables: fixed various issues with using ImGuiTableFlags_NoHostExtendY. --- docs/CHANGELOG.txt | 4 ++++ imgui_demo.cpp | 1 + imgui_tables.cpp | 15 ++++++++++++--- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d0704cac1..fbd0a60f9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,10 @@ Other Changes: - Tables: - In non-scrolling tables, clamp lower border coordinates to stay within visible range (no visible changes, but ImDrawCmd AABB becomes more sensible). + - Fixed various issues with using `ImGuiTableFlags_NoHostExtendY`: + - Fixed selectable highlight straying off the Y2 clipping limit. + - Fixed parent window work rectangle affecting the Y2 clipping limit. + - Fixed the Y2 clipping limit overlapping bottom outer border. - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 550e0d8da..547661f7d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6954,6 +6954,7 @@ static void DemoWindowTables() if (ImGui::TreeNode("Outer size")) { IMGUI_DEMO_MARKER("Tables/Outer size"); + // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY // Important to that note how the two flags have slightly different behaviors! ImGui::Text("Using NoHostExtendX and NoHostExtendY:"); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index a303760a0..0c0796384 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -482,12 +482,12 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap // problem only affect scrolling tables in this case we can get away with doing it without extra cost). + const float border_size = TABLE_BORDER_SIZE; if (inner_window != outer_window) { // FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with // different x/y values to BeginChild(). - const float border_size = TABLE_BORDER_SIZE; if (flags & ImGuiTableFlags_BordersOuterV) { table->HostClipRect.Min.x = ImMin(table->HostClipRect.Min.x + border_size, table->HostClipRect.Max.x); @@ -527,8 +527,15 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width table->InnerClipRect.ClipWithFull(table->HostClipRect); - table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : table->HostClipRect.Max.y; - + if (flags & ImGuiTableFlags_NoHostExtendY) + { + if (flags & ImGuiTableFlags_BordersOuterH) + table->InnerClipRect.Max.y = ImClamp(table->OuterRect.Max.y - border_size, table->InnerClipRect.Min.y, table->InnerClipRect.Max.y); + } + else + { + table->InnerClipRect.Max.y = table->HostClipRect.Max.y; + } table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() table->RowCellPaddingY = 0.0f; @@ -2734,6 +2741,8 @@ void ImGui::TableSetupDrawChannels(ImGuiTable* table) table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect; table->Bg2ClipRectForDrawCmd = table->HostClipRect; IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y); + if (table->Flags & ImGuiTableFlags_NoHostExtendY) + table->Bg2ClipRectForDrawCmd.Max.y = ImMin(table->Bg2ClipRectForDrawCmd.Max.y, table->BgClipRect.Max.y); // Don't apply to Bg0: shapes in Bg0 are already CPU clipped and it makes merging fails. } // This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). From c39a91bfbecc319847e9d4a9b96f320031fd957b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Oct 2026 18:40:27 +0100 Subject: [PATCH 200/245] Tables: latch border size once, and pull all use from same place. (#9415) --- imgui_internal.h | 1 + imgui_tables.cpp | 26 ++++++++++++++------------ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 16743905c..da6d68730 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3156,6 +3156,7 @@ struct IMGUI_API ImGuiTable ImU32 BorderColorLight; float BorderX1; float BorderX2; + float BorderSize; float HostIndentX; float MinColumnWidth; float OuterPaddingX; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0c0796384..4d0ae97d8 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -478,11 +478,14 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size; inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + // Border size + // FIXME-WIP: Changing this is not currently simple due to ClipRect requirements. Easier to manage with new 1.93 primitives though. + const float border_size = table->BorderSize = TABLE_BORDER_SIZE; + // Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap // problem only affect scrolling tables in this case we can get away with doing it without extra cost). - const float border_size = TABLE_BORDER_SIZE; if (inner_window != outer_window) { // FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, @@ -509,14 +512,14 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0; const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true; - const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f; + const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? border_size : 0.0f; const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f; const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f; table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border; table->CellSpacingX2 = inner_spacing_explicit; table->CellPaddingX = inner_padding_explicit; - const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; + const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f; table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX; @@ -1284,7 +1287,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } if (order_n < table->FreezeColumnsCount) - host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x); + host_clip_rect.Min.x = ImClamp(column->MaxX + table->BorderSize, host_clip_rect.Min.x, host_clip_rect.Max.x); offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; } @@ -1510,7 +1513,7 @@ void ImGui::EndTable() // but since the later is likely to be impossible to do we'd rather update both axes together. if (table->Flags & ImGuiTableFlags_ScrollX) { - const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; + const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; float max_pos_x = inner_window->DC.CursorMaxPos.x; if (table->RightMostEnabledColumn != -1) max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border); @@ -2175,7 +2178,6 @@ void ImGui::TableEndRow(ImGuiTable* table) // Decide of top border color ImU32 top_border_col = 0; - const float border_size = TABLE_BORDER_SIZE; if (table->CurrentRow > 0 && (table->Flags & ImGuiTableFlags_BordersInnerH)) top_border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight; @@ -2222,11 +2224,11 @@ void ImGui::TableEndRow(ImGuiTable* table) // Draw top border if (top_border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, border_size); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, table->BorderSize); // Draw bottom border at the row unfreezing mark (always strong) if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, border_size); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, table->BorderSize); } // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) @@ -2967,9 +2969,8 @@ void ImGui::TableDrawBorders(ImGuiTable* table) table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0); inner_drawlist->PushClipRect(table->OuterWindow->ClipRect.Min, table->OuterWindow->ClipRect.Max, false); - const float border_size = TABLE_BORDER_SIZE; - // For e.g. non scrolling table we limit vertex coordinates in order to keep ImDrawCmd AABB roughly within visible range. + const float border_size = table->BorderSize; const float draw_y2_limit = table->OuterWindow->ClipRect.Max.y + (2.0f * ImMax(border_size, inner_drawlist->_FringeScale)); // Draw inner border and resizing feedback @@ -3640,8 +3641,9 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label if (pass == 1) { // Draw border - const float border_size = TABLE_BORDER_SIZE; - draw_list->AddLine(bg_shape[0] + ImVec2(border_size * 0.5f, 0.0f), bg_shape[3] + ImVec2(border_size * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), border_size); + draw_list->AddLine( + bg_shape[0] + ImVec2(table->BorderSize * 0.5f, 0.0f), + bg_shape[3] + ImVec2(table->BorderSize * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), table->BorderSize); } } PopClipRect(); From 0d0cd87dd26fd5cda7858f9c02a811c84487a714 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Oct 2026 18:56:20 +0100 Subject: [PATCH 201/245] Tables: fixed vertical inner borders slightly overlapping bottom outer border. (#4678, #9415) --- docs/CHANGELOG.txt | 2 ++ imgui_tables.cpp | 27 ++++++++++++++------------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fbd0a60f9..d20a74cf0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,8 @@ Other Changes: - Fixed selectable highlight straying off the Y2 clipping limit. - Fixed parent window work rectangle affecting the Y2 clipping limit. - Fixed the Y2 clipping limit overlapping bottom outer border. + - Fixed vertical inner borders slightly overlapping bottom outer border + (may be visible with transparent borders). - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 4d0ae97d8..120c29364 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2970,13 +2970,15 @@ void ImGui::TableDrawBorders(ImGuiTable* table) inner_drawlist->PushClipRect(table->OuterWindow->ClipRect.Min, table->OuterWindow->ClipRect.Max, false); // For e.g. non scrolling table we limit vertex coordinates in order to keep ImDrawCmd AABB roughly within visible range. - const float border_size = table->BorderSize; - const float draw_y2_limit = table->OuterWindow->ClipRect.Max.y + (2.0f * ImMax(border_size, inner_drawlist->_FringeScale)); + const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; + const float border_size_outer_h = (table->Flags & ImGuiTableFlags_BordersOuterH) ? table->BorderSize : 0.0f; + const float border_size_inner = table->BorderSize; + const float draw_y2_limit = table->OuterWindow->ClipRect.Max.y + (2.0f * ImMax(border_size_outer_h, inner_drawlist->_FringeScale)); // Draw inner border and resizing feedback ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); - const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f); - const float draw_y2_body = ImMin(table->InnerRect.Max.y, draw_y2_limit); + const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size_outer_h : 0.0f); + const float draw_y2_body = ImMin(table->InnerRect.Max.y - border_size_outer_h, draw_y2_limit); const float draw_y2_head = table->IsUsingHeaders ? ImMin(draw_y2_body, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; if (table->Flags & ImGuiTableFlags_BordersInnerV) @@ -3011,7 +3013,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) else if ((table->Flags & (ImGuiTableFlags_NoBordersInBodyUntilResize | ImGuiTableFlags_NoBordersInBody)) == 0) draw_y2 = draw_y2_body; if (draw_y2 > draw_y1) - inner_drawlist->AddLineV(column->MaxX, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size); + inner_drawlist->AddLineV(column->MaxX, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size_inner); } } @@ -3029,26 +3031,25 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const ImU32 outer_col = table->BorderColorStrong; if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) { - inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size); + inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size_outer_w); } else if (table->Flags & ImGuiTableFlags_BordersOuterV) { - inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); - inner_drawlist->AddLineV(outer_border.Max.x - border_size, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); + inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); + inner_drawlist->AddLineV(outer_border.Max.x - border_size_outer_w, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); } else if (table->Flags & ImGuiTableFlags_BordersOuterH) { - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size); - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size, outer_col, border_size); + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size_outer_h); + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size_outer_h, outer_col, border_size_outer_h); } } if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) { - // Draw bottom-most row border between it is above outer border. - const float h_inset = (table->Flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; + // Draw bottom-most row border between it and above outer border. const float border_y = table->RowPosY2; if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) - inner_drawlist->AddLineH(table->BorderX1 + h_inset, table->BorderX2 - h_inset, border_y, table->BorderColorLight, border_size); + inner_drawlist->AddLineH(table->BorderX1 + border_size_outer_w, table->BorderX2 - border_size_outer_w, border_y, table->BorderColorLight, border_size_inner); } inner_drawlist->PopClipRect(); From c1581882a4f2703fa81354fea9173c0f92579873 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Oct 2026 20:14:03 +0100 Subject: [PATCH 202/245] Tables: fixed various border overshooting issues, some mostly visible with transparent borders: (#4678, #9415) As a side effect of cleaning up a few things, altering border size becomes closer to being correct. --- docs/CHANGELOG.txt | 11 ++++++---- imgui_internal.h | 1 + imgui_tables.cpp | 53 +++++++++++++++++++--------------------------- 3 files changed, 30 insertions(+), 35 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d20a74cf0..96ebe7493 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -79,14 +79,17 @@ Other Changes: - Modals: fixed an assert displaying a modal in an environment where `io.DisplayFramebufferScale` is not an integer (regression in 1.93.0). (#9598) - Tables: - - In non-scrolling tables, clamp lower border coordinates to stay within visible - range (no visible changes, but ImDrawCmd AABB becomes more sensible). + - Fixed various border overshooting issues, some mostly visible with transparent + borders: (#4678) + - On non-scrolling tables, inner horizontal borders slightly overlapped + outer vertical ones with certain settings. + - On non-scrolling tables, clamping lower border coordinates to stay within + visible range (no visible change, but it makes ImDrawCmd AABB more sensible). + - Fixed vertical inner borders slightly overlapping bottom outer border. - Fixed various issues with using `ImGuiTableFlags_NoHostExtendY`: - Fixed selectable highlight straying off the Y2 clipping limit. - Fixed parent window work rectangle affecting the Y2 clipping limit. - Fixed the Y2 clipping limit overlapping bottom outer border. - - Fixed vertical inner borders slightly overlapping bottom outer border - (may be visible with transparent borders). - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui_internal.h b/imgui_internal.h index da6d68730..001bc687c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -653,6 +653,7 @@ struct IMGUI_API ImRect void TranslateY(float dy) { Min.y += dy; Max.y += dy; } void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. + void ShrinkClamp(const ImVec2& inset_min, const ImVec2& inset_max) { Min.x = ImMin(Min.x + inset_min.x, Max.x); Min.y = ImMin(Min.y + inset_min.y, Max.y); Max.x = ImMax(Max.x - inset_max.x, Min.x); Max.y = ImMax(Max.y - inset_max.y, Min.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } const ImVec4& AsVec4() const { return *(const ImVec4*)&Min.x; } diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 120c29364..f05c29f73 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -483,27 +483,22 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG const float border_size = table->BorderSize = TABLE_BORDER_SIZE; // Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) - // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the - // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap - // problem only affect scrolling tables in this case we can get away with doing it without extra cost). - if (inner_window != outer_window) + // - We normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the + // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap + // problem only affect scrolling tables in this case we can get away with doing it without extra cost). + // - (FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, + // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with + // different x/y values to BeginChild().) + // - For non-scrolling window, this is applied to table->InnerClipRect below. + ImRect border_size_outer = { - // FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, - // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with - // different x/y values to BeginChild(). - if (flags & ImGuiTableFlags_BordersOuterV) - { - table->HostClipRect.Min.x = ImMin(table->HostClipRect.Min.x + border_size, table->HostClipRect.Max.x); - if (inner_window->DecoOuterSizeX2 == 0.0f) - table->HostClipRect.Max.x = ImMax(table->HostClipRect.Max.x - border_size, table->HostClipRect.Min.x); - } - if (flags & ImGuiTableFlags_BordersOuterH) - { - table->HostClipRect.Min.y = ImMin(table->HostClipRect.Min.y + border_size, table->HostClipRect.Max.y); - if (inner_window->DecoOuterSizeY2 == 0.0f) - table->HostClipRect.Max.y = ImMax(table->HostClipRect.Max.y - border_size, table->HostClipRect.Min.y); - } - } + (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f, + (flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f, + ((flags & ImGuiTableFlags_BordersOuterV) && ((inner_window == outer_window) || inner_window->DecoOuterSizeX2 == 0.0f)) ? border_size : 0.0f, + ((flags & ImGuiTableFlags_BordersOuterH) && ((inner_window == outer_window) || inner_window->DecoOuterSizeY2 == 0.0f)) ? border_size : 0.0f, + }; + if (inner_window != outer_window) + table->HostClipRect.ShrinkClamp(border_size_outer.Min, border_size_outer.Max); // Padding and Spacing // - None ........Content..... Pad .....Content........ @@ -528,17 +523,13 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->RowBgColorCounter = 0; table->LastRowFlags = ImGuiTableRowFlags_None; table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; + if (inner_window == outer_window) + table->InnerClipRect.ShrinkClamp(border_size_outer.Min, border_size_outer.Max); table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width table->InnerClipRect.ClipWithFull(table->HostClipRect); - if (flags & ImGuiTableFlags_NoHostExtendY) - { - if (flags & ImGuiTableFlags_BordersOuterH) - table->InnerClipRect.Max.y = ImClamp(table->OuterRect.Max.y - border_size, table->InnerClipRect.Min.y, table->InnerClipRect.Max.y); - } - else - { + if ((flags & ImGuiTableFlags_NoHostExtendY) == 0) table->InnerClipRect.Max.y = table->HostClipRect.Max.y; - } + table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() table->RowCellPaddingY = 0.0f; @@ -1513,10 +1504,10 @@ void ImGui::EndTable() // but since the later is likely to be impossible to do we'd rather update both axes together. if (table->Flags & ImGuiTableFlags_ScrollX) { - const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; + const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; float max_pos_x = inner_window->DC.CursorMaxPos.x; if (table->RightMostEnabledColumn != -1) - max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border); + max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - border_size_outer_w); if (table->ResizedColumn != -1) max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2); inner_window->DC.CursorMaxPos.x = max_pos_x + table->TempData->AngledHeadersExtraWidth; @@ -3049,7 +3040,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) // Draw bottom-most row border between it and above outer border. const float border_y = table->RowPosY2; if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) - inner_drawlist->AddLineH(table->BorderX1 + border_size_outer_w, table->BorderX2 - border_size_outer_w, border_y, table->BorderColorLight, border_size_inner); + inner_drawlist->AddLineH(table->BorderX1, table->BorderX2, border_y, table->BorderColorLight, border_size_inner); } inner_drawlist->PopClipRect(); From 89845f9db638c998c33d2a6a0d30dd65ff9c9369 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Oct 2026 20:42:01 +0100 Subject: [PATCH 203/245] Tables: fixed various issues with using ImGuiTableFlags_NoHostExtendX. --- docs/CHANGELOG.txt | 6 +++--- imgui_tables.cpp | 11 +++++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 96ebe7493..dddcff7a2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,14 +80,14 @@ Other Changes: `io.DisplayFramebufferScale` is not an integer (regression in 1.93.0). (#9598) - Tables: - Fixed various border overshooting issues, some mostly visible with transparent - borders: (#4678) + borders and under specific conditions: (#4678) - On non-scrolling tables, inner horizontal borders slightly overlapped outer vertical ones with certain settings. - On non-scrolling tables, clamping lower border coordinates to stay within visible range (no visible change, but it makes ImDrawCmd AABB more sensible). - Fixed vertical inner borders slightly overlapping bottom outer border. - - Fixed various issues with using `ImGuiTableFlags_NoHostExtendY`: - - Fixed selectable highlight straying off the Y2 clipping limit. + - Fixed various issues using `ImGuiTableFlags_NoHostExtendX`/`_NoHostExtendY`: + - Fixed selectable highlight straying off the X2/Y2 clipping limit. - Fixed parent window work rectangle affecting the Y2 clipping limit. - Fixed the Y2 clipping limit overlapping bottom outer border. - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f05c29f73..b46f23b04 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1310,8 +1310,9 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->Flags &= ~ImGuiTableFlags_NoHostExtendX; if (table->Flags & ImGuiTableFlags_NoHostExtendX) { - table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1; - table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1); + const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; + table->OuterRect.Max.x = table->WorkRect.Max.x = ImMin(table->OuterRect.Max.x, unused_x1 + border_size_outer_w); + table->InnerClipRect.Max.x = ImClamp(table->OuterRect.Max.x - border_size_outer_w, table->InnerClipRect.Min.x, table->InnerClipRect.Max.x); } table->InnerWindow->ParentWorkRect = table->WorkRect; table->BorderX1 = table->InnerClipRect.Min.x; @@ -2734,8 +2735,10 @@ void ImGui::TableSetupDrawChannels(ImGuiTable* table) table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect; table->Bg2ClipRectForDrawCmd = table->HostClipRect; IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y); + if (table->Flags & ImGuiTableFlags_NoHostExtendX) + table->Bg2ClipRectForDrawCmd.Max.x = ImMin(table->Bg2ClipRectForDrawCmd.Max.x, table->BgClipRect.Max.x); // Don't apply to Bg0: shapes in Bg0 are already CPU clipped and it makes merging fails. if (table->Flags & ImGuiTableFlags_NoHostExtendY) - table->Bg2ClipRectForDrawCmd.Max.y = ImMin(table->Bg2ClipRectForDrawCmd.Max.y, table->BgClipRect.Max.y); // Don't apply to Bg0: shapes in Bg0 are already CPU clipped and it makes merging fails. + table->Bg2ClipRectForDrawCmd.Max.y = ImMin(table->Bg2ClipRectForDrawCmd.Max.y, table->BgClipRect.Max.y); // " } // This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). @@ -2893,7 +2896,7 @@ void ImGui::TableMergeDrawChannels(ImGuiTable* table) merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x); if ((merge_group_n & 2) == 0 || !has_freeze_v) merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y); - if ((merge_group_n & 1) != 0) + if ((merge_group_n & 1) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendX) == 0) merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x); if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0) merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y); From f88ec043afbb800c99d05ad74e348bd70e10da9d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 29 Oct 2026 20:56:04 +0100 Subject: [PATCH 204/245] Tables: use center-bias for horizontal borders to better support thick borders. (#9415) + Demo: adjust colors in 'Background Color' section to better showcase the blending difference between Bg0 and Bg1. --- imgui_demo.cpp | 10 +++++++--- imgui_tables.cpp | 4 ++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 547661f7d..a2afd55ad 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6428,7 +6428,9 @@ static void DemoWindowTables() { static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells static bool init = true; - if (!show_widget_frame_bg) + if (show_widget_frame_bg) + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0.0f); + else ImGui::PushStyleColor(ImGuiCol_FrameBg, 0); for (int cell = 0; cell < 3 * 5; cell++) { @@ -6440,7 +6442,9 @@ static void DemoWindowTables() ImGui::InputText("##cell", text_bufs[cell], IM_COUNTOF(text_bufs[cell])); ImGui::PopID(); } - if (!show_widget_frame_bg) + if (show_widget_frame_bg) + ImGui::PopStyleVar(); + else ImGui::PopStyleColor(); init = false; ImGui::EndTable(); @@ -7050,7 +7054,7 @@ static void DemoWindowTables() // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. if (row_bg_type != 0) { - ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient? + ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.40f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.40f)); // Flat or Gradient? ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color); } diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b46f23b04..483cf3004 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2216,11 +2216,11 @@ void ImGui::TableEndRow(ImGuiTable* table) // Draw top border if (top_border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, table->BorderSize); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, table->BorderSize, ImDrawFlags_StrokeCenterBiased); // Draw bottom border at the row unfreezing mark (always strong) if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, table->BorderSize); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, table->BorderSize, ImDrawFlags_StrokeCenterBiased); } // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) From a13badd73e3780690208fde799edb1e73c2f8377 Mon Sep 17 00:00:00 2001 From: MilosLord Date: Fri, 30 Oct 2026 11:56:02 +0100 Subject: [PATCH 205/245] MultiSelect: fixed ImGuiSelectionBasicStorage::GetNextSelectedItem() reading past the end of storage when trailing items are unselected (#9604) --- docs/CHANGELOG.txt | 3 +++ imgui_widgets.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dddcff7a2..4ba908f4f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -90,6 +90,9 @@ Other Changes: - Fixed selectable highlight straying off the X2/Y2 clipping limit. - Fixed parent window work rectangle affecting the Y2 clipping limit. - Fixed the Y2 clipping limit overlapping bottom outer border. +- Multi-Select: + - Fixed `ImGuiSelectionBasicStorage::GetNextSelectedItem()` reading one past the + end of storage when trailing items are unselected (#9604) [@MilosLord] - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e1a884429..0b862b437 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -8803,7 +8803,7 @@ bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* it = _Storage.Data.Data; IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); if (it != it_end) - while (it->val_i == 0 && it < it_end) + while (it < it_end && it->val_i == 0) it++; const bool has_more = (it != it_end); *opaque_it = has_more ? (void**)(it + 1) : (void**)(it); From 1023d3ddaa75072806f6d11c7b434ed031ea14c1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 Oct 2026 17:32:06 +0100 Subject: [PATCH 206/245] InputText: fixed ImGuiInputTextCallbackData::InsertChars() mistakenly over growing internal buffer. (#9603, #7925) Note that the 32-256 ranges may seem misleading because ImVector<> handle its growth policy but it is also the size we request to underlying user impl hence the clamps. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0b862b437..f36a888c2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4471,7 +4471,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (new_text_len + BufTextLen + 1 > obj->TextA.Size && is_resizable && !is_readonly) { IM_ASSERT(Buf == obj->TextA.Data); - int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; + int new_buf_size = BufTextLen + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1; obj->TextA.resize(new_buf_size + 1); obj->TextSrc = obj->TextA.Data; Buf = obj->TextA.Data; From 391f714c3736206b896b63d6d5dfbc6a5e7ed4aa Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 Oct 2026 19:54:08 +0100 Subject: [PATCH 207/245] RenderArrow doesn't need 64-bits rounding. Added ImRoundPositive() for consistency. --- imgui_draw.cpp | 6 +++--- imgui_internal.h | 12 +++++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6ab6c6c45..6d8e3f224 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -7582,9 +7582,9 @@ void ImGui::RenderArrowEx(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float co // Pixel align when at a right angle if (is_fill && (cos_a * sin_a >= -FLT_EPSILON) && (cos_a * sin_a <= FLT_EPSILON)) { - p[0] = ImRoundSigned64(p[0]); - p[1] = ImRoundSigned64(p[1]); - p[2] = ImRoundSigned64(p[2]); + p[0] = ImRoundSigned(p[0]); + p[1] = ImRoundSigned(p[1]); + p[2] = ImRoundSigned(p[2]); } if (is_fill) diff --git a/imgui_internal.h b/imgui_internal.h index 001bc687c..145f3f137 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -284,8 +284,8 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_MEMALIGN(_OFF,_ALIGN) (((_OFF) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8 #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 -#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // Positive values only! ImTrunc() is not inlined in MSVC debug builds -#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! +#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // Positive values only! == ImTrunc() which is not inlined in MSVC debug builds +#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! == ImRoundPositive() which is not inlined in MSVC debug builds. //#define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) // Hint for branch prediction @@ -542,14 +542,16 @@ inline float ImSaturate(float f) { return inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; } -inline float ImTrunc(float f) { return (float)(int)(f); } +inline float ImTrunc(float f) { return (float)(int)(f); } // == IM_TRUNC() inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } +inline float ImTrunc64(float f) { return (float)(ImS64)(f); } inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } -inline float ImTrunc64(float f) { return (float)(ImS64)(f); } +inline float ImRoundPositive(float f) { return (float)(int)(f + 0.5f); } // == IM_ROUND(). Positive values only. inline float ImRoundPositive64(float f) { return (float)(ImS64)(f + 0.5f); } // Positive values only. +inline float ImRoundSigned(float f) { return (float)(int)(f >= 0.0f ? f + 0.5f : f - 0.5f); } +inline ImVec2 ImRoundSigned(const ImVec2& v) { return ImVec2((float)(int)(v.x >= 0.0f ? v.x + 0.5f : v.x - 0.5f), (float)(int)(v.y >= 0.0f ? v.y + 0.5f : v.y - 0.5f)); } inline float ImRoundSigned64(float f) { return (float)(ImS64)(f >= 0.0f ? f + 0.5f : f - 0.5f); } -inline ImVec2 ImRoundSigned64(const ImVec2& v) { return ImVec2((float)(ImS64)(v.x >= 0.0f ? v.x + 0.5f : v.x - 0.5f), (float)(ImS64)(v.y >= 0.0f ? v.y + 0.5f : v.y - 0.5f)); } inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the bit-hack version (search for "0x1p120f"). inline int ImModPositive(int a, int b) { return (a + b) % b; } inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } From 7ee4dbac898be10398e22e5915eb12af9d7acc19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milo=C5=A1=20=C4=90or=C4=91evi=C4=87?= <118117650+MilosLord@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:27:23 +0100 Subject: [PATCH 208/245] imgui_freetype: fixed undefined float to integer conversion when de-multiplying a color glyph with a color above its alpha. (#9599) --- misc/freetype/imgui_freetype.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 975374554..d0d6b8950 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -295,7 +295,7 @@ static void ImGui_ImplFreeType_BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* d case FT_PIXEL_MODE_BGRA: { // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. - #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u) + #define DE_MULTIPLY(color, alpha) (ImU32)ImMin(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f, 255.0f) for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) for (uint32_t x = 0; x < w; x++) { From c6affd114531786ed6615c6ef4036cbbed39808e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Nov 2026 16:13:30 +0100 Subject: [PATCH 209/245] Tables: move code in BeginTableEx() so that RowPosY1 may be assigned before altering WorkRect with padding (subsequent commit). --- imgui_tables.cpp | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 483cf3004..f9fe1e487 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -518,21 +518,11 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f; table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX; - table->CurrentColumn = -1; - table->CurrentRow = -1; - table->RowBgColorCounter = 0; - table->LastRowFlags = ImGuiTableRowFlags_None; - table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; - if (inner_window == outer_window) - table->InnerClipRect.ShrinkClamp(border_size_outer.Min, border_size_outer.Max); - table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width - table->InnerClipRect.ClipWithFull(table->HostClipRect); - if ((flags & ImGuiTableFlags_NoHostExtendY) == 0) - table->InnerClipRect.Max.y = table->HostClipRect.Max.y; - table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() table->RowCellPaddingY = 0.0f; + table->RowBgColorCounter = 0; + table->LastRowFlags = ImGuiTableRowFlags_None; table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any table->FreezeColumnsRequest = table->FreezeColumnsCount = 0; table->IsUnfrozenRows = true; @@ -542,6 +532,15 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->AngledHeadersHeight = 0.0f; temp_data->AngledHeadersExtraWidth = 0.0f; + table->CurrentColumn = -1; + table->CurrentRow = -1; + table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; + if (inner_window == outer_window) + table->InnerClipRect.ShrinkClamp(border_size_outer.Min, border_size_outer.Max); + table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width + table->InnerClipRect.ClipWithFull(table->HostClipRect); + if ((flags & ImGuiTableFlags_NoHostExtendY) == 0) + table->InnerClipRect.Max.y = table->HostClipRect.Max.y; // Using opaque colors facilitate overlapping lines of the grid, otherwise we'd need to improve TableDrawBorders() table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong); table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight); From 852269e25f2e7b54469f74853405a8d438e14fa8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Nov 2026 16:22:54 +0100 Subject: [PATCH 210/245] Tables: fixed Selectable/TreeNode highlight overlapping left/right-most edges when using a border + no scrolling. (#4678) --- imgui_internal.h | 1 + imgui_tables.cpp | 18 ++++++++---------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 145f3f137..57851e7ee 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3262,6 +3262,7 @@ struct IMGUI_API ImGuiTableTempData int TableIndex; // Index in g.Tables.Buf[] pool float LastTimeActive; // Last timestamp this structure was used float AngledHeadersExtraWidth; // Used in EndTable() + ImRect BorderOuterSizes; ImVector AngledHeadersRequests; // Used in TableAngledHeadersRow() // FIXME: Single instance is enough? // Topology change diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f9fe1e487..72202580e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -490,15 +490,12 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with // different x/y values to BeginChild().) // - For non-scrolling window, this is applied to table->InnerClipRect below. - ImRect border_size_outer = - { - (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f, - (flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f, - ((flags & ImGuiTableFlags_BordersOuterV) && ((inner_window == outer_window) || inner_window->DecoOuterSizeX2 == 0.0f)) ? border_size : 0.0f, - ((flags & ImGuiTableFlags_BordersOuterH) && ((inner_window == outer_window) || inner_window->DecoOuterSizeY2 == 0.0f)) ? border_size : 0.0f, - }; + temp_data->BorderOuterSizes.Min.x = (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; + temp_data->BorderOuterSizes.Min.y = (flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f; + temp_data->BorderOuterSizes.Max.x = ((flags & ImGuiTableFlags_BordersOuterV) && ((inner_window == outer_window) || inner_window->DecoOuterSizeX2 == 0.0f)) ? border_size : 0.0f; + temp_data->BorderOuterSizes.Max.y = ((flags & ImGuiTableFlags_BordersOuterH) && ((inner_window == outer_window) || inner_window->DecoOuterSizeY2 == 0.0f)) ? border_size : 0.0f; if (inner_window != outer_window) - table->HostClipRect.ShrinkClamp(border_size_outer.Min, border_size_outer.Max); + table->HostClipRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); // Padding and Spacing // - None ........Content..... Pad .....Content........ @@ -536,7 +533,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->CurrentRow = -1; table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; if (inner_window == outer_window) - table->InnerClipRect.ShrinkClamp(border_size_outer.Min, border_size_outer.Max); + table->InnerClipRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width table->InnerClipRect.ClipWithFull(table->HostClipRect); if ((flags & ImGuiTableFlags_NoHostExtendY) == 0) @@ -1313,7 +1310,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->OuterRect.Max.x = table->WorkRect.Max.x = ImMin(table->OuterRect.Max.x, unused_x1 + border_size_outer_w); table->InnerClipRect.Max.x = ImClamp(table->OuterRect.Max.x - border_size_outer_w, table->InnerClipRect.Min.x, table->InnerClipRect.Max.x); } - table->InnerWindow->ParentWorkRect = table->WorkRect; + table->InnerWindow->ParentWorkRect = table->WorkRect; // Used by Selectable/TreeNode highlight + table->InnerWindow->ParentWorkRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); table->BorderX1 = table->InnerClipRect.Min.x; table->BorderX2 = table->InnerClipRect.Max.x; From c5131aff7ea0ee4b932df5a2f08b5237b960a4c3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Nov 2026 16:31:32 +0100 Subject: [PATCH 211/245] Tables: draw outer border before inner borders. --- imgui_tables.cpp | 54 ++++++++++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 72202580e..d56297a56 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2966,6 +2966,33 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const float border_size_inner = table->BorderSize; const float draw_y2_limit = table->OuterWindow->ClipRect.Max.y + (2.0f * ImMax(border_size_outer_h, inner_drawlist->_FringeScale)); + // Draw outer border + if (table->Flags & ImGuiTableFlags_BordersOuter) + { + // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + // of it in inner window, and the part that's over scrollbars in the outer window..) + // Either solution currently won't allow us to use a larger border size: the border would clipped. + ImRect outer_border = table->OuterRect; + outer_border.Max.y = ImMin(outer_border.Max.y, draw_y2_limit); // Clamp but keep bottom border non-visible. + const ImU32 outer_col = table->BorderColorStrong; + if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) + { + inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size_outer_w); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterV) + { + inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); + inner_drawlist->AddLineV(outer_border.Max.x - border_size_outer_w, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterH) + { + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size_outer_h); + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size_outer_h, outer_col, border_size_outer_h); + } + } + // Draw inner border and resizing feedback ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size_outer_h : 0.0f); @@ -3008,33 +3035,6 @@ void ImGui::TableDrawBorders(ImGuiTable* table) } } - // Draw outer border - // FIXME: could use AddRect or explicit VLine/HLine helper? - if (table->Flags & ImGuiTableFlags_BordersOuter) - { - // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call - // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their - // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part - // of it in inner window, and the part that's over scrollbars in the outer window..) - // Either solution currently won't allow us to use a larger border size: the border would clipped. - ImRect outer_border = table->OuterRect; - outer_border.Max.y = ImMin(outer_border.Max.y, draw_y2_limit); // Clamp but keep bottom border non-visible. - const ImU32 outer_col = table->BorderColorStrong; - if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) - { - inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size_outer_w); - } - else if (table->Flags & ImGuiTableFlags_BordersOuterV) - { - inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); - inner_drawlist->AddLineV(outer_border.Max.x - border_size_outer_w, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); - } - else if (table->Flags & ImGuiTableFlags_BordersOuterH) - { - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size_outer_h); - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size_outer_h, outer_col, border_size_outer_h); - } - } if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) { // Draw bottom-most row border between it and above outer border. From 67f442d5de5ace0e8531442e0cb5446137f01147 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 2 Nov 2026 17:41:04 +0100 Subject: [PATCH 212/245] Tables: workaround/hack for max width 1-off issue when right-most column is resizable. (#4678) Requires !Scroll && Resizable && (NoHostExtendX || RightMostColumnnIsFixed) to see a difference. --- imgui_tables.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d56297a56..f7a39f689 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2415,7 +2415,7 @@ void ImGui::TableEndCell(ImGuiTable* table) //------------------------------------------------------------------------- // [SECTION] Tables: Columns width management //------------------------------------------------------------------------- -// - TableGetMaxColumnWidth() [Internal] +// - TableCalcMaxColumnWidth() [Internal] // - TableGetColumnWidthAuto() [Internal] // - TableSetColumnWidth() // - TableSetColumnWidthAutoSingle() [Internal] @@ -3012,14 +3012,21 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1); - if (column->MaxX > table->InnerClipRect.Max.x && !is_resized) + + // FIXME-TABLE: 1-off display hack for right-most column when resizable (!Scroll && Resizable && (NoHostExtendX || RightMostIsFixed)). + // Fixing actual width would involve altering width_avail in layout and TableCalcMaxColumnWidth(), which would drop the property + // ColumnsGivenWidth == Outer Allocated Width. Worth reworking, but would only make sense if we accept that BorderSize affects layout. + float draw_x2 = column->MaxX; + if (draw_x2 >= table->InnerClipRect.Max.x && draw_x2 - 1.0f <= table->InnerClipRect.Max.x) + draw_x2 = table->InnerClipRect.Max.x; + if (draw_x2 >= table->InnerClipRect.Max.x && !is_resized && !is_hovered) continue; // Decide whether right-most column is visible if (column->NextEnabledColumn == -1 && !is_resizable) if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX)) continue; - if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + if (draw_x2 <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. continue; // Draw in outer window so right-most column won't be clipped @@ -3031,7 +3038,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) else if ((table->Flags & (ImGuiTableFlags_NoBordersInBodyUntilResize | ImGuiTableFlags_NoBordersInBody)) == 0) draw_y2 = draw_y2_body; if (draw_y2 > draw_y1) - inner_drawlist->AddLineV(column->MaxX, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size_inner); + inner_drawlist->AddLineV(draw_x2, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size_inner); } } From 9d0b72573a27d860280811d58ef9ed62f4d46c05 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Nov 2026 20:03:57 +0100 Subject: [PATCH 213/245] Windows: using SetNextWindowPos() with a pivot while a window is hidden and measuring size will still apply temporary position until size is figured out. (#9568) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4ba908f4f..bbd5e0ba4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -72,6 +72,9 @@ Other Changes: shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) Legacy arrow: size: (0.60f,0.70f), thickness: 0.0f New arrow: size: (0.72f,0.40f), thickness: 0.30f +- Windows: + - Using `SetNextWindowPos()` with a pivot while a window is hidden and measuring + size will still apply temporary position until size is figured out. (#9568) - TreeNode: - TreeNodeGetOpen(): added flags parameter to allow passing `ImGuiTreeNodeFlags_DefaultOpen` or `ImGuiTreeNodeFlags_Leaf`. (#9569, #9592, #3823, #9251) [@adalisk-emikhaylov, @Yaki-Blake] diff --git a/imgui.cpp b/imgui.cpp index 67edfa37b..4519c96fb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7994,9 +7994,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Pos = parent_window->DC.CursorPos; } - const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); - if (window_pos_with_pivot) + if (window->SetWindowPosVal.x != FLT_MAX) + { + const ImVec2 backup_pos_val = window->SetWindowPosVal; SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) + if (window->HiddenFramesCannotSkipItems != 0) + window->SetWindowPosVal = backup_pos_val; // Restore set request while hidden, so an updated size will be accounted for. (#9568) + } else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) From b2298afa71f942b40f8bbeeb83a24a94acbf795d Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Nov 2026 18:14:26 +0100 Subject: [PATCH 214/245] Examples: Apple: add native menu with Quit entry. Add missing title text. Standardize code. --- .gitignore | 1 + examples/example_apple_metal/main.mm | 15 +++++++++++++++ examples/example_apple_metal4/main.mm | 15 +++++++++++++++ examples/example_apple_opengl2/main.mm | 19 +++++++------------ examples/example_apple_opengl3/main.mm | 19 +++++++------------ 5 files changed, 45 insertions(+), 24 deletions(-) diff --git a/.gitignore b/.gitignore index 009e61ede..730857c1b 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,7 @@ cmake-build-* ## Unix executables from our example Makefiles examples/example_apple_metal/example_apple_metal +examples/example_apple_metal4/example_apple_metal4 examples/example_apple_opengl2/example_apple_opengl2 examples/example_apple_opengl3/example_apple_opengl3 examples/example_glfw_metal/example_glfw_metal diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index cddc1093c..34811ac4f 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -273,6 +273,20 @@ @implementation AppDelegate +-(void)applicationDidFinishLaunching:(NSNotification *)notification +{ + NSMenu* mainMenuBar = [[NSMenu alloc] init]; + NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+Metal Example"]; + NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; + [quitMenuItem setTarget:NSApp]; + [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + + NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; + [appMenuItem setSubmenu:appMenu]; + [mainMenuBar addItem:appMenuItem]; + [NSApp setMainMenu:mainMenuBar]; +} + -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return YES; @@ -287,6 +301,7 @@ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable backing:NSBackingStoreBuffered defer:NO]; + self.window.title = @"Dear ImGui OSX+Metal Example"; self.window.contentViewController = rootViewController; [self.window center]; [self.window makeKeyAndOrderFront:self]; diff --git a/examples/example_apple_metal4/main.mm b/examples/example_apple_metal4/main.mm index 553eeb34c..5e2d4772b 100644 --- a/examples/example_apple_metal4/main.mm +++ b/examples/example_apple_metal4/main.mm @@ -289,6 +289,20 @@ @implementation AppDelegate +-(void)applicationDidFinishLaunching:(NSNotification *)notification +{ + NSMenu* mainMenuBar = [[NSMenu alloc] init]; + NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+Metal4 Example"]; + NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; + [quitMenuItem setTarget:NSApp]; + [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + + NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; + [appMenuItem setSubmenu:appMenu]; + [mainMenuBar addItem:appMenuItem]; + [NSApp setMainMenu:mainMenuBar]; +} + -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return YES; @@ -303,6 +317,7 @@ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable backing:NSBackingStoreBuffered defer:NO]; + self.window.title = @"Dear ImGui OSX+Metal4 Example"; self.window.contentViewController = rootViewController; [self.window center]; [self.window makeKeyAndOrderFront:self]; diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 67b546ead..e0438d9c9 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -191,19 +191,14 @@ -(void)setupMenu { NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu; - NSMenuItem* menuItem; + NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"]; + NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; + [quitMenuItem setTarget:NSApp]; + [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"]; - menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"]; - [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - - menuItem = [[NSMenuItem alloc] init]; - [menuItem setSubmenu:appMenu]; - - [mainMenuBar addItem:menuItem]; - - appMenu = nil; + NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; + [appMenuItem setSubmenu:appMenu]; + [mainMenuBar addItem:appMenuItem]; [NSApp setMainMenu:mainMenuBar]; } diff --git a/examples/example_apple_opengl3/main.mm b/examples/example_apple_opengl3/main.mm index 7cb2e2a33..ffb344343 100644 --- a/examples/example_apple_opengl3/main.mm +++ b/examples/example_apple_opengl3/main.mm @@ -191,19 +191,14 @@ -(void)setupMenu { NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu; - NSMenuItem* menuItem; + NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL3 Example"]; + NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; + [quitMenuItem setTarget:NSApp]; + [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL3 Example"]; - menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL3 Example" action:@selector(terminate:) keyEquivalent:@"q"]; - [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - - menuItem = [[NSMenuItem alloc] init]; - [menuItem setSubmenu:appMenu]; - - [mainMenuBar addItem:menuItem]; - - appMenu = nil; + NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; + [appMenuItem setSubmenu:appMenu]; + [mainMenuBar addItem:appMenuItem]; [NSApp setMainMenu:mainMenuBar]; } From 8c8b8fc266e8cd7fac09340c0373abc28732adb0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Nov 2026 18:20:12 +0100 Subject: [PATCH 215/245] Examples: Apple: standardize activation and bringing to front. + fix warnings. # Conflicts: # backends/imgui_impl_metal4.mm --- backends/imgui_impl_metal4.mm | 4 ++-- examples/example_apple_metal/main.mm | 4 ++-- examples/example_apple_metal4/main.mm | 4 ++-- examples/example_apple_opengl2/main.mm | 19 ++++++++++--------- examples/example_apple_opengl3/main.mm | 19 ++++++++++--------- 5 files changed, 26 insertions(+), 24 deletions(-) diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index 2f9a53bdb..b811e3d19 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -139,7 +139,7 @@ void ImGui_ImplMetal4_NewFrame(MTL4RenderPassDescriptor* renderPassDescriptor, i { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal4_Init()?"); - IM_ASSERT(frameInFlightIndex < bd->SharedMetalContext.framesInFlight && "frameInFlightIndex out of range! See framesInFlight passed to ImGui_ImplMetal4_Init()."); + IM_ASSERT(frameInFlightIndex < (int)bd->SharedMetalContext.framesInFlight && "frameInFlightIndex out of range! See framesInFlight passed to ImGui_ImplMetal4_Init()."); #ifdef IMGUI_IMPL_METAL_CPP bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; #else @@ -479,7 +479,7 @@ bool ImGui_ImplMetal4_Init(id device, id commandQue bd->SharedMetalContext.commandQueue = commandQueue; bd->SharedMetalContext.framesInFlight = (NSUInteger)framesInFlight; NSMutableArray*>* bufferCaches = [NSMutableArray array]; - for (NSUInteger i = 0; i < framesInFlight; i++) + for (NSUInteger i = 0; i < (NSUInteger)framesInFlight; i++) [bufferCaches addObject:[NSMutableArray array]]; bd->SharedMetalContext.bufferCaches = bufferCaches; return true; diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 34811ac4f..cb27f3330 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -111,7 +111,6 @@ #if TARGET_OS_OSX ImGui_ImplOSX_Init(self.view); - [NSApp activateIgnoringOtherApps:YES]; #endif } @@ -285,6 +284,8 @@ [appMenuItem setSubmenu:appMenu]; [mainMenuBar addItem:appMenuItem]; [NSApp setMainMenu:mainMenuBar]; + + [NSApp activateIgnoringOtherApps:YES]; } -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender @@ -349,7 +350,6 @@ int main(int, const char**) AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window [NSApp setDelegate:appDelegate]; - [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; } return 0; diff --git a/examples/example_apple_metal4/main.mm b/examples/example_apple_metal4/main.mm index 5e2d4772b..40fbbe764 100644 --- a/examples/example_apple_metal4/main.mm +++ b/examples/example_apple_metal4/main.mm @@ -117,7 +117,6 @@ #if TARGET_OS_OSX ImGui_ImplOSX_Init(self.view); - [NSApp activateIgnoringOtherApps:YES]; #endif } @@ -301,6 +300,8 @@ [appMenuItem setSubmenu:appMenu]; [mainMenuBar addItem:appMenuItem]; [NSApp setMainMenu:mainMenuBar]; + + [NSApp activateIgnoringOtherApps:YES]; } -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender @@ -365,7 +366,6 @@ int main(int, const char**) AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window [NSApp setDelegate:appDelegate]; - [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; } return 0; diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index e0438d9c9..94e03c6d4 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -209,10 +209,6 @@ -(void)applicationDidFinishLaunching:(NSNotification *)aNotification { - // Make the application a foreground application (else it won't receive keyboard events) - ProcessSerialNumber psn = {0, kCurrentProcess}; - TransformProcessType(&psn, kProcessTransformToForegroundApplication); - // Menu [self setupMenu]; @@ -236,6 +232,8 @@ NSLog(@"No OpenGL Context!"); [view initialize]; + + [NSApp activateIgnoringOtherApps:YES]; } @end @@ -244,14 +242,17 @@ // Application main() function //----------------------------------------------------------------------------------- -int main(int argc, const char* argv[]) +int main(int, const char**) { @autoreleasepool { - NSApp = [NSApplication sharedApplication]; - AppDelegate* delegate = [[AppDelegate alloc] init]; - [[NSApplication sharedApplication] setDelegate:delegate]; + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + + AppDelegate* appDelegate = [[AppDelegate alloc] init]; + [NSApp setDelegate:appDelegate]; + [NSApp run]; } - return NSApplicationMain(argc, argv); + return 0; } diff --git a/examples/example_apple_opengl3/main.mm b/examples/example_apple_opengl3/main.mm index ffb344343..77c95a90e 100644 --- a/examples/example_apple_opengl3/main.mm +++ b/examples/example_apple_opengl3/main.mm @@ -209,10 +209,6 @@ -(void)applicationDidFinishLaunching:(NSNotification *)aNotification { - // Make the application a foreground application (else it won't receive keyboard events) - ProcessSerialNumber psn = {0, kCurrentProcess}; - TransformProcessType(&psn, kProcessTransformToForegroundApplication); - // Menu [self setupMenu]; @@ -237,6 +233,8 @@ NSLog(@"No OpenGL Context!"); [view initialize]; + + [NSApp activateIgnoringOtherApps:YES]; } @end @@ -245,14 +243,17 @@ // Application main() function //----------------------------------------------------------------------------------- -int main(int argc, const char* argv[]) +int main(int, const char**) { @autoreleasepool { - NSApp = [NSApplication sharedApplication]; - AppDelegate* delegate = [[AppDelegate alloc] init]; - [[NSApplication sharedApplication] setDelegate:delegate]; + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + + AppDelegate* appDelegate = [[AppDelegate alloc] init]; + [NSApp setDelegate:appDelegate]; + [NSApp run]; } - return NSApplicationMain(argc, argv); + return 0; } From a1af3c1a59fe81f7a1cac10dcead0a383b99f245 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Nov 2026 11:38:44 +0100 Subject: [PATCH 216/245] Demo: fixed enabling _WrapAround in "Drag and Slider Flags" demo. --- imgui_demo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a2afd55ad..5545ecc41 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1852,7 +1852,7 @@ static void DemoWindowWidgetsDragsAndSliders() ImGui::Text("Underlying float value: %f", slider_f); ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags_for_sliders); ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags_for_sliders); - ImGui::SliderFloat4("SliderFloat4 (0 -> 1)", slider_f4, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. + ImGui::SliderFloat4("SliderFloat4 (0 -> 1)", slider_f4, 0.0f, 1.0f, "%.3f", flags_for_sliders); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. ImGui::TreePop(); } From 253aa51aba7c3c466b042400c4c16bff81560cda Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Nov 2026 12:38:19 +0100 Subject: [PATCH 217/245] Drags: fixed handling of ImGuiSliderFlags_WrapAround when dragging fast. (#9612, #9611, #7749) --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 1 + imgui_internal.h | 3 +++ imgui_widgets.cpp | 10 ++++++---- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bbd5e0ba4..23b05b5b8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -96,6 +96,8 @@ Other Changes: - Multi-Select: - Fixed `ImGuiSelectionBasicStorage::GetNextSelectedItem()` reading one past the end of storage when trailing items are unselected (#9604) [@MilosLord] +- Drags: fixed handling of `ImGuiSliderFlags_WrapAround`: value could temporarily + escape the range when dragging fast. (#9612, #9611, #7749) [@swayie, @ocornut] - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5545ecc41..bac1791c3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1842,6 +1842,7 @@ static void DemoWindowWidgetsDragsAndSliders() //ImGui::DragFloat("DragFloat (0 -> 0)", &drag_f, 0.005f, 0.0f, 0.0f, "%.3f", flags); // To test ClampZeroRange //ImGui::DragFloat("DragFloat (100 -> 100)", &drag_f, 0.005f, 100.0f, 100.0f, "%.3f", flags); ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags); + ImGui::DragFloat("DragFloat (0 -> 100)", &drag_f, 0.2f, 0, 100, "%.2f", flags); ImGui::DragFloat4("DragFloat4 (0 -> 1)", drag_f4, 0.005f, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. // Sliders diff --git a/imgui_internal.h b/imgui_internal.h index 57851e7ee..add0b8ce1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -531,6 +531,9 @@ template T ImLerp(T a, T b, float t) { return template void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; } template T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; } +inline float ImMod(float a, float b) { return ImFmod(a, b); } +inline double ImMod(double a, double b) { return (double)ImFmod((float)a, (float)b); } // FIXME +template T ImMod(T a, T b) { return a % b; } // - Misc maths helpers inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f36a888c2..62bff5880 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2650,10 +2650,12 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_wrapped) { // Wrap values - if (v_cur < v_min) - v_cur += v_max - v_min + (is_floating_point ? 0 : 1); - if (v_cur > v_max) - v_cur -= v_max - v_min + (is_floating_point ? 0 : 1); + const TYPE range = v_max - v_min + (is_floating_point ? 0 : 1); + TYPE offset = ImMod((TYPE)(v_cur - v_min), range); + if (offset < 0) + offset += range; + v_cur = (TYPE)(v_min + offset); + IM_ASSERT_PARANOID(v_cur >= v_min && v_cur <= v_max); } else { From dbb30112c619990c593ab46f1855ac08d8ff1e52 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Nov 2026 20:27:54 +0100 Subject: [PATCH 218/245] ColorButton, ColorEdit, ColorPicker: fixed an issue rendering colors when inside a BeginDisabled(false) block. (#9511, #9613, #9614) --- docs/CHANGELOG.txt | 4 ++++ imgui_widgets.cpp | 10 ++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 23b05b5b8..a58b03b6b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -98,6 +98,10 @@ Other Changes: end of storage when trailing items are unselected (#9604) [@MilosLord] - Drags: fixed handling of `ImGuiSliderFlags_WrapAround`: value could temporarily escape the range when dragging fast. (#9612, #9611, #7749) [@swayie, @ocornut] +- ColorEdit: + - ColorButton, ColorEdit, ColorPicker: fixed an issue rendering colors when + inside a `BeginDisabled(false)` block, caused by the alpha cancelling-out + code in 1.93.0. (#9511, #9613, #9614) [@tksuoran] - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 62bff5880..91f0d0f61 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6217,7 +6217,8 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl g.NextItemData.ClearFlags(); const float backup_alpha = g.Style.Alpha; - if (g.DisabledStackSize > 0) + const bool is_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0 && (g.DisabledStackSize > 0); // Intentionally not check ItemFlagsSet + if (is_disabled) g.Style.Alpha = g.DisabledAlphaBackup; // Cancel out effect of BeginDisabled() for color swatches. PushID(label); @@ -6579,7 +6580,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl g.ColorEditCurrentID = 0; PopID(); - if (g.DisabledStackSize > 0) + if (is_disabled) g.Style.Alpha = backup_alpha; return value_changed; @@ -6620,7 +6621,8 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl const bool is_mixed = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0; const float backup_alpha = g.Style.Alpha; - if (g.DisabledStackSize > 0) + const bool is_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0 && (g.DisabledStackSize > 0); // Intentionally not use LastItemData.ItemFlags here. + if (is_disabled) g.Style.Alpha = g.DisabledAlphaBackup; // Cancel out effect of BeginDisabled() for color swatches. if (is_mixed) { @@ -6648,7 +6650,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl else window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(col_source), rounding); } - if (g.DisabledStackSize > 0) + if (is_disabled) g.Style.Alpha = backup_alpha; RenderNavCursor(bb, id); if ((flags & ImGuiColorEditFlags_NoBorder) == 0) From 2a98b48358614c4f3b97517a6c108cda78f8b738 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Nov 2026 11:55:53 +0100 Subject: [PATCH 219/245] CI: update runner for iOS build. --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5717f5262..5f0acd670 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -639,7 +639,7 @@ jobs: if: github.event_name == 'workflow_run' Build-iOS: - runs-on: macos-14 + runs-on: macos-26 name: Build - iOS steps: From 1b4a7392f742afb30fe2d90924f06f9d8e093e52 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Nov 2026 12:35:54 +0100 Subject: [PATCH 220/245] Demo: tweaks "Tables" demo. --- imgui_demo.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bac1791c3..d25f6e560 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6126,11 +6126,12 @@ static void DemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags, ImGuiTableFlags_BordersOuter); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags, ImGuiTableFlags_BordersInner); ImGui::Unindent(); - + ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:"); ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text); ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); ImGui::Checkbox("Display headers", &display_headers); + ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags, ImGuiTableFlags_PadOuterX); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers)"); PopStyleCompact(); @@ -6358,6 +6359,7 @@ static void DemoWindowTables() "Actual padding values are using style.CellPadding.\n\n" "In this demo we don't show horizontal borders to emphasize how they don't affect default horizontal padding."); + ImGui::PushID("flags1"); static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV; PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags1, ImGuiTableFlags_PadOuterX); @@ -6368,9 +6370,11 @@ static void DemoWindowTables() ImGui::SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)"); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags1, ImGuiTableFlags_BordersOuterV); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags1, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags1, ImGuiTableFlags_BordersH); static bool show_headers = false; ImGui::Checkbox("show_headers", &show_headers); PopStyleCompact(); + ImGui::PopID(); if (ImGui::BeginTable("table_padding", 3, flags1)) { @@ -6410,7 +6414,7 @@ static void DemoWindowTables() HelpMarker("Setting style.CellPadding to (0,0) or a custom value."); static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; static ImVec2 cell_padding(0.0f, 0.0f); - static bool show_widget_frame_bg = true; + static bool show_widget_frame_bg = false; PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags2, ImGuiTableFlags_Borders); From 135a923659ba2b475f06909bcda8877641a928b5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Nov 2026 12:51:07 +0100 Subject: [PATCH 221/245] Demo: remove some hardcoded sizes. --- imgui_demo.cpp | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d25f6e560..4a9753a89 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4652,6 +4652,8 @@ static void DemoWindowLayout() IMGUI_DEMO_MARKER("Layout/Child windows"); ImGui::SeparatorText("Child windows"); + const float ref_sz = ImGui::GetTextLineHeightWithSpacing(); + HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window."); static bool disable_mouse_wheel = false; static bool disable_menu = false; @@ -4663,7 +4665,7 @@ static void DemoWindowLayout() ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; if (disable_mouse_wheel) window_flags |= ImGuiWindowFlags_NoScrollWithMouse; - ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 260), ImGuiChildFlags_None, window_flags); + ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 15 * ref_sz), ImGuiChildFlags_None, window_flags); for (int i = 0; i < 100; i++) ImGui::Text("%04d: scrollable region", i); ImGui::EndChild(); @@ -4679,7 +4681,7 @@ static void DemoWindowLayout() if (!disable_menu) window_flags |= ImGuiWindowFlags_MenuBar; ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); - ImGui::BeginChild("ChildR", ImVec2(0, 260), ImGuiChildFlags_Borders, window_flags); + ImGui::BeginChild("ChildR", ImVec2(0, 15 * ref_sz), ImGuiChildFlags_Borders, window_flags); if (!disable_menu && ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Menu")) @@ -4708,11 +4710,11 @@ static void DemoWindowLayout() ImGui::SeparatorText("Manual-resize"); { HelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents."); - //if (ImGui::Button("Set Height to 200")) - // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 200.0f)); + //if (ImGui::Button("Set Height to 300")) + // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 300.0f)); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg)); - if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) + if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ref_sz * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) for (int n = 0; n < 10; n++) ImGui::Text("Line %04d", n); ImGui::PopStyleColor(); @@ -4724,12 +4726,12 @@ static void DemoWindowLayout() { static int draw_lines = 3; static int max_height_in_lines = 10; - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::SetNextItemWidth(ref_sz * 7); ImGui::DragInt("Lines Count", &draw_lines, 0.2f); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::SetNextItemWidth(ref_sz * 7); ImGui::DragInt("Max Height (in Lines)", &max_height_in_lines, 0.2f); - ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 1), ImVec2(FLT_MAX, ImGui::GetTextLineHeightWithSpacing() * max_height_in_lines)); + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ref_sz * 1), ImVec2(FLT_MAX, ref_sz * max_height_in_lines)); if (ImGui::BeginChild("ConstrainedChild", ImVec2(-FLT_MIN, 0.0f), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) for (int n = 0; n < draw_lines; n++) ImGui::Text("Line %04d", n); @@ -4749,7 +4751,7 @@ static void DemoWindowLayout() static int offset_x = 0; static bool override_bg_color = true; static ImGuiChildFlags child_flags = ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY; - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::SetNextItemWidth(ref_sz * 7); ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000); ImGui::Checkbox("Override ChildBg color", &override_bg_color); ImGui::CheckboxFlags("ImGuiChildFlags_Borders", &child_flags, ImGuiChildFlags_Borders); @@ -4764,7 +4766,7 @@ static void DemoWindowLayout() ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x); if (override_bg_color) ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); - ImGui::BeginChild("Red", ImVec2(200, 100), child_flags, ImGuiWindowFlags_None); + ImGui::BeginChild("Red", ImVec2(ref_sz * 12.0f, ref_sz * 6.0f), child_flags, ImGuiWindowFlags_None); if (override_bg_color) ImGui::PopStyleColor(); @@ -4861,7 +4863,7 @@ static void DemoWindowLayout() if (show_indented_items) { ImGui::Indent(); - ImGui::DragFloat("float (indented)##6b", &f); + ImGui::DragFloat("##float6b (indented)", &f); ImGui::Unindent(); } ImGui::PopItemWidth(); @@ -4926,7 +4928,8 @@ static void DemoWindowLayout() static int selection[4] = { 0, 1, 2, 3 }; for (int i = 0; i < 4; i++) { - if (i > 0) ImGui::SameLine(); + if (i > 0) + ImGui::SameLine(); ImGui::PushID(i); ImGui::ListBox("", &selection[i], items, IM_COUNTOF(items)); ImGui::PopID(); @@ -4934,9 +4937,11 @@ static void DemoWindowLayout() } ImGui::PopItemWidth(); + const float ref_sz = ImGui::GetTextLineHeightWithSpacing(); + // Dummy IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Dummy"); - ImVec2 button_sz(40, 40); + ImVec2 button_sz(ref_sz * 3.0f, ref_sz * 3.0f); ImGui::Button("A", button_sz); ImGui::SameLine(); ImGui::Dummy(button_sz); ImGui::SameLine(); ImGui::Button("B", button_sz); @@ -5078,9 +5083,9 @@ static void DemoWindowLayout() ImGui::Indent(); // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. - ImGui::Button("80x80", ImVec2(80, 80)); + ImGui::Button("120x120", ImVec2(120, 120)); ImGui::SameLine(); - ImGui::Button("50x50", ImVec2(50, 50)); + ImGui::Button("80x80", ImVec2(80, 80)); ImGui::SameLine(); ImGui::Button("Button()"); ImGui::SameLine(); From 022499b0ce9d7301a8ef9f3e4de75688c09f4279 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Nov 2026 13:10:56 +0100 Subject: [PATCH 222/245] Checkbox: indeterminate/mixed value inner rectangle never has rounding, to reduce confusion with a radio button. (#5518, #5677, #6865, #2644) Amend 2a3517a3998 --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a58b03b6b..da5b2a697 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -98,6 +98,8 @@ Other Changes: end of storage when trailing items are unselected (#9604) [@MilosLord] - Drags: fixed handling of `ImGuiSliderFlags_WrapAround`: value could temporarily escape the range when dragging fast. (#9612, #9611, #7749) [@swayie, @ocornut] +- Checkbox: indeterminate/mixed value inner rectangle never has rounding, + to reduce confusion with a radio button. (#5518, #5677, #6865, #2644) - ColorEdit: - ColorButton, ColorEdit, ColorPicker: fixed an issue rendering colors when inside a `BeginDisabled(false)` block, caused by the alpha cancelling-out diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 91f0d0f61..3d3d1f008 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1299,8 +1299,9 @@ bool ImGui::Checkbox(const char* label, bool* v) { // Undocumented tristate/mixed/indeterminate checkbox (#2644) // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox) - ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f))); - window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); + const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)); + const float rounding = 0.0f;// IM_TRUNC(ImMin((square_sz - pad * 2.0f) * 0.20f, style.FrameRounding)); // Clamp rounding + window->DrawList->AddRectFilled(check_bb.Min + ImVec2(pad, pad), check_bb.Max - ImVec2(pad, pad), check_col, rounding); } else if (*v) { From 3aae2df9f6e5a0fe721e09f23b6e82906a7468f8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Nov 2026 13:14:40 +0100 Subject: [PATCH 223/245] Style: StyleColorsDark(): tweaked PopupBg, ChildBg, to be darker than in 1.93.0. --- docs/CHANGELOG.txt | 2 +- imgui_draw.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index da5b2a697..f54edf32c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,7 +67,7 @@ Autumn cleanup of stuff marked obsolete more than two years ago: Other Changes: - Style: - - `StyleColorsDark()`: tweaked WindowBg to be darker than in 1.93.0. + - `StyleColorsDark()`: tweaked WindowBg, PopupBg, ChildBg to be darker than in 1.93.0. - Added `style.SymbolArrowSizeFactor`, `style.SymbolArrowThicknessFactor` to tweak the shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) Legacy arrow: size: (0.60f,0.70f), thickness: 0.0f diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6d8e3f224..c576e5018 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -192,8 +192,8 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.58f, 0.58f, 0.58f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); + colors[ImGuiCol_ChildBg] = ImVec4(0.17f, 0.17f, 0.17f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.14f, 0.14f, 0.14f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.10f, 0.10f, 1.00f); From 5554e8e4768b367003cb97b23c11e16063e86a32 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Mon, 9 Nov 2026 13:30:01 +0100 Subject: [PATCH 224/245] Backends: GLFW, SDL2: Emscripten's OpenURL() passes 'noopener' to window.open(). (#9615, #7660, #7851) The new tab opened by window.open(url, '_blank') keeps a reference to our page (window.opener). With a "javascript:" url, the script runs in a blank page of the same origin, with full access to ours: a document rendered with TextLinkOpenURL() could carry such a link. 'noopener' removes that reference. --- backends/imgui_impl_glfw.cpp | 2 +- backends/imgui_impl_sdl2.cpp | 2 +- docs/CHANGELOG.txt | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 678129a07..2be125300 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -663,7 +663,7 @@ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817 void ImGui_ImplGlfw_EmscriptenOpenURL(const char* url) { if (url) emscripten::glfw3::OpenURL(url); } #else -EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); +EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank', 'noopener'); }); #endif #endif diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index a93bcc29e..d5ba4dade 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -507,7 +507,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } #ifdef __EMSCRIPTEN__ -EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); +EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank', 'noopener'); }); #endif static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f54edf32c..f310858aa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -112,6 +112,10 @@ Other Changes: to reflect that they can also build X64 or ARM64, given the right environment. Made the script detect the environment when needed (e.g. to specify library path). - Examples: added support for ARM64 in selected build_win.bat helpers. (#9593) [@Harishmcw] +- Backends: + - GLFW, SDL2: Emscripten implementation of `Platform_OpenInShellFn` calls + `window.open()` with `noopener`: prevents newly opened tab from keeping a + reference to opening page. (#9615, #7660, #7851) [@pthom] ----------------------------------------------------------------------- From 8ba9eb061f64f5363833c590f16f2308f02f2f66 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Nov 2026 16:05:00 +0100 Subject: [PATCH 225/245] Internals, Inputs: declaring FindLatestInputEvent() in imgui_internal.h. Might facilitate late-latching experiments? (#9594) --- imgui.cpp | 12 ++++++------ imgui_internal.h | 1 + 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4519c96fb..10a13b56a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1920,7 +1920,7 @@ void ImGuiIO::ClearInputMouse() MouseWheel = MouseWheelH = 0.0f; } -static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1) +ImGuiInputEvent* ImGui::FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg) { ImGuiContext& g = *ctx; for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--) @@ -1965,7 +1965,7 @@ void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value) } // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed) - const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key); + const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key); const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key); const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down; const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue; @@ -2023,7 +2023,7 @@ void ImGuiIO::AddMousePosEvent(float x, float y) ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y); // Filter duplicate - const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos); + const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_MousePos); const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos; if (latest_pos.x == pos.x && latest_pos.y == pos.y) return; @@ -2056,7 +2056,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) } // Filter duplicate - const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button); + const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button); const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button]; if (latest_button_down == down) return; @@ -2066,7 +2066,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) // - At this point we want from !down to down, so this is handling the initial press. if (ConfigMacOSXBehaviors && mouse_button == 0 && down) { - const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super); + const ImGuiInputEvent* latest_super_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super); if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper) { IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n"); @@ -2121,7 +2121,7 @@ void ImGuiIO::AddFocusEvent(bool focused) ImGuiContext& g = *Ctx; // Filter duplicate - const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus); + const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Focus); const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost; if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused)) return; diff --git a/imgui_internal.h b/imgui_internal.h index add0b8ce1..d679e48f9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3499,6 +3499,7 @@ namespace ImGui IMGUI_API void StopMouseMovingWindow(); IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); + IMGUI_API ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1); // Viewports inline ImGuiViewport* GetWindowViewport() { return GetMainViewport(); } // For code consistency. This is public API in docking branch. From c9a52f48e9e88b3fc920aae271e20290431b5357 Mon Sep 17 00:00:00 2001 From: Pascal Thomet Date: Mon, 9 Nov 2026 17:27:21 +0100 Subject: [PATCH 226/245] Backends: SDL2: on iOS, call SDL_StartTextInput()/SDL_StopTextInput() again. (#7636, #9474, #9617) --- backends/imgui_impl_sdl2.cpp | 9 +++++---- docs/CHANGELOG.txt | 7 +++++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index d5ba4dade..8281fa4ed 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,8 +21,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-11-09: Inputs: iOS: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support. (#7636, #9474, #9617) // 2026-08-06: Fixed querying framebuffer scale when using Metal. (#5592) -// 2026-07-15: Inputs: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support on Android/mobile. (#7636, #9474) +// 2026-07-15: Inputs: Android: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support. (#7636, #9474) // 2026-04-16: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return a minimum of 1.0f, as some Linux setup seems to report <1.0f value and this breaks scaling border size. (#9369) // 2026-02-13: Inputs: systems other than X11 are back to starting mouse capture on mouse down (reverts 2025-02-26 change). Only X11 requires waiting for a drag by default (not ideal, but a better default for X11 users). Added ImGui_ImplSDL2_SetMouseCaptureMode() for X11 debugger users. (#3650, #6410, #9235) // 2026-01-15: Changed GetClipboardText() handler to return nullptr on error aka clipboard contents is not text. Consistent with other backends. (#9168) @@ -216,15 +217,15 @@ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImG r.h = (int)data->InputLineHeight; SDL_SetTextInputRect(&r); -#ifdef __ANDROID__ - // SDL_StartTextInput() is needed on Android (and some other platforms) to show the on-screen keyboard. (#7636, #9474, #6306) +#if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) + // SDL_StartTextInput() is needed on Android and iOS to show the on-screen keyboard. (#7636, #9474, #6306) // It was removed in a7703fe6 due to concerns about its relation to desktop IME, but is required on mobile. SDL_StartTextInput(); #endif } else { -#ifdef __ANDROID__ +#if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) SDL_StopTextInput(); #endif } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f310858aa..5b15f168c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -114,8 +114,11 @@ Other Changes: - Examples: added support for ARM64 in selected build_win.bat helpers. (#9593) [@Harishmcw] - Backends: - GLFW, SDL2: Emscripten implementation of `Platform_OpenInShellFn` calls - `window.open()` with `noopener`: prevents newly opened tab from keeping a - reference to opening page. (#9615, #7660, #7851) [@pthom] + `window.open()` with `noopener`: prevents newly opened tab from keeping a + reference to opening page. (#9615, #7660, #7851) [@pthom] + - SDL2: on iOS, also restore calling `SDL_StartTextInput()/SDL_StopTextInput()` + in IME handler. Match Android change in 1.93.0. [@pthom] (#7636, #9474, #9617) + ----------------------------------------------------------------------- From c150bcee03ff1c134594aa872b1dda55a863471a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Nov 2026 16:57:14 +0100 Subject: [PATCH 227/245] Fonts: detect if the parameters leading AddFontDefault() to implicitly select either AddFontDefaultBitmap() or AddFontDefaultVector() have changed. (#9591) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 8 ++++++++ imgui_draw.cpp | 24 ++++++++++++++++-------- imgui_internal.h | 6 ++++-- 4 files changed, 32 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5b15f168c..bed8b58bf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -104,6 +104,10 @@ Other Changes: - ColorButton, ColorEdit, ColorPicker: fixed an issue rendering colors when inside a `BeginDisabled(false)` block, caused by the alpha cancelling-out code in 1.93.0. (#9511, #9613, #9614) [@tksuoran] +- Fonts: + - Detect if the parameters leading `AddFontDefault()` to implicitly select either + `AddFontDefaultBitmap()` or `AddFontDefaultVector()` have changed between init + time and first frame. (#9591) - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. diff --git a/imgui.cpp b/imgui.cpp index 10a13b56a..be3249748 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11259,6 +11259,14 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() if (g.IO.ConfigErrorRecovery) IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL); + // Detect if the parameters leading AddFontDefault() to implicitly select either AddFontDefaultBitmap() or AddFontDefaultVector() have changed. + if (g.FrameCount == 2 && g.IO.Fonts->Builder->LoadedFontDefaultAsVector != -1) + { + const bool old_heuristic_result_for_using_vector_font = (bool)g.IO.Fonts->Builder->LoadedFontDefaultAsVector; + const bool new_heuristic_result_for_using_vector_font = ImFontAtlasHeuristicShouldUseDefaultVectorFont(g.IO.Fonts); + IM_ASSERT_USER_ERROR(old_heuristic_result_for_using_vector_font == new_heuristic_result_for_using_vector_font, "AddFontDefault() font selection heuristic parameters changed between load/init time and now. Verify which parameters have changed or load a default font explicitly!"); + } + #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (g.IO.FontGlobalScale > 1.0f) IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c576e5018..59347e56f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -4363,7 +4363,10 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) ImFontAtlasFontSourceAddToFont(this, font, font_cfg); if (is_first_font) + { ImFontAtlasBuildNotifySetFont(this, NULL, font); + Builder->LoadedFontDefaultAsVector = -1; + } return font; } @@ -4389,13 +4392,17 @@ const char* ImGui_GetDefaultCompressedFontDataProggyForever(int* out_size); #endif // This duplicates some of the logic in UpdateFontsNewFrame() which is a bit chicken-and-eggy/tricky to extract due to variety of codepaths and possible initialization ordering. -static float GetExpectedContextFontSize(ImGuiContext* ctx) +bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas) { + ImGuiContext* ctx = atlas->OwnerContext; + if (ctx == NULL) + return true; float fb_scale = (ctx->IO.DisplayFramebufferScale.x != 0.0f) ? ctx->IO.DisplayFramebufferScale.x : 1.0f; if (ctx->IO.DisplayFramebufferScale.x == 1.0f && ctx->IO.DisplaySize.x <= 0.0f && ctx->IO.ConfigMacOSXBehaviors) - fb_scale = 2.0f; // If called before backend had a chance to init DisplayFramebufferScale. default to expecting Retina. - float scale = ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi * fb_scale; - return ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * scale; + fb_scale = 2.0f; // If called before backend had a chance to init DisplayFramebufferScale: default to expecting Retina on macOS/iOS. + const float scale = ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi * fb_scale; + const float expected_font_size = ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * scale; + return expected_font_size >= 15.0f; } // Legacy function with heuristic to select Pixel or Vector font. @@ -4403,10 +4410,11 @@ static float GetExpectedContextFontSize(ImGuiContext* ctx) // Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg) { - if (OwnerContext == NULL || GetExpectedContextFontSize(OwnerContext) >= 15.0f) - return AddFontDefaultVector(font_cfg); - else - return AddFontDefaultBitmap(font_cfg); + const bool use_vector_font = ImFontAtlasHeuristicShouldUseDefaultVectorFont(this); + ImFont* font = use_vector_font ? AddFontDefaultVector(font_cfg) : AddFontDefaultBitmap(font_cfg); + if (Fonts.Size == 1) + Builder->LoadedFontDefaultAsVector = use_vector_font ? 1 : 0; + return font; } // Load embedded ProggyClean.ttf. Default size 13, disable oversampling. diff --git a/imgui_internal.h b/imgui_internal.h index d679e48f9..1bb0ebcd6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -4086,7 +4086,8 @@ struct ImFontAtlasBuilder ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size") ImVec2i MaxRectBounds; // Bottom-right most used pixels bool LockDisableResize; // Disable resizing texture - bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. + bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. + ImS8 LoadedFontDefaultAsVector; // -1, or record with 0/1 whereas AddFontDefault() picked bitmap or vector font. // Cache of all ImFontBaked ImStableVector BakedPool; @@ -4103,7 +4104,7 @@ struct ImFontAtlasBuilder ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT]; // UVs for baked anti-aliased lines (u0, u1, v, 1/thickness) ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) - ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } + ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; LoadedFontDefaultAsVector = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } }; IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); @@ -4158,6 +4159,7 @@ IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas); +IMGUI_API bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); From 4cb4b17cb5db3d9c581c4c5d539802303e7e9777 Mon Sep 17 00:00:00 2001 From: sarpsenturk Date: Wed, 23 Sep 2026 23:15:57 +0300 Subject: [PATCH 228/245] Backends: Vulkan: don't transition swapchain images before acquire. (#9553, #9496) cc #9152 --- backends/imgui_impl_vulkan.cpp | 77 +--------------------------------- docs/CHANGELOG.txt | 3 ++ 2 files changed, 5 insertions(+), 75 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 7017a6fd1..f44581030 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,6 +27,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-11-10: Don't transition swapchain images from VK_IMAGE_LAYOUT_UNDEFINED to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in examples and multi-viewport support. (#9553, #9496) // 2026-10-06: Added support for dynamic rendering with multiple color attachments (PipelineRenderingCreateInfo.colorAttachmentCount > 1): we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-09-03: Added for support for multiple Vulkan contexts with custom loaders. (#6616) @@ -1918,6 +1919,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V // Create or resize window // - 2025/09/26: v1.92.4 added a trailing 'VkImageUsageFlags image_usage' parameter which is usually VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT. +// - 2026/11/10: v1.93.1 removed a bunch of code transitioning swapchain image layout from `VK_IMAGE_LAYOUT_UNDEFINED` to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`. (#9496) void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count, VkImageUsageFlags image_usage) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); @@ -1926,81 +1928,6 @@ void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevic ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count, image_usage); ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); - - // FIXME: to submit the command buffer, we need a queue. In the examples folder, the ImGui_ImplVulkanH_CreateOrResizeWindow function is called - // before the ImGui_ImplVulkan_Init function, so we don't have access to the queue yet. Here we have the queue_family that we can use to grab - // a queue from the device and submit the command buffer. It would be better to have access to the queue as suggested in the FIXME below. - VkCommandPool command_pool; - VkCommandPoolCreateInfo pool_info = {}; - pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - pool_info.queueFamilyIndex = queue_family; - VkResult err = vkCreateCommandPool(device, &pool_info, allocator, &command_pool); - check_vk_result(err); - - VkFenceCreateInfo fence_info = {}; - fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; - VkFence fence; - err = vkCreateFence(device, &fence_info, allocator, &fence); - check_vk_result(err); - - VkCommandBufferAllocateInfo alloc_info = {}; - alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; - alloc_info.commandPool = command_pool; - alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - alloc_info.commandBufferCount = 1; - VkCommandBuffer command_buffer; - err = vkAllocateCommandBuffers(device, &alloc_info, &command_buffer); - check_vk_result(err); - - VkCommandBufferBeginInfo begin_info = {}; - begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - err = vkBeginCommandBuffer(command_buffer, &begin_info); - check_vk_result(err); - - // Transition the images to the correct layout for rendering - for (uint32_t i = 0; i < wd->ImageCount; i++) - { - VkImageMemoryBarrier barrier = {}; - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.image = wd->Frames[i].Backbuffer; - barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - barrier.subresourceRange.levelCount = 1; - barrier.subresourceRange.layerCount = 1; - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); - } - - err = vkEndCommandBuffer(command_buffer); - check_vk_result(err); - VkSubmitInfo submit_info = {}; - submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - submit_info.commandBufferCount = 1; - submit_info.pCommandBuffers = &command_buffer; - - VkQueue queue; - vkGetDeviceQueue(device, queue_family, 0, &queue); - err = vkQueueSubmit(queue, 1, &submit_info, fence); - check_vk_result(err); - err = vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX); - check_vk_result(err); - err = vkResetFences(device, 1, &fence); - check_vk_result(err); - - err = vkResetCommandPool(device, command_pool, 0); - check_vk_result(err); - - // Destroy command buffer and fence and command pool - vkFreeCommandBuffers(device, command_pool, 1, &command_buffer); - vkDestroyCommandPool(device, command_pool, allocator); - vkDestroyFence(device, fence, allocator); - command_pool = VK_NULL_HANDLE; - command_buffer = VK_NULL_HANDLE; - fence = VK_NULL_HANDLE; - queue = VK_NULL_HANDLE; } void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bed8b58bf..12ebcac84 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -122,6 +122,9 @@ Other Changes: reference to opening page. (#9615, #7660, #7851) [@pthom] - SDL2: on iOS, also restore calling `SDL_StartTextInput()/SDL_StopTextInput()` in IME handler. Match Android change in 1.93.0. [@pthom] (#7636, #9474, #9617) + - Vulkan: don't transition swapchain images from `VK_IMAGE_LAYOUT_UNDEFINED` to + `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in + examples and multi-viewport support. (#9553, #9496, #9152) [@sarpsenturk, @LewisJustin] From 1dc17c426bc1f458bf0db95df30c33f9b94a4f21 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 30 Aug 2026 20:59:44 +0200 Subject: [PATCH 229/245] Tables: minor: refactor use TableInitColumnDefaults() in TableApplyQueuedRequests() for consistency. --- imgui_tables.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f7a39f689..363e36806 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -708,7 +708,7 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) // Handle display order / visibility reset requests if (table->IsResetDisplayOrderRequest) { - for (int n = 0; n < table->ColumnsCount; n++) + for (int n = 0; n < table->ColumnsCount; n++) // Variant of using TableInitColumnDefaults()( table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n; table->IsResetDisplayOrderRequest = false; table->IsSettingsDirty = true; @@ -716,7 +716,7 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) if (table->IsResetVisibilityRequest) { for (ImGuiTableColumn& column : table->Columns) - column.IsUserEnabled = column.IsUserEnabledNextFrame = (column.Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; + TableInitColumnDefaults(table, &column, ImGuiTableFlags_Hideable); table->IsResetVisibilityRequest = false; table->IsSettingsDirty = true; } @@ -1685,7 +1685,7 @@ void ImGui::TableInitColumnDefaults(ImGuiTable* table, ImGuiTableColumn* column, if (init_mask & ImGuiTableFlags_Resizable) { float init_width_or_weight = column->InitStretchWeightOrWidth; - column->WidthRequest = ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f; + column->WidthRequest = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthFixed)) ? init_width_or_weight : -1.0f; column->StretchWeight = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthStretch)) ? init_width_or_weight : -1.0f; if (init_width_or_weight > 0.0f) // Disable auto-fit if an explicit width/weight has been specified column->AutoFitQueue = 0x00; From ac3b6c34e3f7a9020afac7bb0f326f2395e57352 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Nov 2026 18:42:09 +0100 Subject: [PATCH 230/245] Tables: added "Reset->Reset Sizes" context-menu option. Rename mixed sizing policy entry"Size all columns to auto". (#9523, #9605) Amend Demo->Columns Widths to showcase. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 3 ++- imgui.h | 2 +- imgui_demo.cpp | 30 +++++++++++++++++++++--------- imgui_internal.h | 2 ++ imgui_tables.cpp | 15 +++++++++++++-- 6 files changed, 40 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 12ebcac84..b311df197 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -82,6 +82,7 @@ Other Changes: - Modals: fixed an assert displaying a modal in an environment where `io.DisplayFramebufferScale` is not an integer (regression in 1.93.0). (#9598) - Tables: + - Added "Reset->Reset Sizes" context-menu option. (#9523, #9605) - Fixed various border overshooting issues, some mostly visible with transparent borders and under specific conditions: (#4678) - On non-scrolling tables, inner horizontal borders slightly overlapped diff --git a/imgui.cpp b/imgui.cpp index be3249748..e2aea63d4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4305,11 +4305,12 @@ static const ImGuiLocEntry GLocalizationEntriesEnUS[] = { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" }, { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" }, { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" }, - { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" }, + { ImGuiLocKey_TableSizeAllDefault, "Size all columns to auto###SizeAll" }, { ImGuiLocKey_TableReset, "Reset" }, //{ ImGuiLocKey_TableResetAll, "Reset to default###ResetAll" }, { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" }, { ImGuiLocKey_TableResetVisibility, "Reset visibility###ResetVisibility" }, + { ImGuiLocKey_TableResetSizing, "Reset sizing###ResetSizing" }, { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" }, { ImGuiLocKey_WindowingPopup, "(Popup)" }, { ImGuiLocKey_WindowingUntitled, "(Untitled)" }, diff --git a/imgui.h b/imgui.h index 9a2313a59..69e061c34 100644 --- a/imgui.h +++ b/imgui.h @@ -30,7 +30,7 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.93.1 WIP" -#define IMGUI_VERSION_NUM 19302 +#define IMGUI_VERSION_NUM 19303 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4a9753a89..8d27c9f3f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -6796,19 +6796,20 @@ static void DemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize); PopStyleCompact(); - if (ImGui::BeginTable("table1", 3, flags1)) + if (ImGui::BeginTable("table1", 4, flags1)) { - // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. + // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed if not specified. ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f ImGui::TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); // Default to auto + ImGui::TableSetupColumn("four", ImGuiTableColumnFlags_WidthStretch); // Default to remaining width ImGui::TableHeadersRow(); for (int row = 0; row < 4; row++) { ImGui::TableNextRow(); - for (int column = 0; column < 3; column++) + for (int column = 0; column < 4; column++) { - ImGui::TableSetColumnIndex(column); + ImGui::TableNextColumn(); if (row == 0) ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x); else @@ -6817,18 +6818,29 @@ static void DemoWindowTables() } ImGui::EndTable(); } + if (ImGui::BeginTable("table2", 2, flags1)) + { + // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. + ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthStretch, 1.0f); // Default weight + ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default weight + ImGui::TableHeadersRow(); + for (int column = 0; column < 2; column++) + if (ImGui::TableNextColumn()) + ImGui::Text("Default weight %d%%", (column & 1) ? 200 : 100); + ImGui::EndTable(); + } HelpMarker( "Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, " "fixed columns with set width may still be shrunk down if there's not enough space in the host."); - static ImGuiTableFlags flags2 = ImGuiTableFlags_None; + static ImGuiTableFlags flags3 = ImGuiTableFlags_None; PushStyleCompact(); - ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags2, ImGuiTableFlags_NoKeepColumnsVisible); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags2, ImGuiTableFlags_BordersInnerV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags2, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags3, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags3, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags3, ImGuiTableFlags_BordersOuterV); PopStyleCompact(); - if (ImGui::BeginTable("table2", 4, flags2)) + if (ImGui::BeginTable("table3", 4, flags3)) { // We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns // will default to ImGuiTableColumnFlags_WidthFixed. diff --git a/imgui_internal.h b/imgui_internal.h index 1bb0ebcd6..fc1d4582c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2161,6 +2161,7 @@ enum ImGuiLocKey : int //ImGuiLocKey_TableResetAll, ImGuiLocKey_TableResetOrder, ImGuiLocKey_TableResetVisibility, + ImGuiLocKey_TableResetSizing, ImGuiLocKey_WindowingMainMenuBar, ImGuiLocKey_WindowingPopup, ImGuiLocKey_WindowingUntitled, @@ -3241,6 +3242,7 @@ struct IMGUI_API ImGuiTable bool IsResetAllRequest; // Set to queue a call to TableResetSettings() in BeginTable() bool IsResetDisplayOrderRequest; bool IsResetVisibilityRequest; + bool IsResetSizesRequest; bool IsUnfrozenRows; // Set when we got past the frozen row. bool IsDefaultSizingPolicy; // Set if user didn't explicitly set a sizing policy in BeginTable() bool IsActiveIdAliveBeforeTable; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 363e36806..45d596f60 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -705,7 +705,7 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) // table->ReorderColumn = -1; } - // Handle display order / visibility reset requests + // Handle reset requests (display order / visibility / sizes) if (table->IsResetDisplayOrderRequest) { for (int n = 0; n < table->ColumnsCount; n++) // Variant of using TableInitColumnDefaults()( @@ -720,6 +720,13 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) table->IsResetVisibilityRequest = false; table->IsSettingsDirty = true; } + if (table->IsResetSizesRequest) + { + for (ImGuiTableColumn& column : table->Columns) + TableInitColumnDefaults(table, &column, ImGuiTableFlags_Resizable); + table->IsResetSizesRequest = false; + table->IsSettingsDirty = true; + } } // Apply immediately. See TableQueueSetColumnDisplayOrder() for additional checks/constraints. @@ -2568,6 +2575,7 @@ void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n) table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n; } +// FIXME: AutoFitQueue for Stretch columns can do a "reset" if InitStretchWeightOrWidth is valid, therefore might be misnamed. void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table) { for (int column_n = 0; column_n < table->ColumnsCount; column_n++) @@ -3759,7 +3767,7 @@ void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags } // Reset Order/Visibility etc. - if (flags_for_section_to_display & (ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + if (flags_for_section_to_display & (ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Resizable)) if (BeginMenu(LocalizeGetMsg(ImGuiLocKey_TableReset))) { //if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetAll))) // FIXME: Hiding because altering Sort Order + requesting auto-fit simultaneously has a tendency to exhibit a sizing glitch. @@ -3770,6 +3778,9 @@ void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags if (flags_for_section_to_display & ImGuiTableFlags_Hideable) if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetVisibility), NULL, false, !table->IsDefaultVisibility)) table->IsResetVisibilityRequest = true; + if (flags_for_section_to_display & ImGuiTableFlags_Resizable) + if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetSizing), NULL, false)) // Can't easily implement IsDefaultSize + table->IsResetSizesRequest = true; EndMenu(); } From d3b36a875f0f7e7446b99606ca3d6df27b7dad7a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 10 Nov 2026 19:56:06 +0100 Subject: [PATCH 231/245] Backends: Vulkan: ImGui_ImplVulkanH_SelectSurfaceFormat() removed unnecessary check for VK_FORMAT_UNDEFINED. (#7830) Amend 33874073dc (#1042) --- backends/imgui_impl_vulkan.cpp | 26 ++++---------------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index f44581030..cf4d53537 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1594,33 +1594,15 @@ VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physic avail_format.resize((int)avail_count); vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data); - // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available - if (avail_count == 1) - { - if (avail_format[0].format == VK_FORMAT_UNDEFINED) - { - VkSurfaceFormatKHR ret; - ret.format = request_formats[0]; - ret.colorSpace = request_color_space; - return ret; - } - else - { - // No point in searching another format - return avail_format[0]; - } - } - else - { - // Request several formats, the first found will be used + // When requesting several formats, the first found will be used + if (avail_count > 1) for (int request_i = 0; request_i < request_formats_count; request_i++) for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space) return avail_format[avail_i]; - // If none of the requested image formats could be found, use the first available - return avail_format[0]; - } + // If none of the requested image formats could be found, use the first available + return avail_format[0]; } VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count) From 0300d9eb0e8104d84ea606ba2d117dbcf1ffd75b Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Nov 2026 15:00:31 +0100 Subject: [PATCH 232/245] Backends: GLFW: allow initialization with missing HWND. (#9619) --- backends/imgui_impl_glfw.cpp | 21 +++++++++++++-------- docs/CHANGELOG.txt | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 2be125300..9cbffafb6 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -748,11 +748,13 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 - HWND hwnd = (HWND)main_viewport->PlatformHandleRaw; - ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd); - bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); - IM_ASSERT(bd->PrevWndProc != nullptr); - ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); + if (HWND hwnd = (HWND)main_viewport->PlatformHandleRaw) + { + ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd); + bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); + IM_ASSERT(bd->PrevWndProc != nullptr); + ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); + } #endif // Emscripten: the same application can run on various platforms, so we detect the Apple platform at runtime @@ -812,9 +814,12 @@ void ImGui_ImplGlfw_Shutdown() // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_BACKEND_DATA", nullptr); - ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); - bd->PrevWndProc = nullptr; + if (HWND hwnd = (HWND)main_viewport->PlatformHandleRaw) + { + ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", nullptr); + ::SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); + bd->PrevWndProc = nullptr; + } #endif io.BackendPlatformName = nullptr; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b311df197..051d45854 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,7 +63,6 @@ Autumn cleanup of stuff marked obsolete more than two years ago: and `GetWindowContentRegionMax()` will may be removed soon-ish: you should not ever need those functions. See #7838. - Other Changes: - Style: @@ -118,6 +117,7 @@ Other Changes: Made the script detect the environment when needed (e.g. to specify library path). - Examples: added support for ARM64 in selected build_win.bat helpers. (#9593) [@Harishmcw] - Backends: + - GLFW: allow initialization with missing HWND. (#9619) [@djohansson] - GLFW, SDL2: Emscripten implementation of `Platform_OpenInShellFn` calls `window.open()` with `noopener`: prevents newly opened tab from keeping a reference to opening page. (#9615, #7660, #7851) [@pthom] From d4c45226739efd7649725404c26226230561fd3c Mon Sep 17 00:00:00 2001 From: thedmd Date: Fri, 16 Oct 2026 22:48:02 +0200 Subject: [PATCH 233/245] Tables: fixed table submitted while in horizontal layout mode (e.g. a menu bar). (#9589) Items in cells used the layout type of the host window, so each ItemSize() in a cell ended with SameLine(). BeginTable() now sets a vertical layout until EndTable(). Tables with their own child window were not affected. --- imgui_internal.h | 1 + imgui_tables.cpp | 3 +++ 2 files changed, 4 insertions(+) diff --git a/imgui_internal.h b/imgui_internal.h index fc1d4582c..9ab5bea1d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -3286,6 +3286,7 @@ struct IMGUI_API ImGuiTableTempData ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable() float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable() int HostBackupItemWidthStackSize;//Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable() + ImGuiLayoutType HostBackupLayoutType; // Backup of InnerWindow->DC.LayoutType at the end of BeginTable() ImGuiTableTempData() { memset((void*)this, 0, sizeof(*this)); LastTimeActive = -1.0f; } }; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 45d596f60..820b4dde4 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -476,7 +476,9 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos; temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth; temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size; + temp_data->HostBackupLayoutType = inner_window->DC.LayoutType; inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + inner_window->DC.LayoutType = ImGuiLayoutType_Vertical; // Border size // FIXME-WIP: Changing this is not currently simple due to ClipRect requirements. Easier to manage with new 1.93 primitives though. @@ -1493,6 +1495,7 @@ void ImGui::EndTable() // Finalize table height ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize; + inner_window->DC.LayoutType = temp_data->HostBackupLayoutType; inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize; inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos; const float inner_content_max_y = ImCeil(table->RowPosY2); // Rounding final position is important as we currently don't round row height ('Demo->Tables->Outer Size' demo uses non-integer heights) From abaca051e8799037e5b57d007fe35827422057ad Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Nov 2026 15:36:21 +0100 Subject: [PATCH 234/245] Tables: fixed table submitted while in horizontal layout mode (e.g. a menu bar). Amend. (#9589) --- docs/CHANGELOG.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 051d45854..dc204937a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -93,6 +93,8 @@ Other Changes: - Fixed selectable highlight straying off the X2/Y2 clipping limit. - Fixed parent window work rectangle affecting the Y2 clipping limit. - Fixed the Y2 clipping limit overlapping bottom outer border. + - Fixed layout of items submitted while in horizontal layout mode (e.g. a menu bar). + `BeginTable()` resets layout mode to vertical. (#9589) [@themd] - Multi-Select: - Fixed `ImGuiSelectionBasicStorage::GetNextSelectedItem()` reading one past the end of storage when trailing items are unselected (#9604) [@MilosLord] From 98e113e10b9694710d06b2124835902d04662705 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2026 19:56:13 +0200 Subject: [PATCH 235/245] Text: shallow tweaks. --- imgui.cpp | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e2aea63d4..3e6549e30 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4007,13 +4007,12 @@ void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls) text_display_end = text_end; } + if (text == text_display_end) + return; - if (text != text_display_end) - { - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_display_end); - } + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_display_end); } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) @@ -4023,13 +4022,12 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end if (!text_end) text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls) + if (text == text_end) + return; - if (text != text_end) - { - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_end); - } + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_end); } // Default clip_rect uses (pos_min,pos_max) @@ -4037,12 +4035,15 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end // FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList. // Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take // better advantage of the render function taking size into account for coarse clipping. -void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) // DOES NOT CALL LogRenderedText(), unlike RenderTextClipped!!! +void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { + if (text == text_end) + return; + // Perform CPU side clipping for single clipped element to avoid using scissor state ImVec2 pos = pos_min; - const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end, false, 0.0f); const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; @@ -4051,18 +4052,20 @@ void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, co need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. - if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); - if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + if (align.x > 0.0f) + pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) + pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); // Render if (need_clipping) { ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); - draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_end, 0.0f, &fine_clip_rect); } else { - draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_end, 0.0f, NULL); } } From 9fb6f2d8bc81ec7600fad8c9a8f26306c8e36fd0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Nov 2026 22:12:09 +0100 Subject: [PATCH 236/245] stb: update stb_rect_pack.h 1.01 > 1.02 --- docs/CHANGELOG.txt | 2 ++ imstb_rectpack.h | 9 +++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dc204937a..41acd9c1c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -113,6 +113,8 @@ Other Changes: - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. +- Misc: update stb_rect_pack 1.01->1.02 (fixed packing determinism by not + depending on qsort() tiebreak). - CI: added some ARM64 builds. (#9593) [@Harishmcw] - Examples: renamed various helper batch files from build_win32.bat to build_win.bat to reflect that they can also build X64 or ARM64, given the right environment. diff --git a/imstb_rectpack.h b/imstb_rectpack.h index ad0892130..a80217382 100644 --- a/imstb_rectpack.h +++ b/imstb_rectpack.h @@ -2,7 +2,7 @@ // This is a slightly modified version of stb_rect_pack.h 1.01. // Grep for [DEAR IMGUI] to find the changes. // -// stb_rect_pack.h - v1.01 - public domain - rectangle packing +// stb_rect_pack.h - v1.02 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -42,6 +42,7 @@ // Bugfixes / warning fixes // Jeremy Jaussaud // Fabian Giesen +// Joshua Simmons // // Version history: // @@ -533,7 +534,11 @@ static int STBRP__CDECL rect_height_compare(const void *a, const void *b) return -1; if (p->h < q->h) return 1; - return (p->w > q->w) ? -1 : (p->w < q->w); + if (p->w > q->w) + return -1; + if (p->w < q->w) + return 1; + return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); } static int STBRP__CDECL rect_original_order(const void *a, const void *b) From 8527c8a63be0791c2c5248b34354bc1c720726cf Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Nov 2026 23:15:29 +0100 Subject: [PATCH 237/245] stb: update stb_textedit 1.14 -> 1.15, preserving our UTF-8 and word wrapping related changes. --- docs/CHANGELOG.txt | 5 +++ imgui_draw.cpp | 2 +- imgui_widgets.cpp | 4 +++ imstb_textedit.h | 82 ++++++++++++++++++++++++++-------------------- 4 files changed, 57 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 41acd9c1c..ba1f7555c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,6 +95,9 @@ Other Changes: - Fixed the Y2 clipping limit overlapping bottom outer border. - Fixed layout of items submitted while in horizontal layout mode (e.g. a menu bar). `BeginTable()` resets layout mode to vertical. (#9589) [@themd] +- InputText: + - Up/PageUp on the first line now moves the cursor to the beginning + of the line, including when extending a selection. [@blackedout01] - Multi-Select: - Fixed `ImGuiSelectionBasicStorage::GetNextSelectedItem()` reading one past the end of storage when trailing items are unselected (#9604) [@MilosLord] @@ -113,6 +116,8 @@ Other Changes: - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. +- Misc: update stb_textedit 1.14->1.15, preserving UTF-8 and word-wrapping support. + (#6000, #6783, #7925, #3237) - Misc: update stb_rect_pack 1.01->1.02 (fixed packing determinism by not depending on qsort() tiebreak). - CI: added some ARM64 builds. (#9593) [@Harishmcw] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 59347e56f..7b2b7138d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -62,6 +62,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier @@ -112,7 +113,6 @@ namespace IMGUI_STB_NAMESPACE #if defined(__clang__) #pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #endif diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3d3d1f008..2ea056a53 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -54,6 +54,7 @@ Index of this file: // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types @@ -73,6 +74,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. @@ -84,6 +86,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*' #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked @@ -4351,6 +4354,7 @@ static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const cha #define IMSTB_TEXTEDIT_IMPLEMENTATION #define IMSTB_TEXTEDIT_memmove memmove + #include "imstb_textedit.h" // stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling diff --git a/imstb_textedit.h b/imstb_textedit.h index 583508f0b..1fbccba58 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -1,15 +1,15 @@ // [DEAR IMGUI] -// This is a slightly modified version of stb_textedit.h 1.14. +// This is a slightly modified version of stb_textedit.h 1.15. // Those changes would need to be pushed into nothings/stb: // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) -// - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) +// - Added line movement hooks and cursor-side tracking for word-wrapping. // - Added name to struct or it may be forward declared in our code. // - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) // - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. // Grep for [DEAR IMGUI] to find some changes. // - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* -// stb_textedit.h - v1.14 - public domain - Sean Barrett +// stb_textedit.h - v1.15 - public domain - Sean Barrett // Development of this library was sponsored by RAD Game Tools // // This C header file implements the guts of a multi-line text-editing @@ -41,6 +41,7 @@ // VERSION HISTORY // // !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +// 1.15 (2026-11-08) various fixes // 1.14 (2021-07-11) page up/down, various fixes // 1.13 (2019-02-07) fix bug in undo size management // 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash @@ -221,8 +222,9 @@ // void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) // int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) // int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) -// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) +// void stb_textedit_char(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE ch) // void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) +// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) // // Each of these functions potentially updates the string and updates the // state. @@ -249,6 +251,18 @@ // call this to paste text at the current cursor point or over the current // selection if there is one. // +// char: +// (optional) call this for character input sent to the textfield. if the +// framework you are using supplies you with a character or text event, it +// makes sense to use this function. +// make sure to set STB_TEXTEDIT_KEYTOTEXT to 0 for any key that generates +// a corresponding character or text event. +// +// text: +// (optional) call this to directly send text input the textfield, which is required +// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() +// cannot infer text length. +// // key: // call this for keyboard inputs sent to the textfield. you can use it // for "key down" events or for "translated" key events. if you need to @@ -261,11 +275,6 @@ // if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are // transformed into text and stb_textedit_text() is automatically called. // -// text: (added 2025) -// call this to directly send text input the textfield, which is required -// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() -// cannot infer text length. -// // // When rendering, you can read the cursor position and selection state from // the STB_TexteditState. @@ -567,36 +576,25 @@ static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING int z = STB_TEXTEDIT_STRINGLEN(str); int i=0, first; - if (n == z && single_line) { - // special case if it's at the end (may not be needed?) - STB_TEXTEDIT_LAYOUTROW(&r, str, 0); - find->y = 0; - find->first_char = 0; - find->length = z; - find->height = r.ymax - r.ymin; - find->x = r.x1; - return; - } - // search rows to find the one that straddles character n find->y = 0; for(;;) { STB_TEXTEDIT_LAYOUTROW(&r, str, i); - if (n < i + r.num_chars) - break; - if (str->LastMoveDirectionLR == ImGuiDir_Right && str->Stb->cursor > 0 && str->Stb->cursor == i + r.num_chars && STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] Wrapping point handling - break; - if (i + r.num_chars == z && z > 0 && STB_TEXTEDIT_GETCHAR(str, z - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] special handling for last line - break; // [DEAR IMGUI] + + // Use the regular layout scan for EOF, including an empty final row. + // [DEAR IMGUI] At a soft-wrap boundary, the cursor side determines the row. + // A row without a newline is not necessarily the last row when word-wrapping. + if (n <= i + r.num_chars) { + if (n < i + r.num_chars || r.num_chars == 0 || single_line) + break; + if (STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE && (n == z || str->LastMoveDirectionLR == ImGuiDir_Right)) + break; + } + prev_start = i; i += r.num_chars; find->y += r.baseline_y_delta; - if (i == z) // [DEAR IMGUI] - { - r.num_chars = 0; // [DEAR IMGUI] - break; // [DEAR IMGUI] - } } find->first_char = first = i; @@ -798,7 +796,7 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) { // can't add newline in single-line mode - if (text[0] == '\n' && state->single_line) + if (text[0] == STB_TEXTEDIT_NEWLINE && state->single_line) return; if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { @@ -820,6 +818,12 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta } } +// API char: process a character input (not suitable for UTF-8 codepoints). +static void stb_textedit_char(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE ch) +{ + stb_textedit_text(str, state, &ch, 1); +} + // API key: process a keyboard input static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) { @@ -831,7 +835,7 @@ retry: int c = STB_TEXTEDIT_KEYTOTEXT(key); if (c > 0) { IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c; - stb_textedit_text(str, state, &ch, 1); + stb_textedit_char(str, state, ch); } #endif break; @@ -1033,9 +1037,15 @@ retry: for (j = 0; j < row_count; ++j) { float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; - // can only go up if there's a previous row - if (find.prev_first == find.first_char) + // if there's no previous row set cursor to start of the line + if (find.prev_first == find.first_char) { + state->cursor = find.first_char; + stb_textedit_clamp(str, state); + + if (sel) + state->select_end = state->cursor; break; + } // now find character position up a row state->cursor = find.prev_first; @@ -1363,6 +1373,7 @@ static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) } state->cursor = u.where + u.insert_length; + state->select_start = state->select_end = state->cursor; s->undo_point--; s->redo_point--; @@ -1414,6 +1425,7 @@ static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) } state->cursor = r.where + r.insert_length; + state->select_start = state->select_end = state->cursor; s->undo_point++; s->redo_point++; From 3c39cda2d3a48df391a8f6839bf020c103957834 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Nov 2026 23:24:25 +0100 Subject: [PATCH 238/245] stb: update stb_truetype 1.26 -> 1.27. --- docs/CHANGELOG.txt | 16 +- imgui_widgets.cpp | 3 +- imstb_truetype.h | 362 +++++++++++++++++++++++++++++++++++++-------- 3 files changed, 312 insertions(+), 69 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ba1f7555c..b62333dac 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,9 +95,6 @@ Other Changes: - Fixed the Y2 clipping limit overlapping bottom outer border. - Fixed layout of items submitted while in horizontal layout mode (e.g. a menu bar). `BeginTable()` resets layout mode to vertical. (#9589) [@themd] -- InputText: - - Up/PageUp on the first line now moves the cursor to the beginning - of the line, including when extending a selection. [@blackedout01] - Multi-Select: - Fixed `ImGuiSelectionBasicStorage::GetNextSelectedItem()` reading one past the end of storage when trailing items are unselected (#9604) [@MilosLord] @@ -116,10 +113,15 @@ Other Changes: - ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro adds an extra `operator=` to ImVec2. This isn't supported but should not be needed as you should have a constructor to convert from your type to ImVec2. -- Misc: update stb_textedit 1.14->1.15, preserving UTF-8 and word-wrapping support. - (#6000, #6783, #7925, #3237) -- Misc: update stb_rect_pack 1.01->1.02 (fixed packing determinism by not - depending on qsort() tiebreak). +- Misc: update stb_textedit 1.14->1.15. + - InputText: Up/PageUp on the first line now moves the cursor to the beginning + of the line, including when extending a selection. [@blackedout01] +- Misc: update stb_truetype 1.26->1.27. + - Fonts: fixed incorrect glyph mapping with certain character maps, loading fonts + with only a Microsoft Symbol character map, and rendering scaled composite glyphs. + - Fixed an out-of-bounds read with single-point off-curve contours. +- Misc: update stb_rect_pack 1.01->1.02. + - Fixed packing determinism by not depending on qsort() tiebreak. - CI: added some ARM64 builds. (#9593) [@Harishmcw] - Examples: renamed various helper batch files from build_win32.bat to build_win.bat to reflect that they can also build X64 or ARM64, given the right environment. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ea056a53..f54a91160 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1564,8 +1564,9 @@ bool ImGui::TextLink(const char* label) ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); } + // FIXME-TEXT FIXME-DPI: Underline mode. Note how stb_truetype now expose stbtt_GetFontUnderlineMetrics(). float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f); - window->DrawList->AddLineH(bb.Min.x, bb.Max.x, line_y, GetColorU32(line_colf), 1.0f * (float)(int)g.Style._MainScale); // FIXME-TEXT: Underline mode // FIXME-DPI + window->DrawList->AddLineH(bb.Min.x, bb.Max.x, line_y, GetColorU32(line_colf), 1.0f * (float)(int)g.Style._MainScale); PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); RenderText(bb.Min, label, label_end, false); diff --git a/imstb_truetype.h b/imstb_truetype.h index ec4d42c7d..0bc602f6c 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -1,9 +1,9 @@ // [DEAR IMGUI] -// This is a slightly modified version of stb_truetype.h 1.26. +// This is a slightly modified version of stb_truetype.h 1.27. // Mostly fixing for compiler and static analyzer warnings. // Grep for [DEAR IMGUI] to find the changes. -// stb_truetype.h - v1.26 - public domain +// stb_truetype.h - v1.27 - public domain // authored from 2009-2021 by Sean Barrett / RAD Game Tools // // ======================================================================= @@ -50,7 +50,7 @@ // Cass Everitt Martins Mozeiko github:aloucks // stoiko (Haemimont Games) Cap Petschulat github:oyvindjam // Brian Hook Omar Cornut github:vassvik -// Walter van Niftrik Ryan Griege +// Walter van Niftrik Ryan Griege github:Cerallin // David Gow Peter LaValle // David Given Sergey Popov // Ivan-Assen Ivanov Giumo X. Clanjor @@ -59,10 +59,13 @@ // Hou Qiming Derek Vinyard // Rob Loach Cort Stratton // Kenney Phillis Jr. Brian Costabile -// Ken Voskuil (kaesve) +// Ken Voskuil (kaesve) Yakov Galka +// Neil Bickford Matthias Dorfelt +// Isaac "Atridas" Serrano // // VERSION HISTORY // +// 1.27 (2026-11-08) many fixes, support vertical layout, underlines, font name // 1.26 (2021-08-28) fix broken rasterizer // 1.25 (2021-07-11) many fixes // 1.24 (2020-02-05) fix warning @@ -206,10 +209,10 @@ // Baseline: // You need to select a y-coordinate that is the baseline of where // your text will appear. Call GetFontBoundingBox to get the baseline-relative -// bounding box for all characters. SF*-y0 will be the distance in pixels +// bounding box for all characters. SF*y1 will be the distance in pixels // that the worst-case character could extend above the baseline, so if // you want the top edge of characters to appear at the top of the -// screen where y=0, then you would set the baseline to SF*-y0. +// screen where y=0, then you would set the baseline to SF*y1. // // Current point: // Set the current point where the first character will appear. The @@ -220,10 +223,10 @@ // the current point based on that. // // Displaying a character: -// Compute the bounding box of the character. It will contain signed values -// relative to . I.e. if it returns x0,y0,x1,y1, -// then the character should be displayed in the rectangle from -// to . I.e. if it returns x0,y0, +// x1,y1, then the character should be displayed in the rectangle from +// to . // // Advancing for the next character: // Call GlyphHMetrics, and compute 'current_point += SF * advance'. @@ -235,10 +238,10 @@ // // - Use the functions with Subpixel at the end to allow your characters // to have subpixel positioning. Since the font is anti-aliased, not -// hinted, this is very import for quality. (This is not possible with +// hinted, this is very important for quality. (This is not possible with // baked fonts.) // -// - Kerning is now supported, and if you're supporting subpixel rendering +// - Kerning is supported, and if you're supporting subpixel rendering // then kerning is worth using to give your text a polished look. // // Performance: @@ -327,7 +330,7 @@ void my_stbtt_print(float x, float y, char *text) // ////////////////////////////////////////////////////////////////////////////// // -// Complete program (this compiles): get a single bitmap, print as ASCII art +// Compilable program (does no cleanup): get a single bitmap, print as ASCII art // #if 0 #include @@ -342,10 +345,10 @@ int main(int argc, char **argv) unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); - fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); // fclose() omitted for clarity stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); - bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); // stbtt_FreeBitmap() omitted for clarity for (j=0; j < h; ++j) { for (i=0; i < w; ++i) @@ -371,7 +374,7 @@ int main(int argc, char **argv) // ////////////////////////////////////////////////////////////////////////////// // -// Complete program: print "Hello World!" banner, with bugs +// Complete program: print "Hello World!" banner, with bugs & no cleanup // #if 0 char buffer[24<<20]; @@ -625,7 +628,7 @@ typedef struct { float font_size; int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint - int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + const int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints int num_chars; stbtt_packedchar *chardata_for_range; // output unsigned char h_oversample, v_oversample; // don't set these, they're used internally @@ -723,7 +726,7 @@ struct stbtt_fontinfo int numGlyphs; // number of glyphs, needed for range checking - int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf + int loca,head,glyf,hhea,hmtx,vhea,vmtx,kern,gpos,svg; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph @@ -745,7 +748,7 @@ STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, in ////////////////////////////////////////////////////////////////////////////// // -// CHARACTER TO GLYPH-INDEX CONVERSIOn +// CHARACTER TO GLYPH-INDEX CONVERSION STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character @@ -768,6 +771,10 @@ STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixe // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. +STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose width is 'pixels' wide. +// Width is measured as the distance from the left-side-bearing to the right-side-bearing + STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but @@ -781,6 +788,9 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size +STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap); + + STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 // table (specific to MS/Windows TTF files). @@ -790,6 +800,11 @@ STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAsc STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters +STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness); +// the underline position and thickness as defined in the "post" table +// +// Returns 1 on success (table present), 0 on failure. + STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position @@ -802,6 +817,7 @@ STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, i // Gets the bounding box of the visible part of the glyph, in unscaled coordinates STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing); STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency @@ -1043,9 +1059,12 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: -// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html +// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm +STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *output_buffer, size_t output_buffer_len); +// return the default english full name of the font as utf-8 + enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, @@ -1389,6 +1408,7 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in { stbtt_uint32 cmap, t; stbtt_int32 i,numTables; + stbtt_uint32 symbol_map=0; info->data = data; info->fontstart = fontstart; @@ -1400,6 +1420,8 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->vhea = stbtt__find_table(data, fontstart, "vhea"); // not required + info->vmtx = stbtt__find_table(data, fontstart, "vmtx"); // not required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required @@ -1482,6 +1504,9 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; + case STBTT_MS_EID_SYMBOL: + symbol_map = cmap + ttULONG(data+encoding_record+4); + break; } break; case STBTT_PLATFORM_ID_UNICODE: @@ -1491,6 +1516,9 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in break; } } + if (info->index_map == 0) + info->index_map = symbol_map; + if (info->index_map == 0) return 0; @@ -1504,6 +1532,7 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); + if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) @@ -1549,19 +1578,35 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep search += 2; { - stbtt_uint16 offset, start, last; + stbtt_uint16 offset, start, last, index; + stbtt_int16 delta; stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + // get the actual range for this segment start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); last = ttUSHORT(data + endCount + 2*item); if (unicode_codepoint < start || unicode_codepoint > last) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - if (offset == 0) - return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + delta = ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item); - return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + // "if idRangeOffset is 0, the idDelta value is added directly to the character code" + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + delta); + + // "If the idRangeOffset value for the segment is not 0, ..." + // "glyphIndexAddress = idRangeOffset[i] + 2 * (c - startCode[i]) + (Ptr) &idRangeOffset[i]" + index = ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + + // "Once the glyph indexing operation is complete, the glyph ID at the indicated address + // is checked. If it's not 0 (that is, if it's not the missing glyph), the value is added + // to idDelta[i] to get the actual glyph ID to use." + if (index != 0) { + index = (stbtt_uint16) (index + delta); + } + + return index; } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); @@ -1630,7 +1675,7 @@ static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, in STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { if (info->cff.size) { - stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + return stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; @@ -1772,8 +1817,8 @@ static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, s if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - // now start the new one - start_off = !(flags & 1); + // now start the new one... avoid looking ahead if we're at the end of a contour + start_off = !(flags & 1) && i < ttUSHORT(endPtsOfContours+j*2); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. @@ -1856,23 +1901,35 @@ static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, s mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } - // Find transformation scales. + // Find transformation scales. Per TrueType spec, these are used + // ONLY to rescale the offsets (mtx[4], mtx[5]) when + // SCALED_COMPONENT_OFFSET (flag bit 11, 0x800) is set. They must + // NOT scale the linear part of the transform — doing so squares + // the scale factor and is the cause of composite sub-components + // rendering at wrong sizes in COLR emoji fonts (OpenMoji, Noto + // Color Emoji, Microsoft Fluent Emoji). m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + // Default: UNSCALED offsets (Microsoft convention; matches modern + // font tooling). Only SCALED_COMPONENT_OFFSET (bit 11) set without + // UNSCALED_COMPONENT_OFFSET (bit 12) triggers the offset rescale. + if ((flags & (1<<11)) && !(flags & (1<<12))) { + mtx[4] *= m; mtx[5] *= n; + } // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { - // Transform vertices. + // Transform vertices: v' = M·v + t. No double-scaling. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; - v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + v->x = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); + v->y = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); x=v->cx; y=v->cy; - v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + v->cx = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); + v->cy = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); @@ -2008,7 +2065,7 @@ static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int gly start = end; } } - if (fdselector == -1) return stbtt__new_buf(NULL, 0); // [DEAR IMGUI] fixed, see #6007 and nothings/stb#1422 + if (fdselector == -1) return stbtt__new_buf(NULL, 0); return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); } @@ -2319,6 +2376,12 @@ STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_inde } } +STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing) +{ + if (advanceHeight) *advanceHeight = ttSHORT(info->data + info->vmtx + 4*glyph_index); + if (topSideBearing) *topSideBearing = ttSHORT(info->data + info->vmtx + 4*glyph_index + 2); +} + STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) { stbtt_uint8 *data = info->data + info->kern; @@ -2511,7 +2574,7 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, in data = info->data + info->gpos; if (ttUSHORT(data+0) != 1) return 0; // Major version 1 - if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 + if (ttUSHORT(data+2) > 1) return 0; // Minor version 0, or 1 lookupListOffset = ttUSHORT(data+8); lookupList = data + lookupListOffset; @@ -2524,15 +2587,28 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, in stbtt_uint16 lookupType = ttUSHORT(lookupTable); stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4); stbtt_uint8 *subTableOffsets = lookupTable + 6; - if (lookupType != 2) // Pair Adjustment Positioning Subtable + if (lookupType != 2 && // Pair Adjustment Positioning Subtable + lookupType != 9) // Positioning Subtable Extension continue; for (sti=0; sti= class1Count) return 0; // malformed if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed + valueRecordPairSizeInBytes = valueFormat1 == 68 ? 4 : 2; + class1Records = table + 16; - class2Records = class1Records + 2 * (glyph1class * class2Count); - xAdvance = ttSHORT(class2Records + 2 * glyph2class); + class2Records = class1Records + valueRecordPairSizeInBytes * (glyph1class * class2Count); + xAdvance = ttSHORT(class2Records + valueRecordPairSizeInBytes * glyph2class); return xAdvance; } else return 0; @@ -2617,9 +2700,10 @@ STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int int xAdvance = 0; if (info->gpos) - xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); - else if (info->kern) - xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + xAdvance = stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + + if (info->kern && xAdvance == 0) + xAdvance = stbtt__GetGlyphKernInfoAdvance(info, g1, g2); return xAdvance; } @@ -2636,6 +2720,11 @@ STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepo stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } +STBTT_DEF void stbtt_GetCodepointVMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceHeight, int *topSideBearing) +{ + stbtt_GetGlyphVMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceHeight, topSideBearing); +} + STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); @@ -2643,6 +2732,13 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } +STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap) +{ + if (vertTypoAscender ) *vertTypoAscender = ttSHORT(info->data+info->vhea + 4); + if (vertTypoDescender) *vertTypoDescender = ttSHORT(info->data+info->vhea + 6); + if (vertTypoLineGap) *vertTypoLineGap = ttSHORT(info->data+info->vhea + 8); +} + STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); @@ -2662,12 +2758,28 @@ STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y1 = ttSHORT(info->data + info->head + 42); } +STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "post"); + if (!tab) + return 0; + *position = ttSHORT(info->data + tab + 8); + *thickness = ttSHORT(info->data + tab + 10); + return 1; +} + STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } +STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float width) +{ + int fwidth = ttSHORT(info->data + info->hhea + 10) - ttSHORT(info->data + info->hhea + 12); + return (float) width / fwidth; +} + STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); @@ -3202,9 +3314,8 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, if (y_final > y_bottom) { int denom = (x2 - (x1+1)); y_final = y_bottom; - if (denom != 0) { // [DEAR IMGUI] Avoid div by zero (https://github.com/nothings/stb/issues/1316) + if (denom != 0) dy = (y_final - y_crossing ) / denom; // if denom=0, y_final = y_crossing, so y_final <= y_bottom - } } // in second pixel, area covered by line segment found in first pixel @@ -4215,7 +4326,7 @@ STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { - int i,j,k, missing_glyph = -1, return_value = 1; + int i,j,k, missing_range = -1, missing_glyph = -1, return_value = 1; // save current values int old_h_over = spc->h_oversample; @@ -4281,12 +4392,14 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->yoff2 = (y0 + r->h) * recip_v + sub_y; - if (glyph == 0) + if (glyph == 0) { + missing_range = i; missing_glyph = j; + } } else if (spc->skip_missing) { return_value = 0; } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { - ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; + ranges[i].chardata_for_range[j] = ranges[missing_range].chardata_for_range[missing_glyph]; } else { return_value = 0; // if any fail, report failure } @@ -4310,7 +4423,7 @@ STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; - int i, j, n, return_value; // [DEAR IMGUI] removed = 1; + int i, j, n, return_value; //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; @@ -4467,7 +4580,7 @@ static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], } } -static int equal(float *a, float *b) +static int stbtt__equal(float *a, float *b) { return (a[0] == b[0] && a[1] == b[1]); } @@ -4515,7 +4628,7 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex q1[1] = (float)y1; q2[0] = (float)x2; q2[1] = (float)y2; - if (equal(q0,q1) || equal(q1,q2)) { + if (stbtt__equal(q0,q1) || stbtt__equal(q1,q2)) { x0 = (int)verts[i-1].x; //-V1048 y0 = (int)verts[i-1].y; //-V1048 x1 = (int)verts[i ].x; @@ -4592,8 +4705,13 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); // if empty, return NULL - if (ix0 == ix1 || iy0 == iy1) + if (ix0 == ix1 || iy0 == iy1) { + if (width) *width = 0; + if (height) *height = 0; + if (xoff) *xoff = 0; + if (yoff) *yoff = 0; return NULL; + } ix0 -= padding; iy0 -= padding; @@ -4612,6 +4730,8 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc scale_y = -scale_y; { + // distance from singular values (in the same units as the pixel grid) + const float eps = 1./1024, eps2 = eps*eps; int x,y,i,j; float *precompute; stbtt_vertex *verts; @@ -4624,15 +4744,15 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); - precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; + precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist; } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float len2 = bx*bx + by*by; - if (len2 != 0.0f) - precompute[i] = 1.0f / (bx*bx + by*by); + if (len2 >= eps2) + precompute[i] = 1.0f / len2; else precompute[i] = 0.0f; } else @@ -4697,8 +4817,8 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc float a = 3*(ax*bx + ay*by); float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); float c = mx*ax+my*ay; - if (a == 0.0) { // if a is 0, it's linear - if (b != 0.0) { + if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear + if (STBTT_fabs(b) >= eps2) { res[num++] = -c/b; } } else { @@ -4848,6 +4968,126 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l return NULL; } +// convert utf16 to utf8 and return the length required to output NUL-terminated; buffer_len of 0 means to just query length +// if you pass a buffer that's too small, it'll NULL terminate and return the actual length computed +STBTT_DEF int stbtt__ConvertUTF16BEtoUTF8(char *buffer, size_t buffer_len, unsigned char *src, size_t src_len_raw) +{ + int src_len = (int) src_len_raw; + int write_max = 0; + int i = 0, write, off = 0; + write = (buffer_len != 0); + write_max = (int) (buffer_len-1); + + if ((size_t) src_len != src_len_raw) + return -1; + + if (write) { + if (write_max < 0 || ((size_t) write_max+1 != buffer_len && write_max != 0)) + return -1; + } + + if (buffer_len == 1) { + buffer[0] = 0; + return 1; + } + + while (off < src_len) { + stbtt_uint16 ch = src[off+0]*256 + src[off+1]; + off += 2; + if (ch < 0x80) { + if (write) { + if (i >= write_max) { buffer[i] = 0; return i+1; } + buffer[i] = (char) ch; + } + ++i; + } else if (ch < 0x800) { + if (write) { + if (i+1 >= write_max) { buffer[i] = 0; return i+1; } + buffer[i+0] = (char) ( 0xc0 + (ch >> 6) ); + buffer[i+1] = (char) ( 0x80 + (ch & 0x3f) ); + } + i += 2; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = src[off+0]*256 + src[off+1]; + off += 2; + if (write) { + if (i+3 >= write_max) { buffer[i] = 0; return i+1; } + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + buffer[i+0] = (char) ( 0xf0 + (c >> 18) ); + buffer[i+1] = (char) ( 0x80 + ((c >> 12) & 0x3f) ); + buffer[i+2] = (char) ( 0x80 + ((c >> 6) & 0x3f) ); + buffer[i+3] = (char) ( 0x80 + ((c ) & 0x3f) ); + } + i += 4; + } else if (ch >= 0xdc00 && ch < 0xe000) { + if (write) + buffer[i] = 0; + return -1; + } else { + if (write) { + if (i+2 >= write_max) { buffer[i] = 0; return i+1; } + buffer[i+0] = (char) ( 0xe0 + (ch >> 12) ); + buffer[i+1] = (char) ( 0x80 + ((ch >> 6) & 0x3f) ); + buffer[i+2] = (char) ( 0x80 + ((ch ) & 0x3f) ); + } + i += 3; + } + } + if (write) { + STBTT_assert(i <= write_max); + buffer[i] = 0; + } + return i+1; +} + +// Returns the english full name of the font as UTF-8 +STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *buffer, size_t buffer_len) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return -1; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + char* str; + stbtt_uint16 platformId; + stbtt_uint16 encodingId; + stbtt_uint16 languageId; + size_t length; + stbtt_uint32 loc = nm + 6 + 12 * i; + if (ttUSHORT(fc+loc+6) != 4) continue; + platformId = ttUSHORT(fc+loc+0); + encodingId = ttUSHORT(fc+loc+2); + languageId = ttUSHORT(fc+loc+4); + if (!(platformId == STBTT_PLATFORM_ID_MAC && languageId == STBTT_MAC_LANG_ENGLISH) && !(platformId == STBTT_PLATFORM_ID_MICROSOFT && languageId == STBTT_MS_LANG_ENGLISH)) + continue; + + length = ttUSHORT(fc+loc+8); + str = (char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + if (platformId == STBTT_PLATFORM_ID_UNICODE || (platformId == STBTT_PLATFORM_ID_MICROSOFT && (encodingId == 1 || encodingId == 10))) //-V560 + return stbtt__ConvertUTF16BEtoUTF8(buffer, buffer_len, (unsigned char *) str, length); + else { + if (buffer == NULL) + return (int) length; + + if (length < buffer_len) { + memcpy(buffer, str, length); + buffer[length] = 0; + return (int) length; + } else { + memcpy(buffer, str, buffer_len-1); + buffer[buffer_len-1] = 0; + return (int) length; + } + } + } + return -1; +} + static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; From b626430cf778d0ed033a9e3f7aa8ad594716524e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Nov 2026 17:07:05 +0100 Subject: [PATCH 239/245] stb: shallow updates to stb_textedit to match cleaned up PR. --- imstb_textedit.h | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/imstb_textedit.h b/imstb_textedit.h index 1fbccba58..a5b0b2687 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -40,7 +40,8 @@ // // VERSION HISTORY // -// !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +// x.xx (2026-11-12) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +// x.xx (2026-11-12) add stb_textedit_text(), STB_TEXTEDIT_GETPREVCHARINDEX(), STB_TEXTEDIT_GETNEXTCHARINDEX() to facilitate UTF-8 support while preserving byte indices. // 1.15 (2026-11-08) various fixes // 1.14 (2021-07-11) page up/down, various fixes // 1.13 (2019-02-07) fix bug in undo size management @@ -183,12 +184,12 @@ // STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text // STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text // -// To support UTF-8: +// To support UTF-8 while using indices to _bytes_ (instead of indices to _codepoints_): // // STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character // STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character +// Call stb_textedit_text() directly to submit text contents. // Do NOT define STB_TEXTEDIT_KEYTOTEXT. -// Instead, call stb_textedit_text() directly for text contents. // // Keyboard input must be encoded as a single integer value; e.g. a character code // and some bitflags that represent shift states. to simplify the interface, SHIFT must @@ -259,8 +260,8 @@ // a corresponding character or text event. // // text: -// (optional) call this to directly send text input the textfield, which is required -// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() +// (optional) call this to directly send text input the textfield, which is +// helpful for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() // cannot infer text length. // // key: @@ -271,7 +272,7 @@ // various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit // set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is // clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to -// anything other type you want before including. +// any other type you want before including. // if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are // transformed into text and stb_textedit_text() is automatically called. // @@ -422,12 +423,9 @@ typedef struct #define IMSTB_TEXTEDIT_memmove memmove #endif -// [DEAR IMGUI] -// Functions must be implemented for UTF8 support -// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit. -// There is not necessarily a '[DEAR IMGUI]' at the usage sites. -#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX -#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) +// Functions must be implemented for UTF-8 support with indices to bytes. +#ifndef STB_TEXTEDIT_GETPREVCHARINDEX +#define STB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) #endif #ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX #define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1) @@ -787,12 +785,7 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS return 0; } -#ifndef STB_TEXTEDIT_KEYTYPE -#define STB_TEXTEDIT_KEYTYPE int -#endif - // API key: process text input -// [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) { // can't add newline in single-line mode @@ -818,12 +811,16 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta } } -// API char: process a character input (not suitable for UTF-8 codepoints). +// API char: process a character input static void stb_textedit_char(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE ch) { stb_textedit_text(str, state, &ch, 1); } +#ifndef STB_TEXTEDIT_KEYTYPE +#define STB_TEXTEDIT_KEYTYPE int +#endif + // API key: process a keyboard input static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) { @@ -831,10 +828,10 @@ retry: switch (key) { default: { #ifdef STB_TEXTEDIT_KEYTOTEXT - // This is not suitable for UTF-8 support. + // This is not suitable for UTF-8 support with indices to bytes. int c = STB_TEXTEDIT_KEYTOTEXT(key); if (c > 0) { - IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c; + IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE) c; stb_textedit_char(str, state, ch); } #endif From 36682babdf082e2ede9d74ef2d9602af2dbd3b7f Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Nov 2026 17:40:59 +0100 Subject: [PATCH 240/245] CI: update attempt for apt-key missing in Ubuntu 26. --- .github/workflows/static-analysis.yml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 231d3a972..d092fd714 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -23,9 +23,16 @@ jobs: run: | if [[ "$PVS_STUDIO_LICENSE" != "" ]]; then - wget -q https://files.pvs-studio.com/etc/pubkey.txt - sudo apt-key add pubkey.txt - sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.pvs-studio.com/etc/viva64.list + wget -qO pvs-key.asc https://files.pvs-studio.com/etc/pubkey.txt + gpg --dearmor -o pvs-key.gpg pvs-key.asc + sudo install -D -m 644 pvs-key.gpg /etc/apt/keyrings/pvs-studio.gpg + wget -qO viva64.list https://files.pvs-studio.com/etc/viva64.list + sed -E \ + -e 's|^deb \[|deb [signed-by=/etc/apt/keyrings/pvs-studio.gpg |; t' \ + -e 's|^deb |deb [signed-by=/etc/apt/keyrings/pvs-studio.gpg] |' \ + viva64.list > viva64-scoped.list + sudo install -m 644 viva64-scoped.list /etc/apt/sources.list.d/viva64.list + sudo apt-get update sudo apt-get install -y pvs-studio pvs-studio-analyzer credentials -o pvs-studio.lic $PVS_STUDIO_LICENSE From 8c36ecfb61733a3e6172d97b9e1fdb7caf9147f9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Nov 2026 18:18:11 +0100 Subject: [PATCH 241/245] Backends: DirectX9: pre-transforming vertices and using `D3DFVF_XYZRHW` vertex format, largely increasing performances when in `D3DCREATE_SOFTWARE_VERTEXPROCESSING` mode. (#9628) --- backends/imgui_impl_dx9.cpp | 21 ++++++++++++--------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 360398f04..10d0dc21e 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-11-13: DirectX9: Pre-transforming vertices and using `D3DFVF_XYZRHW` vertex format, largely increasing performances when in `D3DCREATE_SOFTWARE_VERTEXPROCESSING` mode. (#9628) // 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. (#9378) // 2026-03-19: Fixed issue in ImGui_ImplDX9_UpdateTexture() if ImTextureID_Invalid is defined to be != 0, which became the default since 2026-03-12. (#9295, #9310) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. @@ -71,10 +72,11 @@ struct ImGui_ImplDX9_Data struct CUSTOMVERTEX { float pos[3]; + float rhw; D3DCOLOR col; float uv[2]; }; -#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) +#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1) #ifdef IMGUI_USE_BGRA_PACKED_COLOR #define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL) @@ -141,7 +143,7 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); - // Setup orthographic projection matrix + // Setup orthographic projection matrix for custom draw callbacks. Our pretransformed vertices bypass these transforms. // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() { @@ -232,18 +234,19 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) return; } - // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. - // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and - // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR - // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } + // Copy and pre-transform all vertices into a single contiguous buffer, convert colors to DX9 default format. + // XYZRHW bypasses vertex processing, avoiding repeated software transforms for each draw command. Apply DX9's half-pixel offset here. + // Define IMGUI_USE_BGRA_PACKED_COLOR in imconfig.h to avoid repacking colors. + const ImVec2 pos_offset(draw_data->DisplayPos.x + 0.5f, draw_data->DisplayPos.y + 0.5f); for (const ImDrawList* draw_list : draw_data->CmdLists) { const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data; for (int i = 0; i < draw_list->VtxBuffer.Size; i++) { - vtx_dst->pos[0] = vtx_src->pos.x; - vtx_dst->pos[1] = vtx_src->pos.y; - vtx_dst->pos[2] = 0.0f; + vtx_dst->pos[0] = vtx_src->pos.x - pos_offset.x; + vtx_dst->pos[1] = vtx_src->pos.y - pos_offset.y; + vtx_dst->pos[2] = 0.5f; + vtx_dst->rhw = 1.0f; vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col); vtx_dst->uv[0] = vtx_src->uv.x; vtx_dst->uv[1] = vtx_src->uv.y; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b62333dac..d449038d1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -128,6 +128,8 @@ Other Changes: Made the script detect the environment when needed (e.g. to specify library path). - Examples: added support for ARM64 in selected build_win.bat helpers. (#9593) [@Harishmcw] - Backends: + - DirectX9: pre-transforming vertices and using `D3DFVF_XYZRHW` vertex format, largely + increasing performances when in `D3DCREATE_SOFTWARE_VERTEXPROCESSING` mode. (#9628) - GLFW: allow initialization with missing HWND. (#9619) [@djohansson] - GLFW, SDL2: Emscripten implementation of `Platform_OpenInShellFn` calls `window.open()` with `noopener`: prevents newly opened tab from keeping a From be74a55b330eb79ce03c3d0057e3b7559f41803c Mon Sep 17 00:00:00 2001 From: Marius PvW Date: Wed, 11 Nov 2026 14:24:01 -0500 Subject: [PATCH 242/245] Backends: Metal4: renamed internal Objective-C classes so the Metal and Metal4 backends can be linked into the same binary. (#9626) --- backends/imgui_impl_metal4.mm | 82 +++++++++++++++++------------------ 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index b811e3d19..a8a20ae73 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -41,7 +41,7 @@ struct ImGui_Metal4_ConstantData float ModelViewProjectionMatrix[4][4]; }; -@interface MetalBuffer : NSObject +@interface Metal4Buffer : NSObject @property (nonatomic, strong) id buffer; @property (nonatomic, assign) double lastReuseTime; - (instancetype)initWithBuffer:(id)buffer; @@ -51,7 +51,7 @@ struct ImGui_Metal4_ConstantData // An object that encapsulates the data necessary to uniquely identify a // render pipeline state. These are used as cache keys. -@interface FramebufferDescriptor : NSObject +@interface Metal4FramebufferDescriptor : NSObject @property (nonatomic, assign) unsigned long sampleCount; @property (nonatomic, assign) MTLPixelFormat depthPixelFormat; @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat; @@ -59,7 +59,7 @@ struct ImGui_Metal4_ConstantData - (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index; @end -@interface MetalTexture : NSObject +@interface Metal4Texture : NSObject @property (nonatomic, strong) id metalTexture; - (instancetype)initWithTexture:(id)metalTexture; @end @@ -67,7 +67,7 @@ struct ImGui_Metal4_ConstantData // A singleton that stores long-lived objects that are needed by the Metal // renderer backend. Stores the render pipeline state cache and the default // font texture, and manages the reusable buffer cache. -@interface MetalContext : NSObject +@interface Metal4Context : NSObject @property (nonatomic, strong) id device; @property (nonatomic, strong) id commandQueue; @property (nonatomic, strong) id depthStencilState; @@ -75,24 +75,24 @@ struct ImGui_Metal4_ConstantData @property (nonatomic, strong) id samplerStateLinear; @property (nonatomic, strong) id samplerStateNearest; @property (nonatomic, strong) id residencySet; -@property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; +@property (nonatomic, strong) Metal4FramebufferDescriptor* framebufferDescriptor; @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; @property (nonatomic, assign) NSUInteger framesInFlight; @property (nonatomic, assign) NSUInteger currentFrameSlot; @property (nonatomic, strong) NSArray>* constantBuffers; @property (nonatomic, assign) ImGui_Metal4_ConstantData** constantBufferContentsArray; -@property (nonatomic, strong) NSMutableArray*>* bufferCaches; +@property (nonatomic, strong) NSMutableArray*>* bufferCaches; @property (nonatomic, strong) NSObject* bufferCacheLock; @property (nonatomic, assign) double lastBufferCachePurge; - (id)currentConstantBuffer; - (ImGui_Metal4_ConstantData*)currentConstantBufferContents; -- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; -- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device; +- (Metal4Buffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; +- (id)renderPipelineStateForFramebufferDescriptor:(Metal4FramebufferDescriptor*)descriptor device:(id)device; @end struct ImGui_ImplMetal4_Data { - MetalContext* SharedMetalContext; + Metal4Context* SharedMetalContext; id RenderCommandEncoder; ImGui_ImplMetal4_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -126,7 +126,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, (__bridge id)(commandEncoder)); } -bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device) +bool ImGui_ImplMetal4_CreateDeviceObjects(MTL::Device* device) { return ImGui_ImplMetal4_CreateDeviceObjects((__bridge id)(device)); } @@ -141,9 +141,9 @@ void ImGui_ImplMetal4_NewFrame(MTL4RenderPassDescriptor* renderPassDescriptor, i IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal4_Init()?"); IM_ASSERT(frameInFlightIndex < (int)bd->SharedMetalContext.framesInFlight && "frameInFlightIndex out of range! See framesInFlight passed to ImGui_ImplMetal4_Init()."); #ifdef IMGUI_IMPL_METAL_CPP - bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; + bd->SharedMetalContext.framebufferDescriptor = [[[Metal4FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; #else - bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; + bd->SharedMetalContext.framebufferDescriptor = [[Metal4FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; #endif bd->SharedMetalContext.currentFrameSlot = (NSUInteger)frameInFlightIndex; if (bd->SharedMetalContext.depthStencilState == nil) @@ -152,7 +152,7 @@ void ImGui_ImplMetal4_NewFrame(MTL4RenderPassDescriptor* renderPassDescriptor, i static void ImGui_ImplMetal4_SetupRenderState(ImDrawData* draw_data, id commandBuffer, id commandEncoder, id renderPipelineState, - MetalBuffer* vertexBuffer, size_t vertexBufferOffset) + Metal4Buffer* vertexBuffer, size_t vertexBufferOffset) { IM_UNUSED(commandBuffer); ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); @@ -204,7 +204,7 @@ static void ImGui_ImplMetal4_DrawCallback_SetSamplerNearest(const ImDrawList*, c void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder) { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); - MetalContext* ctx = bd->SharedMetalContext; + Metal4Context* ctx = bd->SharedMetalContext; // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x + 0.5f); @@ -233,8 +233,8 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idTotalVtxCount * sizeof(ImDrawVert); size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx); - MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; - MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; + Metal4Buffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; + Metal4Buffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; bd->RenderCommandEncoder = commandEncoder; ImGui_ImplMetal4_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0); @@ -312,10 +312,10 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idIdxBuffer.Size * sizeof(ImDrawIdx); } - MetalContext* sharedMetalContext = bd->SharedMetalContext; + Metal4Context* sharedMetalContext = bd->SharedMetalContext; @synchronized(sharedMetalContext.bufferCacheLock) { - NSMutableArray* slotCache = sharedMetalContext.bufferCaches[sharedMetalContext.currentFrameSlot]; + NSMutableArray* slotCache = sharedMetalContext.bufferCaches[sharedMetalContext.currentFrameSlot]; [slotCache addObject:vertexBuffer]; [slotCache addObject:indexBuffer]; } @@ -327,7 +327,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idBackendUserData)) + if (Metal4Texture* backend_tex = (__bridge_transfer Metal4Texture*)(tex->BackendUserData)) { IM_ASSERT(backend_tex.metalTexture == (__bridge id)(void*)(intptr_t)tex->TexID); backend_tex.metalTexture = nil; @@ -363,7 +363,7 @@ void ImGui_ImplMetal4_UpdateTexture(ImTextureData* tex) id texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor]; [bd->SharedMetalContext.residencySet addAllocation:texture]; [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4]; - MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture]; + Metal4Texture* backend_tex = [[Metal4Texture alloc] initWithTexture:texture]; // Store identifiers tex->SetTexID((ImTextureID)(intptr_t)texture); @@ -374,7 +374,7 @@ void ImGui_ImplMetal4_UpdateTexture(ImTextureData* tex) { // Update selected blocks. We only ever write to textures regions which have never been used before! // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region. - MetalTexture* backend_tex = (__bridge MetalTexture*)(tex->BackendUserData); + Metal4Texture* backend_tex = (__bridge Metal4Texture*)(tex->BackendUserData); for (ImTextureRect& r : tex->Updates) { [backend_tex.metalTexture replaceRegion:MTLRegionMake2D((NSUInteger)r.x, (NSUInteger)r.y, (NSUInteger)r.w, (NSUInteger)r.h) @@ -474,11 +474,11 @@ bool ImGui_ImplMetal4_Init(id device, id commandQue platform_io.DrawCallback_SetSamplerLinear = ImGui_ImplMetal4_DrawCallback_SetSamplerLinear; platform_io.DrawCallback_SetSamplerNearest = ImGui_ImplMetal4_DrawCallback_SetSamplerNearest; - bd->SharedMetalContext = [[MetalContext alloc] init]; + bd->SharedMetalContext = [[Metal4Context alloc] init]; bd->SharedMetalContext.device = device; bd->SharedMetalContext.commandQueue = commandQueue; bd->SharedMetalContext.framesInFlight = (NSUInteger)framesInFlight; - NSMutableArray*>* bufferCaches = [NSMutableArray array]; + NSMutableArray*>* bufferCaches = [NSMutableArray array]; for (NSUInteger i = 0; i < (NSUInteger)framesInFlight; i++) [bufferCaches addObject:[NSMutableArray array]]; bd->SharedMetalContext.bufferCaches = bufferCaches; @@ -502,7 +502,7 @@ void ImGui_ImplMetal4_Shutdown() platform_io.ClearRendererHandlers(); } -@implementation MetalBuffer +@implementation Metal4Buffer - (instancetype)initWithBuffer:(id)buffer { if ((self = [super init])) @@ -514,9 +514,9 @@ void ImGui_ImplMetal4_Shutdown() } @end -#pragma mark - FramebufferDescriptor implementation +#pragma mark - Metal4FramebufferDescriptor implementation -@implementation FramebufferDescriptor +@implementation Metal4FramebufferDescriptor { MTLPixelFormat _colorPixelFormats[IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS]; } @@ -541,7 +541,7 @@ void ImGui_ImplMetal4_Shutdown() - (nonnull id)copyWithZone:(nullable NSZone*)zone { - FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; + Metal4FramebufferDescriptor* copy = [[Metal4FramebufferDescriptor allocWithZone:zone] init]; copy.sampleCount = self.sampleCount; memcpy(copy->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)); copy.depthPixelFormat = self.depthPixelFormat; @@ -563,8 +563,8 @@ void ImGui_ImplMetal4_Shutdown() - (BOOL)isEqual:(id)object { - FramebufferDescriptor* other = object; - if (![other isKindOfClass:[FramebufferDescriptor class]]) + Metal4FramebufferDescriptor* other = object; + if (![other isKindOfClass:[Metal4FramebufferDescriptor class]]) return NO; return other.sampleCount == self.sampleCount && memcmp(other->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)) == 0 && @@ -574,9 +574,9 @@ void ImGui_ImplMetal4_Shutdown() @end -#pragma mark - MetalTexture implementation +#pragma mark - Metal4Texture implementation -@implementation MetalTexture +@implementation Metal4Texture - (instancetype)initWithTexture:(id)metalTexture { if ((self = [super init])) @@ -586,9 +586,9 @@ void ImGui_ImplMetal4_Shutdown() @end -#pragma mark - MetalContext implementation +#pragma mark - Metal4Context implementation -@implementation MetalContext +@implementation Metal4Context - (instancetype)init { if ((self = [super init])) @@ -615,20 +615,20 @@ void ImGui_ImplMetal4_Shutdown() return self.constantBufferContentsArray[self.currentFrameSlot]; } -- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device +- (Metal4Buffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device { double now = GetMachAbsoluteTimeInSeconds(); - NSMutableArray* slotCache = self.bufferCaches[self.currentFrameSlot]; + NSMutableArray* slotCache = self.bufferCaches[self.currentFrameSlot]; @synchronized(self.bufferCacheLock) { // Purge old buffers that haven't been useful for a while if (now - self.lastBufferCachePurge > 1.0) { - for (NSMutableArray* cache in self.bufferCaches) + for (NSMutableArray* cache in self.bufferCaches) { NSMutableArray* survivors = [NSMutableArray array]; - for (MetalBuffer* candidate in cache) + for (Metal4Buffer* candidate in cache) if (candidate.lastReuseTime > self.lastBufferCachePurge) [survivors addObject:candidate]; [cache setArray:survivors]; @@ -637,8 +637,8 @@ void ImGui_ImplMetal4_Shutdown() } // See if we have a buffer we can reuse, from this frame-in-flight slot's own cache - MetalBuffer* bestCandidate = nil; - for (MetalBuffer* candidate in slotCache) + Metal4Buffer* bestCandidate = nil; + for (Metal4Buffer* candidate in slotCache) if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime)) bestCandidate = candidate; @@ -653,7 +653,7 @@ void ImGui_ImplMetal4_Shutdown() // No luck; make a new buffer id backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared]; [self.residencySet addAllocation:backing]; - return [[MetalBuffer alloc] initWithBuffer:backing]; + return [[Metal4Buffer alloc] initWithBuffer:backing]; } const char* shaderCode = R"( @@ -695,7 +695,7 @@ fragment half4 fragment_main(VertexOut in [[stage_in]], } )"; -- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device +- (id)renderPipelineStateForFramebufferDescriptor:(Metal4FramebufferDescriptor*)descriptor device:(id)device { NSError* error = nil; From 514f6a8e7f2deeab14063bf9850ddacaadde9aee Mon Sep 17 00:00:00 2001 From: Marius PvW Date: Wed, 11 Nov 2026 11:22:58 -0500 Subject: [PATCH 243/245] Backends: Metal4: defer recycling vertex/index buffers until the frame slot is reused. (#9622, #9625) On master, the application waits for GPU completion before reusing a frame slot. Keep the buffers out of the cache until NewFrame() is called for that slot. --- backends/imgui_impl_metal4.h | 1 + backends/imgui_impl_metal4.mm | 17 ++++++++++++++++- docs/CHANGELOG.txt | 2 ++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_metal4.h b/backends/imgui_impl_metal4.h index b5b54cad0..9ef6e06ef 100644 --- a/backends/imgui_impl_metal4.h +++ b/backends/imgui_impl_metal4.h @@ -38,6 +38,7 @@ IMGUI_IMPL_API bool ImGui_ImplMetal4_Init(id device, id commandBuffer, diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index a8a20ae73..7c4b0775d 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -19,6 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2026-11-16: Fixed vertex/index buffers being reused by a later draw in the same frame. (#9622, #9625) // 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-07: Metal 4: Added metal-cpp support. (#9461) @@ -82,6 +83,7 @@ struct ImGui_Metal4_ConstantData @property (nonatomic, strong) NSArray>* constantBuffers; @property (nonatomic, assign) ImGui_Metal4_ConstantData** constantBufferContentsArray; @property (nonatomic, strong) NSMutableArray*>* bufferCaches; +@property (nonatomic, strong) NSMutableArray*>* buffersInFlight; // per frame slot: buffers used since its last NewFrame(), may still be read by the GPU @property (nonatomic, strong) NSObject* bufferCacheLock; @property (nonatomic, assign) double lastBufferCachePurge; - (id)currentConstantBuffer; @@ -148,6 +150,13 @@ void ImGui_ImplMetal4_NewFrame(MTL4RenderPassDescriptor* renderPassDescriptor, i bd->SharedMetalContext.currentFrameSlot = (NSUInteger)frameInFlightIndex; if (bd->SharedMetalContext.depthStencilState == nil) ImGui_ImplMetal4_CreateDeviceObjects(bd->SharedMetalContext.device); + + // The application has finished GPU work for this slot before reusing it. + @synchronized(bd->SharedMetalContext.bufferCacheLock) + { + [bd->SharedMetalContext.bufferCaches[frameInFlightIndex] addObjectsFromArray:bd->SharedMetalContext.buffersInFlight[frameInFlightIndex]]; + [bd->SharedMetalContext.buffersInFlight[frameInFlightIndex] removeAllObjects]; + } } static void ImGui_ImplMetal4_SetupRenderState(ImDrawData* draw_data, id commandBuffer, @@ -315,7 +324,8 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idSharedMetalContext; @synchronized(sharedMetalContext.bufferCacheLock) { - NSMutableArray* slotCache = sharedMetalContext.bufferCaches[sharedMetalContext.currentFrameSlot]; + // Keep these buffers alive and out of the cache until the next NewFrame() for this slot. + NSMutableArray* slotCache = sharedMetalContext.buffersInFlight[sharedMetalContext.currentFrameSlot]; [slotCache addObject:vertexBuffer]; [slotCache addObject:indexBuffer]; } @@ -479,9 +489,14 @@ bool ImGui_ImplMetal4_Init(id device, id commandQue bd->SharedMetalContext.commandQueue = commandQueue; bd->SharedMetalContext.framesInFlight = (NSUInteger)framesInFlight; NSMutableArray*>* bufferCaches = [NSMutableArray array]; + NSMutableArray*>* buffersInFlight = [NSMutableArray array]; for (NSUInteger i = 0; i < (NSUInteger)framesInFlight; i++) + { [bufferCaches addObject:[NSMutableArray array]]; + [buffersInFlight addObject:[NSMutableArray array]]; + } bd->SharedMetalContext.bufferCaches = bufferCaches; + bd->SharedMetalContext.buffersInFlight = buffersInFlight; return true; } diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d449038d1..a5befa83b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -136,6 +136,8 @@ Other Changes: reference to opening page. (#9615, #7660, #7851) [@pthom] - SDL2: on iOS, also restore calling `SDL_StartTextInput()/SDL_StopTextInput()` in IME handler. Match Android change in 1.93.0. [@pthom] (#7636, #9474, #9617) + - Metal4: fixed vertex/index buffers being reused by a later draw in the same frame + before the GPU had processed them. (#9622, #9625) [@lailoken] - Vulkan: don't transition swapchain images from `VK_IMAGE_LAYOUT_UNDEFINED` to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in examples and multi-viewport support. (#9553, #9496, #9152) [@sarpsenturk, @LewisJustin] From 96704190661ed45686cc0850087d9e475d398ee9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 16 Nov 2026 12:46:50 +0100 Subject: [PATCH 244/245] Backends: Metal4: align 16-bit index buffer addresses to 4 bytes (workaround for supposed Metal4 glitch). --- backends/imgui_impl_metal4.mm | 29 +++++++++++++++++++++++++---- docs/CHANGELOG.txt | 2 ++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index 7c4b0775d..9045dc4e0 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -19,7 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-16: Fixed vertex/index buffers being reused by a later draw in the same frame. (#9622, #9625) +// 2026-11-16: Worked around rendering artifacts by aligning 16-bit index buffer addresses to 4 bytes. / Fixed vertex/index buffers being reused by a later draw in the same frame. (#9622, #9625) // 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-07: Metal 4: Added metal-cpp support. (#9461) @@ -37,6 +37,8 @@ #pragma mark - Support classes and structs +#define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) + struct ImGui_Metal4_ConstantData { float ModelViewProjectionMatrix[4][4]; @@ -242,6 +244,16 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idTotalVtxCount * sizeof(ImDrawVert); size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx); + // Work around Metal 4 corrupting draws whose 16-bit index buffer address is only 2-byte aligned. + // Pack each draw at a 4-byte boundary, with at most one padding index per draw. + if (sizeof(ImDrawIdx) == 2) + { + indexBufferLength = 0; + for (const ImDrawList* draw_list : draw_data->CmdLists) + for (const ImDrawCmd& cmd : draw_list->CmdBuffer) + if (cmd.UserCallback == nullptr) + indexBufferLength += MEMALIGN((size_t)cmd.ElemCount * sizeof(ImDrawIdx), 4); + } Metal4Buffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; Metal4Buffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; @@ -258,7 +270,8 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idCmdLists) { memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); - memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + if (sizeof(ImDrawIdx) == 4) + memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { @@ -309,16 +322,24 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idSharedMetalContext.argumentTable setAddress:(vertexBuffer.buffer.gpuAddress + vertexBufferOffset + (pcmd->VtxOffset * sizeof(ImDrawVert))) attributeStride:sizeof(ImDrawVert) atIndex:0]; size_t indexBufferCmdOffset = indexBufferOffset + (pcmd->IdxOffset * sizeof(ImDrawIdx)); + size_t indexBufferCmdLength = (size_t)pcmd->ElemCount * sizeof(ImDrawIdx); + if (sizeof(ImDrawIdx) == 2) + { + indexBufferCmdOffset = indexBufferOffset; + memcpy((char*)indexBuffer.buffer.contents + indexBufferCmdOffset, draw_list->IdxBuffer.Data + pcmd->IdxOffset, indexBufferCmdLength); + indexBufferOffset += MEMALIGN(indexBufferCmdLength, 4); + } [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:pcmd->ElemCount indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 indexBuffer:indexBuffer.buffer.gpuAddress + indexBufferCmdOffset - indexBufferLength:indexBuffer.buffer.length - indexBufferCmdOffset]; + indexBufferLength:indexBufferCmdLength]; } } vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert); - indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); + if (sizeof(ImDrawIdx) == 4) + indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); } Metal4Context* sharedMetalContext = bd->SharedMetalContext; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a5befa83b..c798ec58a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -136,6 +136,8 @@ Other Changes: reference to opening page. (#9615, #7660, #7851) [@pthom] - SDL2: on iOS, also restore calling `SDL_StartTextInput()/SDL_StopTextInput()` in IME handler. Match Android change in 1.93.0. [@pthom] (#7636, #9474, #9617) + - Metal4: worked around rendering artifacts (e.g. flickering diagonal lines) with + 16-bit indices by aligning each draw command index buffer address to 4 bytes. - Metal4: fixed vertex/index buffers being reused by a later draw in the same frame before the GPU had processed them. (#9622, #9625) [@lailoken] - Vulkan: don't transition swapchain images from `VK_IMAGE_LAYOUT_UNDEFINED` to From 77fe4588e6af934b4167b91312174ca3fbb0d71a Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 16 Nov 2026 18:09:38 +0100 Subject: [PATCH 245/245] Backends: Metal4: remove the residency set from the command queue on shutdown. --- backends/imgui_impl_metal4.mm | 19 +++++++++++-------- docs/CHANGELOG.txt | 2 ++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index 9045dc4e0..e5d3e3472 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -19,7 +19,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-16: Worked around rendering artifacts by aligning 16-bit index buffer addresses to 4 bytes. / Fixed vertex/index buffers being reused by a later draw in the same frame. (#9622, #9625) +// 2026-11-16: Worked around rendering artifacts by aligning 16-bit index buffer addresses to 4 bytes. / Fixed vertex/index buffers being reused by a later draw in the same frame. (#9622, #9625) / Remove the residency set from the command queue on shutdown so the queue can be reused. // 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-07: Metal 4: Added metal-cpp support. (#9461) @@ -425,14 +425,15 @@ bool ImGui_ImplMetal4_CreateDeviceObjects(id device) { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); - MTLResidencySetDescriptor* residencySetDescriptor = [[MTLResidencySetDescriptor alloc] init]; - residencySetDescriptor.initialCapacity = 1000; - NSError* error = nil; - bd->SharedMetalContext.residencySet = [device newResidencySetWithDescriptor:residencySetDescriptor error:&error]; - IM_ASSERT(bd->SharedMetalContext.residencySet != nil && error == nil); - - [bd->SharedMetalContext.commandQueue addResidencySet:bd->SharedMetalContext.residencySet]; + if (bd->SharedMetalContext.residencySet == nil) + { + MTLResidencySetDescriptor* residencySetDescriptor = [[MTLResidencySetDescriptor alloc] init]; + residencySetDescriptor.initialCapacity = 1000; + bd->SharedMetalContext.residencySet = [device newResidencySetWithDescriptor:residencySetDescriptor error:&error]; + IM_ASSERT(bd->SharedMetalContext.residencySet != nil && error == nil); + [bd->SharedMetalContext.commandQueue addResidencySet:bd->SharedMetalContext.residencySet]; + } MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init]; depthStencilDescriptor.depthWriteEnabled = NO; @@ -530,6 +531,8 @@ void ImGui_ImplMetal4_Shutdown() ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplMetal4_DestroyDeviceObjects(); + if (bd->SharedMetalContext.residencySet != nil) + [bd->SharedMetalContext.commandQueue removeResidencySet:bd->SharedMetalContext.residencySet]; ImGui_ImplMetal4_DestroyBackendData(); io.BackendRendererName = nullptr; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c798ec58a..9788196ce 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -140,6 +140,8 @@ Other Changes: 16-bit indices by aligning each draw command index buffer address to 4 bytes. - Metal4: fixed vertex/index buffers being reused by a later draw in the same frame before the GPU had processed them. (#9622, #9625) [@lailoken] + - Metal4: remove the residency set from the command queue on shutdown to avoid + hitting Metal's residency set limit when reinitializing on the same queue. - Vulkan: don't transition swapchain images from `VK_IMAGE_LAYOUT_UNDEFINED` to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in examples and multi-viewport support. (#9553, #9496, #9152) [@sarpsenturk, @LewisJustin]