From b2e7a3806a3536ecfdd082ea0d3eafec1bcd9b0b Mon Sep 17 00:00:00 2001 From: Sebastian Krzyszkowiak Date: Fri, 30 Nov 2018 16:46:43 +0100 Subject: [PATCH 001/566] Examples: Allegro5: Add touchscreen support --- examples/example_allegro5/README.md | 2 +- examples/imgui_impl_allegro5.cpp | 46 ++++++++++++++++++----------- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/examples/example_allegro5/README.md b/examples/example_allegro5/README.md index 5fdcc504..1a83fe89 100644 --- a/examples/example_allegro5/README.md +++ b/examples/example_allegro5/README.md @@ -12,7 +12,7 @@ Note that the back-end supports _BOTH_ 16-bit and 32-bit indices, but 32-bit ind - On Ubuntu 14.04+ ```bash -g++ -DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" -I .. -I ../.. main.cpp ..\imgui_impl_allegro5.cpp ../../imgui*.cpp -lallegro -lallegro_primitives -o allegro5_example +g++ -DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" -I .. -I ../.. main.cpp ../imgui_impl_allegro5.cpp ../../imgui*.cpp -lallegro -lallegro_primitives -o allegro5_example ``` - On Windows with Visual Studio's CLI diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 9a9c5801..a85ed915 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2018-11-30: Platform: Added touchscreen support. // 2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12). // 2018-06-13: Renderer: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-06-13: Renderer: Backup/restore transform and clipping rectangle. @@ -266,6 +267,8 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) io.KeyMap[ImGuiKey_Y] = ALLEGRO_KEY_Y; io.KeyMap[ImGuiKey_Z] = ALLEGRO_KEY_Z; + io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + #if ALLEGRO_HAS_CLIPBOARD io.SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText; @@ -297,8 +300,31 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT *ev) switch (ev->type) { case ALLEGRO_EVENT_MOUSE_AXES: - io.MouseWheel += ev->mouse.dz; - io.MouseWheelH += ev->mouse.dw; + if (ev->mouse.display == g_Display) + { + io.MouseWheel += ev->mouse.dz; + io.MouseWheelH += ev->mouse.dw; + io.MousePos = ImVec2(ev->mouse.x, ev->mouse.y); + } + return true; + case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: + case ALLEGRO_EVENT_MOUSE_BUTTON_UP: + if (ev->mouse.display == g_Display && ev->mouse.button <= 5) + io.MouseDown[ev->mouse.button - 1] = (ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN); + return true; + case ALLEGRO_EVENT_TOUCH_MOVE: + if (ev->touch.display == g_Display) + io.MousePos = ImVec2(ev->touch.x, ev->touch.y); + return true; + case ALLEGRO_EVENT_TOUCH_BEGIN: + case ALLEGRO_EVENT_TOUCH_END: + case ALLEGRO_EVENT_TOUCH_CANCEL: + if (ev->touch.display == g_Display && ev->touch.primary) + io.MouseDown[0] = (ev->type == ALLEGRO_EVENT_TOUCH_BEGIN); + return true; + case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY: + if (ev->mouse.display == g_Display) + io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); return true; case ALLEGRO_EVENT_KEY_CHAR: if (ev->keyboard.display == g_Display) @@ -368,21 +394,5 @@ void ImGui_ImplAllegro5_NewFrame() io.KeyAlt = al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR); io.KeySuper = al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN); - ALLEGRO_MOUSE_STATE mouse; - if (keys.display == g_Display) - { - al_get_mouse_state(&mouse); - io.MousePos = ImVec2((float)mouse.x, (float)mouse.y); - } - else - { - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - } - - al_get_mouse_state(&mouse); - io.MouseDown[0] = mouse.buttons & (1 << 0); - io.MouseDown[1] = mouse.buttons & (1 << 1); - io.MouseDown[2] = mouse.buttons & (1 << 2); - ImGui_ImplAllegro5_UpdateMouseCursor(); } From 699e945a82a69249771518858c0fde169e8dfe87 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 10:22:46 +0100 Subject: [PATCH 002/566] Merged from Docking branch: non-const ImVec2[] operator. --- imgui.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index dd859441..0d73eea3 100644 --- a/imgui.h +++ b/imgui.h @@ -170,7 +170,8 @@ struct ImVec2 float x, y; ImVec2() { x = y = 0.0f; } ImVec2(float _x, float _y) { x = _x; y = _y; } - float operator[] (size_t i) const { IM_ASSERT(i <= 1); return (&x)[i]; } // We very rarely use this [] operator, the assert overhead is fine. + float operator[] (size_t idx) const { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine. + float& operator[] (size_t idx) { IM_ASSERT(idx <= 1); return (&x)[idx]; } // We very rarely use this [] operator, the assert overhead is fine. #ifdef IM_VEC2_CLASS_EXTRA IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. #endif From 52a9f8bd3e7f7837df6157802a7b1fe327c768d3 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 10:26:08 +0100 Subject: [PATCH 003/566] Merged from Docking branch: Various small changes, comments, typos fixes, moved blocks. To reduce overall drift. Should be no-op. --- imgui.cpp | 95 +++++++++++++++++++++++++++++++++--------------- imgui.h | 11 +++--- imgui_demo.cpp | 5 ++- imgui_internal.h | 56 +++++++++++++++++----------- 4 files changed, 108 insertions(+), 59 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2e26ddcb..ba54366e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -937,8 +937,8 @@ CODE #endif // Debug options -#define IMGUI_DEBUG_NAV_SCORING 0 -#define IMGUI_DEBUG_NAV_RECTS 0 +#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL +#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window // Visual Studio warnings #ifdef _MSC_VER @@ -998,7 +998,6 @@ static void CheckStacksSize(ImGuiWindow* window, bool write); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list); -static void AddWindowToDrawData(ImVector* out_list, ImGuiWindow* window); static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window); static ImRect GetViewportRect(); @@ -1033,7 +1032,7 @@ static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); -static void RenderOuterBorders(ImGuiWindow* window, int border_held); +static void RenderOuterBorders(ImGuiWindow* window); } @@ -1170,7 +1169,8 @@ ImGuiIO::ImGuiIO() DisplayFramebufferScale = ImVec2(1.0f, 1.0f); DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f); - // Miscellaneous configuration options + // Miscellaneous options + MouseDrawCursor = false; #ifdef __APPLE__ ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag #else @@ -2522,6 +2522,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) Appearing = false; Hidden = false; HasCloseButton = false; + ResizeBorderHeld = -1; BeginCount = 0; BeginOrderWithinParent = -1; BeginOrderWithinContext = -1; @@ -2850,7 +2851,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) return false; - // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case. + // Special handling for the dummy item after Begin() which represent the title bar or tab. + // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed) return false; return true; @@ -3084,13 +3086,17 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) { // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. - // This is because we want ActiveId to be set even when the window is stuck from moving. + // This is because we want ActiveId to be set even when the window is not permitted to move. ImGuiContext& g = *GImGui; FocusWindow(window); SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; - if (!(window->Flags & ImGuiWindowFlags_NoMove) && !(window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) + + bool can_move_window = true; + if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) + can_move_window = false; + if (can_move_window) g.MovingWindow = window; } @@ -3158,7 +3164,8 @@ void ImGui::UpdateMouseMovingWindowEndFrame() } else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL) { - FocusWindow(NULL); // Clicking on void disable focus + // Clicking on void disable focus + FocusWindow(NULL); } } @@ -3406,7 +3413,7 @@ void ImGui::NewFrame() g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; - // Setup current font and draw list + // Setup current font and draw list shared data g.IO.Fonts->Locked = true; SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); @@ -3418,7 +3425,7 @@ void ImGui::NewFrame() g.OverlayDrawList.PushClipRectFullScreen(); g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); - // Mark rendering data as invalid to prevent user who may have a handle on it to use it + // Mark rendering data as invalid to prevent user who may have a handle on it to use it. g.DrawData.Clear(); // Drag and drop keep the source ID alive so even if the source disappear our state is consistent @@ -3545,7 +3552,7 @@ void ImGui::Initialize(ImGuiContext* context) ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen; ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine; ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll; - g.SettingsHandlers.push_front(ini_handler); + g.SettingsHandlers.push_back(ini_handler); g.Initialized = true; } @@ -3585,8 +3592,7 @@ void ImGui::Shutdown(ImGuiContext* context) g.CurrentWindowStack.clear(); g.WindowsById.Clear(); g.NavWindow = NULL; - g.HoveredWindow = NULL; - g.HoveredRootWindow = NULL; + g.HoveredWindow = g.HoveredRootWindow = NULL; g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; g.MovingWindow = NULL; g.ColorModifiers.clear(); @@ -3691,7 +3697,7 @@ static void AddWindowToDrawData(ImVector* out_render_list, ImGuiWin } } -static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window) +static void AddRootWindowToDrawData(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (window->Flags & ImGuiWindowFlags_Tooltip) @@ -3827,7 +3833,8 @@ void ImGui::EndFrame() AddWindowToSortBuffer(&g.WindowsSortBuffer, window); } - IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong + // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. + IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); g.Windows.swap(g.WindowsSortBuffer); g.IO.MetricsActiveWindows = g.WindowsActiveCount; @@ -3859,11 +3866,11 @@ void ImGui::Render() { ImGuiWindow* window = g.Windows[n]; if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1]) - AddWindowToDrawDataSelectLayer(window); + AddRootWindowToDrawData(window); } for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++) if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window - AddWindowToDrawDataSelectLayer(windows_to_render_front_most[n]); + AddRootWindowToDrawData(windows_to_render_front_most[n]); g.DrawDataBuilder.FlattenIntoSingleLayer(); // Draw software mouse cursor if requested @@ -4227,7 +4234,10 @@ bool ImGui::IsItemFocused() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - return g.NavId && !g.NavDisableHighlight && g.NavId == window->DC.LastItemId; + + if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId) + return false; + return true; } bool ImGui::IsItemClicked(int mouse_button) @@ -4561,13 +4571,16 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) } else { - // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. + // Maximum window size is determined by the display size const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0; const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0; ImVec2 size_min = style.WindowMinSize; if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) size_min = ImMin(size_min, ImVec2(4.0f, 4.0f)); ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f)); + + // When the window cannot fit all contents (either because of constraints, either because screen is too small), + // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit); if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) size_auto_fit.y += style.ScrollbarSize; @@ -4783,13 +4796,15 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au window->Size = window->SizeFull; } -static void ImGui::RenderOuterBorders(ImGuiWindow* window, int border_held) +static void ImGui::RenderOuterBorders(ImGuiWindow* window) { ImGuiContext& g = *GImGui; float rounding = window->WindowRounding; float border_size = window->WindowBorderSize; if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground)) window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); + + int border_held = window->ResizeBorderHeld; if (border_held != -1) { struct ImGuiResizeBorderDef @@ -5111,9 +5126,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Pos = FindBestWindowPosForPopup(window); // Clamp position so it stays visible - if (!(flags & ImGuiWindowFlags_ChildWindow)) + // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) { - if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + if (g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); ImVec2 size_for_clamping = ((g.IO.ConfigWindowsMoveFromTitleBarOnly) && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size; @@ -5139,8 +5155,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Apply window focus (new and reactivated windows are moved to front) bool want_focus = false; if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) - if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) + { + if (flags & ImGuiWindowFlags_Popup) want_focus = true; + else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0) + want_focus = true; + } // Handle manual resize: Resize Grips, Borders, Gamepad int border_held = -1; @@ -5149,6 +5169,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); if (!window->Collapsed) UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); + window->ResizeBorderHeld = (signed char)border_held; // Default item width. Make it proportional to window size if window manually resizes if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) @@ -5187,6 +5208,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } // Draw window + handle manual resize + // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame. const float window_rounding = window->WindowRounding; const float window_border_size = window->WindowBorderSize; const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; @@ -5207,8 +5229,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (!(flags & ImGuiWindowFlags_NoBackground)) { ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); + float alpha = 1.0f; if (g.NextWindowData.BgAlphaCond != 0) - bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT); + alpha = g.NextWindowData.BgAlphaVal; + if (alpha != 1.0f) + bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); } g.NextWindowData.BgAlphaCond = 0; @@ -5251,7 +5276,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } // Borders - RenderOuterBorders(window, border_held); + RenderOuterBorders(window); } // Draw navigation selection/windowing rectangle border @@ -5408,7 +5433,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize))); window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); - // After Begin() we fill the last item / hovered data based on title bar data. It is a standard behavior (to allow creation of context menus on title bar only, etc.). + // We fill last item data based on Title Bar, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). + // This is useful to allow creating context menus on title bar only, etc. window->DC.LastItemId = window->MoveId; window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; window->DC.LastItemRect = title_bar_rect; @@ -5428,7 +5454,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); - if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) window->HiddenFramesRegular = 1; @@ -5553,7 +5578,7 @@ void ImGui::FocusWindow(ImGuiWindow* window) g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId g.NavIdIsAlive = false; g.NavLayer = ImGuiNavLayer_Main; - //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", g.FrameCount, window ? window->Name : NULL); + //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL); } // Passing NULL allow to disable keyboard focus @@ -6821,7 +6846,7 @@ void ImGui::ClosePopupToLevel(int remaining, bool apply_focus_to_window_under) // FIXME: This code is faulty and we may want to eventually to replace or remove the 'apply_focus_to_window_under=true' path completely. // Instead of using g.OpenPopupStack[remaining-1].Window etc. we should find the highest root window that is behind the popups we are closing. // The current code will set focus to the parent of the popup window which is incorrect. - // It rarely manifested until now because UpdateMouseMovingWindow() would call FocusWindow() again on the clicked window, + // It rarely manifested until now because UpdateMouseMovingWindowNewFrame() would call FocusWindow() again on the clicked window, // leading to a chain of focusing A (clicked window) then B (parent window of the popup) then A again. // However if the clicked window has the _NoMove flag set we would be left with B focused. // For now, we have disabled this path when called from ClosePopupsOverWindow() because the users of ClosePopupsOverWindow() don't need to alter focus anyway, @@ -8728,6 +8753,9 @@ void ImGui::EndDragDropTarget() //----------------------------------------------------------------------------- // [SECTION] LOGGING/CAPTURING //----------------------------------------------------------------------------- +// All text output from the interface can be captured into tty/file/clipboard. +// By default, tree nodes are automatically opened during logging. +//----------------------------------------------------------------------------- // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) @@ -8931,6 +8959,13 @@ ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) return NULL; } +ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) +{ + if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name, 0))) + return settings; + return CreateNewWindowSettings(name); +} + void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) { size_t file_data_size = 0; diff --git a/imgui.h b/imgui.h index 0d73eea3..c46c1dbd 100644 --- a/imgui.h +++ b/imgui.h @@ -255,7 +255,8 @@ namespace ImGui IMGUI_API bool IsWindowCollapsed(); IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! - IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the window, to append your own drawing primitives + IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API) IMGUI_API ImVec2 GetWindowSize(); // get current window size IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) @@ -1281,7 +1282,7 @@ struct ImGuiIO ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by back-end (imgui_impl_xxx files or custom back-end) to communicate features supported by the back-end. - ImVec2 DisplaySize; // // Main display size, in pixels. For clamping windows positions. + ImVec2 DisplaySize; // // Main display size, in pixels. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file. Set NULL to disable automatic .ini loading/saving, if e.g. you want to manually load/save from memory. @@ -1298,16 +1299,16 @@ struct ImGuiIO float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. - ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. + ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For hi-dpi/retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. ImVec2 DisplayVisibleMin; // // [OBSOLETE] If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. ImVec2 DisplayVisibleMax; // // [OBSOLETE] Just use io.DisplaySize! If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize - // Miscellaneous configuration options + // Miscellaneous options bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations. bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63) bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be the a per-window ImGuiWindowFlags_ResizeFromAnySide flag) - bool ConfigWindowsMoveFromTitleBarOnly;// = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected. + bool ConfigWindowsMoveFromTitleBarOnly; // = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected. //------------------------------------------------------------------ // Platform Functions diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ffdc1060..d22434a2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -338,6 +338,7 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Backend Flags")) { + ShowHelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities."); ImGuiBackendFlags backend_flags = io.BackendFlags; // Make a local copy to avoid modifying the back-end flags. ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); @@ -2806,8 +2807,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::Text("Rounding"); - ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 14.0f, "%.0f"); - ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); diff --git a/imgui_internal.h b/imgui_internal.h index 141c05ca..68690708 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -126,6 +126,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointe #else #define IM_NEWLINE "\n" #endif + #define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) #define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1] #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose @@ -286,14 +287,6 @@ struct IMGUI_API ImPool // Misc data structures //----------------------------------------------------------------------------- -// 1D vector (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) -struct ImVec1 -{ - float x; - ImVec1() { x = 0.0f; } - ImVec1(float _x) { x = _x; } -}; - enum ImGuiButtonFlags_ { ImGuiButtonFlags_None = 0, @@ -352,6 +345,19 @@ enum ImGuiSeparatorFlags_ ImGuiSeparatorFlags_Vertical = 1 << 1 }; +// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). +// This is going to be exposed in imgui.h when stabilized enough. +enum ImGuiItemFlags_ +{ + ImGuiItemFlags_NoTabStop = 1 << 0, // false + ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. + ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211 + ImGuiItemFlags_NoNav = 1 << 3, // false + ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false + ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window + ImGuiItemFlags_Default_ = 0 +}; + // Storage for LastItem data enum ImGuiItemStatusFlags_ { @@ -460,6 +466,15 @@ enum ImGuiPopupPositionPolicy ImGuiPopupPositionPolicy_ComboBox }; +// 1D vector (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) +struct ImVec1 +{ + float x; + ImVec1() { x = 0.0f; } + ImVec1(float _x) { x = _x; } +}; + + // 2D axis aligned bounding-box // NB: we can't rely on ImVec2 math operators being available here struct IMGUI_API ImRect @@ -585,8 +600,8 @@ struct ImGuiWindowSettings struct ImGuiSettingsHandler { - const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' - ImGuiID TypeHash; // == ImHash(TypeName, 0, 0) + const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' + ImGuiID TypeHash; // == ImHashStr(TypeName, 0, 0) void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' @@ -726,6 +741,10 @@ struct ImGuiNextWindowData } }; +//----------------------------------------------------------------------------- +// Tabs +//----------------------------------------------------------------------------- + struct ImGuiTabBarSortItem { int Index; @@ -1010,18 +1029,9 @@ struct ImGuiContext } }; -// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). -// This is going to be exposed in imgui.h when stabilized enough. -enum ImGuiItemFlags_ -{ - ImGuiItemFlags_NoTabStop = 1 << 0, // false - ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. - ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211 - ImGuiItemFlags_NoNav = 1 << 3, // false - ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false - ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window - ImGuiItemFlags_Default_ = 0 -}; +//----------------------------------------------------------------------------- +// ImGuiWindow +//----------------------------------------------------------------------------- // Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. // FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered. @@ -1134,6 +1144,7 @@ struct IMGUI_API ImGuiWindow bool Appearing; // Set during the frame where the window is appearing (or re-appearing) bool Hidden; // Do not display (== (HiddenFramesForResize > 0) || bool HasCloseButton; // Set when the window has a close button (p_open != NULL) + signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) short BeginOrderWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. short BeginOrderWithinContext; // Order within entire imgui context. This is mostly used for debugging submission order related issues. @@ -1317,6 +1328,7 @@ namespace ImGui IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id); + IMGUI_API ImGuiWindowSettings* FindOrCreateWindowSettings(const char* name); IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); // Basic Accessors From cbf24a91518b1005b571b2d362d258e87e3af6db Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 11:04:04 +0100 Subject: [PATCH 004/566] Comments. Fix duplicate entries in About box. Synchronize a few small changes from Master branch. --- imgui.cpp | 22 +++++++++++----------- imgui_demo.cpp | 9 +-------- imgui_internal.h | 2 +- 3 files changed, 13 insertions(+), 20 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 598a41f5..ceda20de 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -884,8 +884,8 @@ CODE (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse) Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows (1 overlay per viewport). - - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData, - and then call your rendered code with your own ImDrawList or ImDrawData data. + - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create + your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls". @@ -3576,7 +3576,7 @@ void ImGui::NewFrame() UpdateViewportsNewFrame(); - // Setup current font, and draw list shared data + // Setup current font and draw list shared data // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! g.IO.Fonts->Locked = true; SetCurrentFont(GetDefaultFont()); @@ -3587,7 +3587,8 @@ void ImGui::NewFrame() g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, virtual_space_max.x, virtual_space_max.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; - // Mark rendering data as invalid to prevent user who may have a handle on it to use it. Setup Overlay draw list for the viewport. + // Setup Overlay draw list for the viewport. + // Mark rendering data as invalid to prevent user who may have a handle on it to use it. for (int n = 0; n < g.Viewports.Size; n++) { ImGuiViewportP* viewport = g.Viewports[n]; @@ -5110,7 +5111,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au } // Apply back modified position/size to window - if (size_target.x != FLT_MAX && (size_target.x != window->SizeFull.x || size_target.y != window->SizeFull.y)) + if (size_target.x != FLT_MAX) { window->SizeFull = size_target; MarkIniSettingsDirty(window); @@ -5451,9 +5452,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) MarkIniSettingsDirty(window); } - //if (window->DockNode && window->DockIsActive) - // size_full_modified = window->SizeFull; - // Apply minimum/maximum window size constraints and final size window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull); window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; @@ -5596,7 +5594,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { if (flags & ImGuiWindowFlags_Popup) want_focus = true; - else if ((window->DockIsActive || !(flags & ImGuiWindowFlags_ChildWindow)) && !(flags & ImGuiWindowFlags_Tooltip)) + else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip)) want_focus = true; } @@ -11398,10 +11396,9 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w node->IsFocused = is_focused; if (is_focused) node->LastFrameFocused = g.FrameCount; - - // Notify root of visible window (used to display title in OS task bar) if (node->VisibleWindow) { + // Notify root of visible window (used to display title in OS task bar) if (is_focused || root_node->VisibleWindow == NULL) root_node->VisibleWindow = node->VisibleWindow; if (node->TabBar) @@ -13173,6 +13170,9 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings //----------------------------------------------------------------------------- // [SECTION] LOGGING/CAPTURING //----------------------------------------------------------------------------- +// All text output from the interface can be captured into tty/file/clipboard. +// By default, tree nodes are automatically opened during logging. +//----------------------------------------------------------------------------- // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f001fff2..65262805 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2729,9 +2729,6 @@ void ImGui::ShowAboutWindow(bool* p_open) #endif #ifdef IMGUI_HAS_DOCK ImGui::Text("define: IMGUI_HAS_DOCK"); -#endif -#ifdef IMGUI_HAS_TABS - ImGui::Text("define: IMGUI_HAS_TABS"); #endif ImGui::Separator(); ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL"); @@ -2756,10 +2753,6 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.ConfigDockingWithShift) ImGui::Text("io.ConfigDockingWithShift"); if (io.ConfigDockingTabBarOnSingleWindows) ImGui::Text("io.ConfigDockingTabBarOnSingleWindows"); if (io.ConfigDockingTransparentPayload) ImGui::Text("io.ConfigDockingTransparentPayload"); - if (io.ConfigViewportsNoAutoMerge) ImGui::Text("io.ConfigViewportsNoAutoMerge"); - if (io.ConfigViewportsNoTaskBarIcon) ImGui::Text("io.ConfigViewportsNoTaskBarIcon"); - if (io.ConfigViewportsNoDecoration) ImGui::Text("io.ConfigViewportsNoDecoration"); - if (io.ConfigViewportsNoParent) ImGui::Text("io.ConfigViewportsNoParent"); if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors"); if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); @@ -4263,7 +4256,7 @@ void ShowExampleAppDocuments(bool* p_open) return; } - // Menu Bar + // Menu if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("File")) diff --git a/imgui_internal.h b/imgui_internal.h index 2f6600af..ea79bc7f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -352,7 +352,7 @@ enum ImGuiSeparatorFlags_ ImGuiSeparatorFlags_Vertical = 1 << 1 }; -// Transient per-window ItemFlags, reset at the beginning of the frame. For child windows: inherited from parent on first Begin(). +// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). // This is going to be exposed in imgui.h when stabilized enough. enum ImGuiItemFlags_ { From 65a2350a5f41447ad630d16de1ec6f0e365d0f1c Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 11:12:37 +0100 Subject: [PATCH 005/566] Docking: Extracted code into a DocknodeUpdateTabListMenu() functions + minor other changes. --- imgui.cpp | 80 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 41 insertions(+), 39 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ceda20de..b67fa92d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10204,6 +10204,7 @@ namespace ImGui static void DockNodeUpdate(ImGuiDockNode* node); static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node); static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window); + static ImGuiID DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar); static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node); static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window); static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window); @@ -11370,6 +11371,36 @@ static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* r return (a->BeginOrderWithinContext - b->BeginOrderWithinContext); } +static ImGuiID ImGui::DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar) +{ + // Try to position the menu so it is more likely to stays within the same viewport + ImGuiID ret_tab_id = 0; + SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight())); + if (BeginPopup("#TabListMenu")) + { + node->IsFocused = true; + if (tab_bar->Tabs.Size == 1) + { + if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar)) + node->WantHiddenTabBarToggle = true; + } + else + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + IM_ASSERT(tab->Window != NULL); + if (Selectable(tab->Window->Name, tab->ID == tab_bar->SelectedTabId)) + ret_tab_id = tab->ID; + SameLine(); + Text(" "); + } + } + EndPopup(); + } + return ret_tab_id; +} + static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window) { ImGuiContext& g = *GImGui; @@ -11423,38 +11454,17 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w tab_bar = node->TabBar = IM_NEW(ImGuiTabBar)(); ImGuiID focus_tab_id = 0; + node->IsFocused = is_focused; // Collapse button changes shape and display a list if (IsPopupOpen("#TabListMenu")) { - // Try to position the menu so it is more likely to stays within the same viewport - SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight())); - if (BeginPopup("#TabListMenu")) - { - is_focused = true; - if (tab_bar->Tabs.Size == 1) - { - if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar)) - node->WantHiddenTabBarToggle = true; - } - else - { - for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) - { - ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - IM_ASSERT(tab->Window != NULL); - if (Selectable(tab->Window->Name, tab->ID == tab_bar->SelectedTabId)) - focus_tab_id = tab_bar->NextSelectedTabId = tab->ID; - SameLine(); - Text(" "); - } - } - EndPopup(); - } + if (ImGuiID tab_id = DockNodeUpdateTabListMenu(node, tab_bar)) + focus_tab_id = tab_bar->NextSelectedTabId = tab_id; + is_focused |= node->IsFocused; } // Title bar - node->IsFocused = is_focused; if (is_focused) node->LastFrameFocused = g.FrameCount; ImRect title_bar_rect = ImRect(node->Pos, node->Pos + ImVec2(node->Size.x, g.FontSize + style.FramePadding.y * 2.0f)); @@ -12134,10 +12144,10 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) // [DEBUG] Render limits ImDrawList* draw_list = node->HostWindow ? GetOverlayDrawList(node->HostWindow) : GetOverlayDrawList((ImGuiViewportP*)GetMainViewport()); for (int n = 0; n < 2; n++) - if (axis == ImGuiAxis_X) - draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f); - else - draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f); + if (axis == ImGuiAxis_X) + draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f); + else + draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f); */ } @@ -12156,7 +12166,6 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) // Lock the size of every node that is a sibling of the node we are touching // This might be less desirable if we can merge sibling of a same axis into the same parental level. -#if 1 for (int side_n = 0; side_n < 2; side_n++) for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++) { @@ -12176,7 +12185,6 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) touching_node = touching_node->ParentNode; } } -#endif DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size); DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size); @@ -12767,7 +12775,6 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) ImGuiContext& g = *ctx; const bool auto_dock_node = (g.IO.ConfigDockingTabBarOnSingleWindows) && !(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)); - if (auto_dock_node) { if (window->DockId == 0) @@ -12861,7 +12868,6 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) window->DockTabIsVisible = false; return; } - IM_ASSERT(node->HostWindow); IM_ASSERT(node->IsLeafNode()); @@ -12869,7 +12875,6 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) SetNextWindowPos(node->Pos); SetNextWindowSize(node->Size); g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos() - window->DockIsActive = true; window->DockTabIsVisible = false; if (node->Flags & ImGuiDockNodeFlags_KeepAliveOnly) @@ -12931,7 +12936,6 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); if (!g.DragDropActive) return; - if (!BeginDragDropTargetCustom(window->Rect(), window->ID)) return; @@ -13027,7 +13031,7 @@ static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ } } -static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id) +static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id) { // FIXME-OPT ImGuiDockContext* dc = ctx->DockContext; @@ -13126,9 +13130,7 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings buf->appendf("[%s][Data]\n", handler->TypeName); for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++) { -#if IMGUI_DEBUG_DOCKING_INI - const int line_start_pos = buf->size(); -#endif + const int line_start_pos = buf->size(); (void)line_start_pos; const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n]; buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", node_settings->IsDockSpace ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file buf->appendf(" ID=0x%08X", node_settings->ID); From e30babef093319d2a5e5511e12b01d528dc86046 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 11:22:53 +0100 Subject: [PATCH 006/566] Fixed Clang/Win32 warning. --- imgui_internal.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index ea79bc7f..936e44a6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -85,6 +85,7 @@ struct ImGuiWindowSettings; // Storage for window settings stored in .in // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical +typedef int ImGuiDataAutority; // -> enum ImGuiDataAutority_ // Enum: for storing the source autority (dock node vs window) of a field typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags @@ -818,7 +819,7 @@ enum ImGuiDockNodeFlagsPrivate_ ImGuiDockNodeFlags_Dockspace = 1 << 10 }; -enum ImGuiDataAutority +enum ImGuiDataAutority_ { ImGuiDataAutority_Auto, ImGuiDataAutority_DockNode, From 0d4a2a2cd01c205d5ed12e2beb9861a46541d163 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 12:04:42 +0100 Subject: [PATCH 007/566] Internals: Track ActiveIdHasBeenPressed (similar to ActiveIdHasBeenEdited). This is currently mostly for the benefit of the range_select branch. (#1861) --- imgui.cpp | 1 + imgui_internal.h | 7 +++++-- imgui_widgets.cpp | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ba54366e..b38c50aa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2636,6 +2636,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) if (g.ActiveIdIsJustActivated) { g.ActiveIdTimer = 0.0f; + g.ActiveIdHasBeenPressed = false; g.ActiveIdHasBeenEdited = false; if (id != 0) { diff --git a/imgui_internal.h b/imgui_internal.h index 68690708..76c3ce51 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -423,7 +423,7 @@ enum ImGuiNavHighlightFlags_ ImGuiNavHighlightFlags_None = 0, ImGuiNavHighlightFlags_TypeDefault = 1 << 0, ImGuiNavHighlightFlags_TypeThin = 1 << 1, - ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, + ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, // Draw rectangular highlight if (g.NavId == id) _even_ when using the mouse. ImGuiNavHighlightFlags_NoRounding = 1 << 3 }; @@ -792,6 +792,7 @@ struct ImGuiContext float ActiveIdTimer; bool ActiveIdIsJustActivated; // Set at the time of activation for one frame bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) + bool ActiveIdHasBeenPressed; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. bool ActiveIdHasBeenEdited; // Was the value associated to the widget Edited over the course of the Active state. bool ActiveIdPreviousFrameIsAlive; bool ActiveIdPreviousFrameHasBeenEdited; @@ -897,7 +898,8 @@ struct ImGuiContext ImVector PrivateClipboard; // If no custom clipboard handler is defined // Platform support - ImVec2 PlatformImePos, PlatformImeLastPos; // Cursor position request & last passed to the OS Input Method Editor + ImVec2 PlatformImePos; // Cursor position request & last passed to the OS Input Method Editor + ImVec2 PlatformImeLastPos; // Settings bool SettingsLoaded; @@ -948,6 +950,7 @@ struct ImGuiContext ActiveIdTimer = 0.0f; ActiveIdIsJustActivated = false; ActiveIdAllowOverlap = false; + ActiveIdHasBeenPressed = false; ActiveIdHasBeenEdited = false; ActiveIdPreviousFrameIsAlive = false; ActiveIdPreviousFrameHasBeenEdited = false; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index feeb3f9e..283a17d2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -507,6 +507,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool bool held = false; if (g.ActiveId == id) { + if (pressed) + g.ActiveIdHasBeenPressed = true; if (g.ActiveIdSource == ImGuiInputSource_Mouse) { if (g.ActiveIdIsJustActivated) From d5945aa25b19fb5ef4cc834df1f6f393d2358dc3 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 12:11:27 +0100 Subject: [PATCH 008/566] Internals: Minor changes to TreeNodeBehavior() and Selectable() for the benefit of fhe range_select branch. (#1861) --- imgui_widgets.cpp | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 283a17d2..36cc5fbe 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4811,20 +4811,24 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l } // Flags that affects opening behavior: - // - 0(default) ..................... single-click anywhere to open + // - 0 (default) .................... single-click anywhere to open // - OpenOnDoubleClick .............. double-click anywhere to open // - OpenOnArrow .................... single-click on arrow to open // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open - ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0); - if (!is_leaf) - button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; + ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers; + if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) + button_flags |= ImGuiButtonFlags_AllowItemOverlap; if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); + if (!is_leaf) + button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; - bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; + bool hovered, held; + bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + bool toggled = false; if (!is_leaf) { - bool toggled = false; if (pressed) { toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id); @@ -4859,11 +4863,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y); + ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin; if (display_frame) { // Framed type RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding); - RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin); + RenderNavHighlight(frame_bb, id, nav_highlight_flags); RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); if (g.LogEnabled) { @@ -4882,10 +4887,10 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l else { // Unframed typed for tree nodes - if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) + if (hovered || selected) { RenderFrame(frame_bb.Min, frame_bb.Max, col, false); - RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin); + RenderNavHighlight(frame_bb, id, nav_highlight_flags); } if (flags & ImGuiTreeNodeFlags_Bullet) @@ -5065,11 +5070,11 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (flags & ImGuiSelectableFlags_PressedOnRelease) button_flags |= ImGuiButtonFlags_PressedOnRelease; if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; - bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); if (flags & ImGuiSelectableFlags_Disabled) selected = false; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets) if (pressed || hovered) if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent) From 5cb7040f667b30cc4112bb4b98b545200e6c8598 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 12:14:12 +0100 Subject: [PATCH 009/566] Internals: Tracking dummy select scope id (currently always zero) to facilitate merging of the range_select branch. (#1861) --- imgui.cpp | 9 ++++++++- imgui_internal.h | 19 ++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b38c50aa..1ae667b1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7321,6 +7321,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con if (new_best) { result->ID = id; + result->SelectScopeId = g.MultiSelectScopeId; result->Window = window; result->RectRel = nav_bb_rel; } @@ -7332,6 +7333,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con { result = &g.NavMoveResultLocalVisibleSet; result->ID = id; + result->SelectScopeId = g.MultiSelectScopeId; result->Window = window; result->RectRel = nav_bb_rel; } @@ -7872,8 +7874,13 @@ static void ImGui::NavUpdateMoveResult() ClearActiveID(); g.NavWindow = result->Window; + if (g.NavId != result->ID) + { + // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId) + g.NavJustMovedToId = result->ID; + g.NavJustMovedToSelectScopeId = result->SelectScopeId; + } SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel); - g.NavJustMovedToId = result->ID; g.NavMoveFromClampedRefRect = false; } diff --git a/imgui_internal.h b/imgui_internal.h index 76c3ce51..eb6d1e76 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -691,6 +691,7 @@ struct ImDrawDataBuilder struct ImGuiNavMoveResult { ImGuiID ID; // Best candidate + ImGuiID SelectScopeId;// Best candidate window current selectable group ID ImGuiWindow* Window; // Best candidate window float DistBox; // Best candidate box distance to current NavId float DistCenter; // Best candidate center distance to current NavId @@ -698,7 +699,7 @@ struct ImGuiNavMoveResult ImRect RectRel; // Best candidate bounding box in window relative space ImGuiNavMoveResult() { Clear(); } - void Clear() { ID = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); } + void Clear() { ID = SelectScopeId = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); } }; // Storage for SetNexWindow** functions @@ -823,8 +824,9 @@ struct ImGuiContext ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0 ImGuiID NavInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0 ImGuiID NavJustTabbedId; // Just tabbed to this id. - ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest) - ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame + ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). + ImGuiID NavJustMovedToSelectScopeId; // Just navigated to this select scope id (result of a successfully MoveRequest). + ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard. ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring. int NavScoringCount; // Metrics for debugging @@ -897,6 +899,10 @@ struct ImGuiContext int TooltipOverrideCount; ImVector PrivateClipboard; // If no custom clipboard handler is defined + // Range-Select/Multi-Select + // [This is unused in this branch, but left here to facilitate merging/syncing multiple branches] + ImGuiID MultiSelectScopeId; + // Platform support ImVec2 PlatformImePos; // Cursor position request & last passed to the OS Input Method Editor ImVec2 PlatformImeLastPos; @@ -968,7 +974,7 @@ struct ImGuiContext NavWindow = NULL; NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0; - NavJustTabbedId = NavJustMovedToId = NavNextActivateId = 0; + NavJustTabbedId = NavJustMovedToId = NavJustMovedToSelectScopeId = NavNextActivateId = 0; NavInputSource = ImGuiInputSource_None; NavScoringRectScreen = ImRect(); NavScoringCount = 0; @@ -1014,6 +1020,9 @@ struct ImGuiContext DragSpeedDefaultRatio = 1.0f / 100.0f; ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); TooltipOverrideCount = 0; + + MultiSelectScopeId = 0; + PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX); SettingsLoaded = false; @@ -1352,7 +1361,7 @@ namespace ImGui IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL); IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id); IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); - IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop = true); // Return true if focus is requested + IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop = true); // Return true if focus is requested IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); From 5fc6899dc24c5ff9c01d866926bc64351fdc761a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 15:13:54 +0100 Subject: [PATCH 010/566] Examples: OpenGL3: Using GLSL 4.10 shaders for any GLSL version over 410 (e.g. 430, 450). (#2329) [@BrutPitt] --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_opengl3.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1df96435..b255fd18 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,7 @@ Other Changes: - Examples: Win32: Added support for XInput games (if ImGuiConfigFlags_NavEnableGamepad is enabled). - Examples: Win32: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. (#2264) - Examples: DirectX9: Explicitly disable fog (D3DRS_FOGENABLE) before drawing in case user state has it set. (#2288, #2230) +- Examples: OpenGL3: Using GLSL 4.10 shaders for any GLSL version over 410 (e.g. 430, 450). (#2329) [@BrutPitt] ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 14a8964a..f217ecf4 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -11,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT). // 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used. @@ -477,7 +478,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() vertex_shader = vertex_shader_glsl_120; fragment_shader = fragment_shader_glsl_120; } - else if (glsl_version == 410) + else if (glsl_version >= 410) { vertex_shader = vertex_shader_glsl_410_core; fragment_shader = fragment_shader_glsl_410_core; From 03b0266b5921a5191ca33961ceb17d5b74b698f1 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 15:23:25 +0100 Subject: [PATCH 011/566] Examples: Made imgui_impl_win32 drag gdi32.lib for GetDeviceCaps(). (#2327) --- examples/imgui_impl_win32.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 7b60dd1b..f34d8405 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -447,6 +447,10 @@ void ImGui_ImplWin32_EnableDpiAwareness() } } +#ifdef _MSC_VER +#pragma comment(lib, "gdi32") // GetDeviceCaps() +#endif + float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { UINT xdpi = 96, ydpi = 96; From ac6d474103af7f07dc983a63cb25d1ed2f1168ac Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 16:37:07 +0100 Subject: [PATCH 012/566] Removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 4 +--- imgui.h | 2 -- imgui_demo.cpp | 1 + 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b255fd18..06a1b45e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -33,6 +33,10 @@ HOW TO UPDATE? VERSION 1.68 (In progress) ----------------------------------------------------------------------- +Breaking Changes: + +- Removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). + Other Changes: - Added .editorconfig file for text editors to standardize using spaces. (#2038) [@kudaba] - InputText: Fixed a bug where ESCAPE would not restore the initial value in all situations. (#2321) [@relick] diff --git a/imgui.cpp b/imgui.cpp index 1ae667b1..994621ec 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -364,6 +364,7 @@ CODE When you are not sure about a 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. + - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete). - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects. @@ -1167,7 +1168,6 @@ ImGuiIO::ImGuiIO() FontDefault = NULL; FontAllowUserScaling = false; DisplayFramebufferScale = ImVec2(1.0f, 1.0f); - DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f); // Miscellaneous options MouseDrawCursor = false; @@ -4307,8 +4307,6 @@ ImVec2 ImGui::GetItemRectSize() static ImRect GetViewportRect() { ImGuiContext& g = *GImGui; - if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) - return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } diff --git a/imgui.h b/imgui.h index c46c1dbd..a5c48597 100644 --- a/imgui.h +++ b/imgui.h @@ -1300,8 +1300,6 @@ struct ImGuiIO bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For hi-dpi/retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. - ImVec2 DisplayVisibleMin; // // [OBSOLETE] If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. - ImVec2 DisplayVisibleMax; // // [OBSOLETE] Just use io.DisplaySize! If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize // Miscellaneous options bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d22434a2..e0eaf216 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2687,6 +2687,7 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::Separator(); ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); + ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); ImGui::Separator(); ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y); ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize); From e215809c4d06397bbe1da71d51087967b8ded68f Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Feb 2019 16:37:07 +0100 Subject: [PATCH 013/566] Removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 4 ++-- imgui_demo.cpp | 1 + 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b4669fb1..f937c4cd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -97,6 +97,10 @@ Other changes: VERSION 1.68 (In progress) ----------------------------------------------------------------------- +Breaking Changes: + +- Removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). + Other Changes: - Added .editorconfig file for text editors to standardize using spaces. (#2038) [@kudaba] - InputText: Fixed a bug where ESCAPE would not restore the initial value in all situations. (#2321) [@relick] diff --git a/imgui.cpp b/imgui.cpp index 61ee26c5..92c2694b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -373,9 +373,9 @@ CODE - likewise io.MousePos and GetMousePos() will use OS coordinates. If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos. - 2018/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api. - - 2018/XX/XX (1.XX) - removed io.DisplayVisibleMin, io.DisplayVisibleMax settings (they were used to clip within the (0,0)..DisplaySize range, I don't know of anyone using it) - + + - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete). - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 65262805..c6df1628 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2767,6 +2767,7 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::Separator(); ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); + ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); ImGui::Separator(); ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y); ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize); From f087359621d27b808e363670d52cd7ad14be5675 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 3 Feb 2019 13:54:04 +0100 Subject: [PATCH 014/566] Revert part of change from 5536eded. Fixed drag and drop in docking branch. (#2331, reopening #2325) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 92c2694b..f47be8d6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4297,7 +4297,7 @@ static void FindHoveredWindow() g.HoveredWindow = hovered_window; g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; - g.HoveredWindowUnderMovingWindow = g.MovingWindow ? hovered_window_ignoring_moving_window : NULL; + g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window; if (g.MovingWindow) g.MovingWindow->Viewport = moving_window_viewport; From c23a19c26fa9cc778f755e76799f0cafdcb5a13b Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 3 Feb 2019 17:29:51 +0100 Subject: [PATCH 015/566] Internals: Exposed internal SetWindowPos to imgui_internal.h (for imgui-test) --- imgui.cpp | 9 +++------ imgui_internal.h | 3 +++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 994621ec..04a80b71 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -990,9 +990,6 @@ static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduc //------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window); -static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond); -static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond); -static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); static void CheckStacksSize(ImGuiWindow* window, bool write); @@ -6035,7 +6032,7 @@ void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) window->DC.CursorMaxPos.y -= window->Scroll.y; } -static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) +void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) @@ -6070,7 +6067,7 @@ ImVec2 ImGui::GetWindowSize() return window->Size; } -static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond) +void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) @@ -6113,7 +6110,7 @@ void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) SetWindowSize(window, size, cond); } -static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond) +void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) diff --git a/imgui_internal.h b/imgui_internal.h index eb6d1e76..947b2f1d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1321,6 +1321,9 @@ namespace ImGui IMGUI_API float GetWindowScrollMaxX(ImGuiWindow* window); IMGUI_API float GetWindowScrollMaxY(ImGuiWindow* window); IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); + IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond); + IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond); + IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond); IMGUI_API void SetCurrentFont(ImFont* font); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } From 80d51c692a6661f06ad193d5df05fe32cede4b65 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 3 Feb 2019 18:44:30 +0100 Subject: [PATCH 016/566] Docking: Fixed dragging docked window with _NoMove flag (#2325) --- imgui.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b124b7f7..593db341 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5925,8 +5925,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginAsDockableDragDropSource() also overwrites it. if ((g.ActiveId == window->MoveId) && ((g.IO.ConfigDockingWithShift && g.IO.KeyShift) || (!g.IO.ConfigDockingWithShift))) - if ((window->RootWindow->Flags & (ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking)) == 0) - BeginAsDockableDragDropSource(window); + if ((window->Flags & ImGuiWindowFlags_NoMove) == 0) + if ((window->RootWindow->Flags & (ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking)) == 0) + BeginAsDockableDragDropSource(window); // Docking: Any dockable window can act as a target. For dock node hosts we call BeginAsDockableDragDropTarget() in DockNodeUpdate() instead. if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking)) From f902435a538cf336ade6b9d4ddafb0b467df0443 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 3 Feb 2019 18:58:07 +0100 Subject: [PATCH 017/566] Docking: Fixed less of node size/pos caused by 1f2bdd37 (#2109) --- imgui.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 593db341..975f8dd7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10770,7 +10770,8 @@ ImGuiDockNode::ImGuiDockNode(ImGuiID id) LastFocusedNodeID = 0; SelectedTabID = 0; WantCloseTabID = 0; - AutorityForPos = AutorityForSize = AutorityForViewport = ImGuiDataAutority_Auto; + AutorityForPos = AutorityForSize = ImGuiDataAutority_DockNode; + AutorityForViewport = ImGuiDataAutority_Auto; IsVisible = true; IsFocused = IsCentralNode = IsHiddenTabBar = HasCloseButton = HasCollapseButton = false; WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; @@ -11257,12 +11258,14 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) // after the dock host window, losing their top-most status. if (node->HostWindow->Appearing) BringWindowToDisplayFront(node->HostWindow); + + node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto; } else if (node->ParentNode) { node->HostWindow = host_window = node->ParentNode->HostWindow; + node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto; } - node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto; if (node->WantMouseMove && node->HostWindow) DockNodeStartMouseMovingWindow(node, node->HostWindow); } From 8e44aacc8e14d6791cb634e324ed488620ee3c65 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 Feb 2019 14:38:35 +0100 Subject: [PATCH 018/566] Fonts: Fixed crash if FontGlobalScale is zero. Correctly debug naming default font if not 13 px. Demo: Moved PopupRounding along with other rounding values. Metrics: Displaying indexes with idx to be correct / less misleading. --- imgui.cpp | 14 ++++++++------ imgui_demo.cpp | 11 ++++++----- imgui_draw.cpp | 6 ++++-- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 04a80b71..4822a09b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1124,7 +1124,6 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) PopupRounding = ImFloor(PopupRounding * scale_factor); FramePadding = ImFloor(FramePadding * scale_factor); FrameRounding = ImFloor(FrameRounding * scale_factor); - TabRounding = ImFloor(TabRounding * scale_factor); ItemSpacing = ImFloor(ItemSpacing * scale_factor); ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor); TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor); @@ -1134,6 +1133,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); + TabRounding = ImFloor(TabRounding * scale_factor); DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); @@ -5661,7 +5661,7 @@ void ImGui::SetCurrentFont(ImFont* font) IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; - g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; + g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; ImFontAtlas* atlas = g.Font->ContainerAtlas; @@ -9329,16 +9329,18 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) - for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) + for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) { char buf[300]; char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangles_pos[3]; - for (int n = 0; n < 3; n++, vtx_i++) + for (int n = 0; n < 3; n++, idx_i++) { - ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; + int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i; + ImDrawVert& v = draw_list->VtxBuffer[vtx_i]; triangles_pos[n] = v.pos; - buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", + (n == 0) ? "idx" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); } ImGui::Selectable(buf, false); if (ImGui::IsItemHovered()) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e0eaf216..2b2da8f3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2793,7 +2793,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGui::Text("Main"); ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 16.0f, "%.0f"); ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); @@ -2811,6 +2810,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"); + ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); @@ -2882,7 +2882,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::BeginTabItem("Fonts")) { - ImFontAtlas* atlas = ImGui::GetIO().Fonts; + ImGuiIO& io = ImGui::GetIO(); + ImFontAtlas* atlas = io.Fonts; ShowHelpMarker("Read FAQ and misc/fonts/README.txt for details on font loading."); ImGui::PushItemWidth(120); for (int i = 0; i < atlas->Fonts.Size; i++) @@ -2890,7 +2891,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImFont* font = atlas->Fonts[i]; ImGui::PushID(font); bool font_details_opened = ImGui::TreeNode(font, "Font %d: \"%s\"\n%.2f px, %d glyphs, %d file(s)", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); - ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) ImGui::GetIO().FontDefault = font; + ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; } if (font_details_opened) { ImGui::PushFont(font); @@ -2955,9 +2956,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) } static float window_scale = 1.0f; - if (ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f")) // scale only this window + if (ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.2f")) // scale only this window ImGui::SetWindowFontScale(window_scale); - ImGui::DragFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale everything + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.2f"); // scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index b73299b1..8e694d9f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1592,8 +1592,10 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) font_cfg.OversampleH = font_cfg.OversampleV = 1; font_cfg.PixelSnapH = true; } - if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "ProggyClean.ttf, 13px"); - if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f; + if (font_cfg.SizePixels <= 0.0f) + font_cfg.SizePixels = 13.0f * 1.0f; + if (font_cfg.Name[0] == '\0') + ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault(); From 0b05ba18df11b88035fd6f23728091cc2ae67fcd Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 Feb 2019 22:36:46 +0100 Subject: [PATCH 019/566] Internals: DragScalar, SliderScalar: Calling ItemSize before ItemAdd as with every other widgets so we can more easily rearrange the signature of ItemXXX functions (toward allowing non-rounded sizes for scaling and flow layout). --- imgui_widgets.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 36cc5fbe..cd38456d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1876,12 +1876,10 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); - // NB- we don't call ItemSize() yet because we may turn into a text edit box below + ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb)) - { - ItemSize(total_bb, style.FramePadding.y); return false; - } + const bool hovered = ItemHoverable(frame_bb, id); // Default format string when passing NULL @@ -1909,12 +1907,12 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) { + window->DC.CursorPos = frame_bb.Min; FocusableItemUnregister(window); return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); } // Actual drag behavior - ItemSize(total_bb, style.FramePadding.y); const bool value_changed = DragBehavior(id, data_type, v, v_speed, v_min, v_max, format, power, ImGuiDragFlags_None); if (value_changed) MarkItemEdited(id); @@ -2311,12 +2309,9 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); - // NB- we don't call ItemSize() yet because we may turn into a text edit box below + ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb)) - { - ItemSize(total_bb, style.FramePadding.y); return false; - } // Default format string when passing NULL // Patch old "%.0f" format string to use "%d", read function comments for more details. @@ -2344,12 +2339,11 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) { + window->DC.CursorPos = frame_bb.Min; FocusableItemUnregister(window); return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); } - ItemSize(total_bb, style.FramePadding.y); - // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); From f7c879eb6034dbc1aa223b2af31c8bd66ccd32e5 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 Feb 2019 23:19:19 +0100 Subject: [PATCH 020/566] RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). + Internals: Checkbox, RadioButton: Single call to ItemSize() for flow layout purpose. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 58 ++++++++++++++++------------------------------ 2 files changed, 21 insertions(+), 38 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 06a1b45e..ea94b323 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,7 @@ Other Changes: - InputText: Fixed a bug where ESCAPE would be first captured by the Keyboard Navigation code. (#2321, #787) - Fixed range-version of PushID() and GetID() not honoring the ### operator to restart from the seed value. - Fixed CloseCurrentPopup() on a child-menu of a modal incorrectly closing the modal. (#2308) +- RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). - Window: When resizing from an edge, the border is more visible and better follow the rounded corners. - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" with a small number of segments (e.g. an hexagon). (#2287) [@baktery] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cd38456d..eea0e610 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -895,19 +895,11 @@ bool ImGui::Checkbox(const char* label, bool* v) const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); // We want a square shape to we use Y twice - ItemSize(check_bb, style.FramePadding.y); - - ImRect total_bb = check_bb; - if (label_size.x > 0) - SameLine(0, style.ItemInnerSpacing.x); - const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); - if (label_size.x > 0) - { - ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); - total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); - } - + const float square_sz = GetFrameHeight(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); + const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); + ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id)) return false; @@ -923,15 +915,14 @@ bool ImGui::Checkbox(const char* label, bool* v) RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); if (*v) { - const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); - const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); - RenderCheckMark(check_bb.Min + ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad*2.0f); + const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f)); + RenderCheckMark(check_bb.Min + ImVec2(pad, pad), GetColorU32(ImGuiCol_CheckMark), square_sz - pad*2.0f); } if (g.LogEnabled) - LogRenderedText(&text_bb.Min, *v ? "[x]" : "[ ]"); + LogRenderedText(&total_bb.Min, *v ? "[x]" : "[ ]"); if (label_size.x > 0.0f) - RenderText(text_bb.Min, label); + RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return pressed; @@ -963,26 +954,18 @@ bool ImGui::RadioButton(const char* label, bool active) const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); - ItemSize(check_bb, style.FramePadding.y); - - ImRect total_bb = check_bb; - if (label_size.x > 0) - SameLine(0, style.ItemInnerSpacing.x); - const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); - if (label_size.x > 0) - { - ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); - total_bb.Add(text_bb); - } - + const float square_sz = GetFrameHeight(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); + const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); + ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id)) return false; ImVec2 center = check_bb.GetCenter(); center.x = (float)(int)center.x + 0.5f; center.y = (float)(int)center.y + 0.5f; - const float radius = check_bb.GetHeight() * 0.5f; + const float radius = (square_sz - 1.0f) * 0.5f; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); @@ -993,21 +976,20 @@ bool ImGui::RadioButton(const char* label, bool active) window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); if (active) { - const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); - const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); - window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); + const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16); } if (style.FrameBorderSize > 0.0f) { - window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); + window->DrawList->AddCircle(center + ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize); } if (g.LogEnabled) - LogRenderedText(&text_bb.Min, active ? "(x)" : "( )"); + LogRenderedText(&total_bb.Min, active ? "(x)" : "( )"); if (label_size.x > 0.0f) - RenderText(text_bb.Min, label); + RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label); return pressed; } From 65c972e9e42ae69f66dfebe0a51005a6509b6c00 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 11:45:19 +0100 Subject: [PATCH 021/566] Update README.md --- docs/README.md | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/docs/README.md b/docs/README.md index a6c4b416..dd7aa18a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -145,7 +145,7 @@ Frameworks: - Ogre: [ogreimgui](https://bitbucket.org/LMCrashy/ogreimgui/src) - OpenFrameworks: [ofxImGui](https://github.com/jvcleave/ofxImGui) - OpenSceneGraph/OSG: [gist](https://gist.github.com/fulezi/d2442ca7626bf270226014501357042c) -- ORX: [pr #1843](https://github.com/ocornut/imgui/pull/1843) +- ORX: [#1843](https://github.com/ocornut/imgui/pull/1843) - LÖVE+Lua: [love-imgui](https://github.com/slages/love-imgui) - Magnum: [ImGuiIntegration](https://doc.magnum.graphics/magnum/namespaceMagnum_1_1ImGuiIntegration.html) ([example](https://doc.magnum.graphics/magnum/examples-imgui.html)) - NanoRT: [syoyo/imgui](https://github.com/syoyo/imgui/tree/nanort) @@ -159,8 +159,8 @@ For other bindings: see [Bindings](https://github.com/ocornut/imgui/wiki/Binding Roadmap ------- Some of the goals for 2019 are: -- Finish work on docking, tabs. (see [#2109](https://github.com/ocornut/imgui/issues/2109), public branch looking for feedback) -- Finish work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), public branch looking for feedback) +- Finish work on docking, tabs. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public `docking` branch looking for feedback) +- Finish work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public `docking` branch looking for feedback) - Finish work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) - Add an automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) - Make Columns better. (they are currently pretty terrible!) @@ -177,7 +177,6 @@ User screenshots:
[Gallery Part 6](https://github.com/ocornut/imgui/issues/1607) (Feb 2018 to June 2018)
[Gallery Part 7](https://github.com/ocornut/imgui/issues/1902) (June 2018 to January 2019)
[Gallery Part 8](https://github.com/ocornut/imgui/issues/2265) (January 2019 onward) -
Also see the [Mega screenshots](https://github.com/ocornut/imgui/issues/1273) for an idea of the available features. Custom engine [![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) @@ -204,12 +203,14 @@ The Immediate Mode GUI paradigm may at first appear unusual to some users. This See the [Wiki](https://github.com/ocornut/imgui/wiki) for more references and [Bindings](https://github.com/ocornut/imgui/wiki/Bindings) for third-party bindings to different languages and frameworks. -Support Forums --------------- +Support +------- + +If you are new to Dear ImGui and have issues with: compiling, linking, adding fonts, wiring inputs, running or displaying Dear ImGui: please post on the Discourse forums: https://discourse.dearimgui.org. -If you have issues with: compiling, linking, adding fonts, running or displaying Dear ImGui, or wiring inputs: please post on the Discourse forums: https://discourse.dearimgui.org. +Otherwise for any other questions, bug reports, requests, feedback, you may post on https://github.com/ocornut/imgui/issues. Please read and fill the New Issue template carefully. -For any other questions, bug reports, requests, feedback, you may post on https://github.com/ocornut/imgui/issues. Please read and fill the New Issue template carefully. +Private support is available for paying customers. Frequently Asked Question (FAQ) ------------------------------- @@ -226,7 +227,7 @@ Frequently Asked Question (FAQ) I occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. -You may also peak at the [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) branches. Even though they are marked beta, several projects are using them and they are kept in sync with master regularly. +You may also peak at the [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features in the `docking` branch. Several projects are using this branch and it is kept in sync with master regularly. **Who uses Dear ImGui?** @@ -234,7 +235,7 @@ See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) and [Software usi **Why the odd dual naming, "Dear ImGui" vs "ImGui"?** -The library started its life and is best known as "ImGui" only due to the fact that I didn't give it a proper name when I released it. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations. It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "dear imgui" that people can use to refer to this specific library in ambiguous situations. +The library started its life as "ImGui" due to the fact that I didn't give it a proper name when I released 1.0 and had no particular expectation that it would taker off. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations (e.g. Unity uses it own implementation of the IMGUI paradigm). It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "Dear ImGui" that people can use to refer to this specific library in ambiguous situations. Please try to refer to it as "Dear ImGui". **How can I tell whether to dispatch mouse/keyboard to imgui or to my application?**
**How can I display an image? What is ImTextureID, how does it works?** @@ -269,7 +270,7 @@ You can alter the look of the interface to some degree: changing colors, sizes, Dear ImGui takes advantage of a few C++ languages features for convenience but nothing anywhere Boost-insanity/quagmire. Dear ImGui does NOT require C++11 so it can be used with most old C++ compilers. Dear ImGui doesn't use any C++ header file. Language-wise, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience. -There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/cimgui/cimgui) by Sonoro1234 and Stephan Dilly. This is designed for binding other languages. If possible, I would suggest using your target language functionalities to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. Also see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings) for third-party bindings to other languages. +There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/cimgui/cimgui) by Sonoro1234 and Stephan Dilly. It is designed for creating binding to other languages. If possible, I would suggest using your target language functionalities to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. Also see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings) for various third-party bindings. Support dear imgui ------------------ @@ -279,7 +280,7 @@ Support dear imgui - You may participate in the [Discourse forums](https://discourse.dearimgui.org) and the GitHub [issues tracker](https://github.com/ocornut/imgui/issues). - You may help with development and submit pull requests! Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance forever. PR should be crafted both in the interest in the end-users and also to ease the maintainer into understanding and accepting it. - See [Help wanted](https://github.com/ocornut/imgui/wiki/Help-Wanted) on the [Wiki](https://github.com/ocornut/imgui/wiki/) for some more ideas. -- Convince your company to financially support this project. +- Have your company financially support this project. **How can I help financing further development of Dear ImGui?** @@ -316,7 +317,7 @@ Credits Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com). -I first discovered the IMGUI paradigm at [Q-Games](http://www.q-games.com) where Atman had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating on it. +I first discovered the IMGUI paradigm at [Q-Games](http://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it. Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license). @@ -327,4 +328,4 @@ Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Bin License ------- -Dear ImGui is licensed under the MIT License, see LICENSE for more information. +Dear ImGui is licensed under the MIT License, see [LICENSE.txt](https://github.com/ocornut/imgui/blob/master/LICENSE.txt) for more information. From d93e3c17fc7e0da618ac8cf4396af91c7459d8a4 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 13:13:35 +0100 Subject: [PATCH 022/566] ImGuiTextBuffer: Fix size() to allow using ImGuiTextBuffer with resize(0) patterns. --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index a5c48597..3d565462 100644 --- a/imgui.h +++ b/imgui.h @@ -1583,7 +1583,7 @@ struct ImGuiTextBuffer inline char operator[](int i) { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator - int size() const { return Buf.Data ? Buf.Size - 1 : 0; } + int size() const { return Buf.Size ? Buf.Size - 1 : 0; } bool empty() { return Buf.Size <= 1; } void clear() { Buf.clear(); } void reserve(int capacity) { Buf.reserve(capacity); } From d38f4dc1437914ccadbcfc71ba0e9531d0316990 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 13:16:09 +0100 Subject: [PATCH 023/566] Tabs: Non-docking tab bars are storing names to allow tab list button + whole style scaling. Added ImGuiTabBarFlags_TabListPopupButton flag to show a popup button on manual tab bars. Locking FramePadding for the scope of a tab-bar to avoid sheering/clipping of tab item. Made scaling of tab ellipsis less awkward. (#261, #351) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 4 +-- imgui_demo.cpp | 1 + imgui_draw.cpp | 3 +- imgui_internal.h | 26 +++++++++++---- imgui_widgets.cpp | 79 ++++++++++++++++++++++++++++++++++++++++------ 6 files changed, 95 insertions(+), 20 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ea94b323..442b0706 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Other Changes: - InputText: Fixed a bug where ESCAPE would be first captured by the Keyboard Navigation code. (#2321, #787) - Fixed range-version of PushID() and GetID() not honoring the ### operator to restart from the seed value. - Fixed CloseCurrentPopup() on a child-menu of a modal incorrectly closing the modal. (#2308) +- Tabs: Added ImGuiTabBarFlags_TabListPopupButton flag to show a popup button on manual tab bars. (#261, #351) +- Tabs: Removed ImGuiTabBarFlags_NoTabListPopupButton which was available in 1.67 but actually had zero use. - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). - Window: When resizing from an edge, the border is more visible and better follow the rounded corners. - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" diff --git a/imgui.h b/imgui.h index 3d565462..c905f6db 100644 --- a/imgui.h +++ b/imgui.h @@ -810,8 +810,8 @@ enum ImGuiTabBarFlags_ ImGuiTabBarFlags_None = 0, ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear - ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. - ImGuiTabBarFlags_NoTabListPopupButton = 1 << 3, + ImGuiTabBarFlags_TabListPopupButton = 1 << 2, + ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2b2da8f3..bd4792d5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1774,6 +1774,7 @@ static void ShowDemoWindowLayout() static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable; ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_Reorderable); ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8e694d9f..90b451e3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3058,7 +3058,8 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im void ImGui::RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, int count, ImU32 col) { ImFont* font = draw_list->_Data->Font; - pos.y += (float)(int)(font->DisplayOffset.y + font->Ascent + 0.5f - 1.0f); + const float font_scale = draw_list->_Data->FontSize / font->FontSize; + pos.y += (float)(int)(font->DisplayOffset.y + font->Ascent * font_scale + 0.5f - 1.0f); for (int dot_n = 0; dot_n < count; dot_n++) draw_list->AddRectFilled(ImVec2(pos.x + dot_n * 2.0f, pos.y), ImVec2(pos.x + dot_n * 2.0f + 1.0f, pos.y + 1.0f), col); } diff --git a/imgui_internal.h b/imgui_internal.h index 947b2f1d..b1f5d751 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1245,10 +1245,14 @@ struct ImGuiItemHoveredDataBackup enum ImGuiTabBarFlagsPrivate_ { - ImGuiTabBarFlags_DockNode = 1 << 20, // [Docking: Unused in Master Branch] Part of a dock node - ImGuiTabBarFlags_DockNodeIsDockSpace = 1 << 21, // [Docking: Unused in Master Branch] Part of an explicit dockspace node node - ImGuiTabBarFlags_IsFocused = 1 << 22, - ImGuiTabBarFlags_SaveSettings = 1 << 23 // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs + ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node + ImGuiTabBarFlags_IsFocused = 1 << 21, + ImGuiTabBarFlags_SaveSettings = 1 << 22 // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs +}; + +enum ImGuiTabItemFlagsPrivate_ +{ + ImGuiTabItemFlags_NoCloseButton = 1 << 20 // Store whether p_open is set or not, which we need to recompute WidthContents during layout. }; // Storage for one active tab item (sizeof() 26~32 bytes) @@ -1258,11 +1262,12 @@ struct ImGuiTabItem ImGuiTabItemFlags Flags; int LastFrameVisible; int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance + int NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames float Offset; // Position relative to beginning of tab float Width; // Width currently displayed float WidthContents; // Width of actual contents, stored during BeginTabItem() call - ImGuiTabItem() { ID = Flags = 0; LastFrameVisible = LastFrameSelected = -1; Offset = Width = WidthContents = 0.0f; } + ImGuiTabItem() { ID = Flags = 0; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = WidthContents = 0.0f; } }; // Storage for a tab bar (sizeof() 92~96 bytes) @@ -1287,9 +1292,16 @@ struct ImGuiTabBar bool WantLayout; bool VisibleTabWasSubmitted; short LastTabItemIdx; // For BeginTabItem()/EndTabItem() + ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() + ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); - int GetTabOrder(const ImGuiTabItem* tab) const { return Tabs.index_from_ptr(tab); } + int GetTabOrder(const ImGuiTabItem* tab) const { return Tabs.index_from_ptr(tab); } + const char* GetTabName(const ImGuiTabItem* tab) const + { + IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size); + return TabsNames.Buf.Data + tab->NameOffset; + } }; //----------------------------------------------------------------------------- @@ -1421,7 +1433,7 @@ namespace ImGui IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags); IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button); IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); - IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, const char* label, ImGuiID tab_id, ImGuiID close_button_id); + IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id); // Render helpers // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eea0e610..04948657 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5780,6 +5780,7 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, // - TabBarScrollToTab() [Internal] // - TabBarQueueChangeTabOrder() [Internal] // - TabBarScrollingButtons() [Internal] +// - TabBarTabListPopupButton() [Internal] //------------------------------------------------------------------------- namespace ImGui @@ -5790,6 +5791,7 @@ namespace ImGui static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar); + static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar); } ImGuiTabBar::ImGuiTabBar() @@ -5869,6 +5871,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab() tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible; tab_bar->CurrFrameVisible = g.FrameCount; + tab_bar->FramePadding = g.Style.FramePadding; // Layout ItemSize(ImVec2(tab_bar->OffsetMax, tab_bar->BarRect.GetHeight())); @@ -5878,8 +5881,8 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_Tab); const float y = tab_bar->BarRect.Max.y - 1.0f; { - const float separator_min_x = tab_bar->BarRect.Min.x - ((flags & ImGuiTabBarFlags_DockNodeIsDockSpace) ? 0.0f : window->WindowPadding.x); - const float separator_max_x = tab_bar->BarRect.Max.x + ((flags & ImGuiTabBarFlags_DockNodeIsDockSpace) ? 0.0f : window->WindowPadding.x); + const float separator_min_x = tab_bar->BarRect.Min.x - window->WindowPadding.x; + const float separator_max_x = tab_bar->BarRect.Max.x + window->WindowPadding.x; window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f); } return true; @@ -5983,9 +5986,12 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (tab->ID == tab_bar->SelectedTabId) found_selected_tab_id = true; - // Refresh tab width immediately if we can (for manual tab bar, WidthContent will lag by one frame which is mostly noticeable when changing style.FramePadding.x) + // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. + const char* tab_name = tab_bar->GetTabName(tab); + tab->WidthContents = TabItemCalcSize(tab_name, (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true).x; + width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->WidthContents; // Store data so we can build an array sorted by width if we need to shrink tabs down @@ -6038,6 +6044,12 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); tab_bar->OffsetNextTab = 0.0f; + // Tab List Popup + const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; + if (tab_list_popup_button) + if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! + scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; + // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) @@ -6063,6 +6075,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) const float scrolling_speed = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) ? FLT_MAX : (g.IO.DeltaTime * g.FontSize * 70.0f); if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget) tab_bar->ScrollingAnim = ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, scrolling_speed); + + // Clear name buffers + if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) + tab_bar->TabsNames.Buf.resize(0); } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. @@ -6204,6 +6220,42 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) return tab_to_select; } +static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y * 2.0f; + const ImVec2 backup_cursor_pos = window->DC.CursorPos; + tab_bar->BarRect.Max.x -= tab_list_popup_button_width; + if (window->HasCloseButton) + tab_bar->BarRect.Max.x += g.Style.ItemInnerSpacing.x; + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Min.y); + + ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; + arrow_col.w *= 0.5f; + PushStyleColor(ImGuiCol_Text, arrow_col); + PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_PopupAlignLeft); + PopStyleColor(2); + + ImGuiTabItem* tab_to_select = NULL; + if (open) + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + const char* tab_name = tab_bar->GetTabName(tab); + if (MenuItem(tab_name)) + tab_to_select = tab; + } + EndCombo(); + } + + window->DC.CursorPos = backup_cursor_pos; + return tab_to_select; +} + //------------------------------------------------------------------------- // [SECTION] Widgets: BeginTabItem, EndTabItem, etc. //------------------------------------------------------------------------- @@ -6290,12 +6342,19 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab); tab->WidthContents = size.x; + if (p_open == NULL) + flags |= ImGuiTabItemFlags_NoCloseButton; + const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0; const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount); tab->LastFrameVisible = g.FrameCount; tab->Flags = flags; + // Append name with zero-terminator + tab->NameOffset = tab_bar->TabsNames.size(); + tab_bar->TabsNames.append(label, label + strlen(label) + 1); + // If we are not reorderable, always reset offset based on submission order. // (We already handled layout and sizing using the previous known order, but sizing is not affected by order!) if (!tab_appearing && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) @@ -6412,7 +6471,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Render tab label, process close button const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; - bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, label, id, close_button_id); + bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id); if (just_closed && p_open != NULL) { *p_open = false; @@ -6480,22 +6539,22 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI } // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic -bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, const char* label, ImGuiID tab_id, ImGuiID close_button_id) +// We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. +bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id) { ImGuiContext& g = *GImGui; - ImGuiStyle& style = g.Style; ImVec2 label_size = CalcTextSize(label, NULL, true); if (bb.GetWidth() <= 1.0f) return false; // Render text label (with clipping + alpha gradient) + unsaved marker const char* TAB_UNSAVED_MARKER = "*"; - ImRect text_pixel_clip_bb(bb.Min.x + style.FramePadding.x, bb.Min.y + style.FramePadding.y, bb.Max.x - style.FramePadding.x, bb.Max.y); + ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); if (flags & ImGuiTabItemFlags_UnsavedDocument) { text_pixel_clip_bb.Max.x -= CalcTextSize(TAB_UNSAVED_MARKER, NULL, false).x; - ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + style.FramePadding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + style.FramePadding.y + (float)(int)(-g.FontSize * 0.25f)); - RenderTextClippedEx(draw_list, unsaved_marker_pos, bb.Max - style.FramePadding, TAB_UNSAVED_MARKER, NULL, NULL); + ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + frame_padding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + frame_padding.y + (float)(int)(-g.FontSize * 0.25f)); + RenderTextClippedEx(draw_list, unsaved_marker_pos, bb.Max - frame_padding, TAB_UNSAVED_MARKER, NULL, NULL); } ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; @@ -6513,7 +6572,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, { ImGuiItemHoveredDataBackup last_item_backup; const float close_button_sz = g.FontSize * 0.5f; - if (CloseButton(close_button_id, ImVec2(bb.Max.x - style.FramePadding.x - close_button_sz, bb.Min.y + style.FramePadding.y + close_button_sz), close_button_sz)) + if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x - close_button_sz, bb.Min.y + frame_padding.y + close_button_sz), close_button_sz)) close_button_pressed = true; last_item_backup.Restore(); From b980e0077aca9a8fe5cf395d19c6a220f0f61b98 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 13:39:48 +0100 Subject: [PATCH 024/566] Tabs: Moved Tab List Popup to left-side to match docking button. Highlight selected tab. (#261, #351) --- imgui_widgets.cpp | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 04948657..c7a2b7c5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5969,6 +5969,12 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->ReorderRequestTabId = 0; } + // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!) + const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; + if (tab_list_popup_button) + if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! + scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; + ImVector& width_sort_buffer = g.TabSortByWidthBuffer; width_sort_buffer.resize(tab_bar->Tabs.Size); @@ -6044,12 +6050,6 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); tab_bar->OffsetNextTab = 0.0f; - // Tab List Popup - const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; - if (tab_list_popup_button) - if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! - scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; - // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) @@ -6225,18 +6225,17 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y * 2.0f; + // We use g.Style.FramePadding.y to match the square ArrowButton size + const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y; const ImVec2 backup_cursor_pos = window->DC.CursorPos; - tab_bar->BarRect.Max.x -= tab_list_popup_button_width; - if (window->HasCloseButton) - tab_bar->BarRect.Max.x += g.Style.ItemInnerSpacing.x; - window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Min.y); + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y); + tab_bar->BarRect.Min.x += tab_list_popup_button_width; ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; arrow_col.w *= 0.5f; PushStyleColor(ImGuiCol_Text, arrow_col); PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); - bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_PopupAlignLeft); + bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview); PopStyleColor(2); ImGuiTabItem* tab_to_select = NULL; @@ -6246,7 +6245,7 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; const char* tab_name = tab_bar->GetTabName(tab); - if (MenuItem(tab_name)) + if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID)) tab_to_select = tab; } EndCombo(); From f6fbb99a9c628187be24f5b57e5c2dd4f5b046cf Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 15:45:26 +0100 Subject: [PATCH 025/566] Examples: SDL: Fix for Emscripten/Android/iOS on Docking branch. --- examples/imgui_impl_sdl.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index e1c505f5..a1ab790d 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -269,13 +269,12 @@ static void ImGui_ImplSDL2_UpdateMousePosAndButtons() io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; -#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) // SDL 2.0.4 and later has SDL_GetGlobalMouseState() and SDL_CaptureMouse() int mouse_x_global, mouse_y_global; SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); -#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) @@ -284,7 +283,6 @@ static void ImGui_ImplSDL2_UpdateMousePosAndButtons() io.MousePos = ImVec2((float)mouse_x_global, (float)mouse_y_global); } else -#endif { // Single-viewport mode: mouse position in client window coordinatesio.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) if (SDL_GetWindowFlags(g_Window) & SDL_WINDOW_INPUT_FOCUS) From 521470b3cd8bfbecc6c72bd1f3cff8731e1408e0 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 17:51:01 +0100 Subject: [PATCH 026/566] Internals: Removed unnecessary code. --- imgui.cpp | 2 +- imgui_widgets.cpp | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4822a09b..c4bf4614 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6216,7 +6216,7 @@ void ImGui::SetNextWindowBgAlpha(float alpha) g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) } -// In window space (not screen space!) +// FIXME: This is in window space (not screen space!) ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GetCurrentWindowRead(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c7a2b7c5..f2b58c7c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -897,7 +897,6 @@ bool ImGui::Checkbox(const char* label, bool* v) const float square_sz = GetFrameHeight(); const ImVec2 pos = window->DC.CursorPos; - const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id)) @@ -911,6 +910,7 @@ bool ImGui::Checkbox(const char* label, bool* v) MarkItemEdited(id); } + const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); RenderNavHighlight(total_bb, id); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); if (*v) @@ -1855,7 +1855,6 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); - const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); @@ -1910,7 +1909,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); if (label_size.x > 0.0f) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags); return value_changed; From b8c24aff4cbcfcbee8f06c1c2b77de012e4a45ca Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 18:03:27 +0100 Subject: [PATCH 027/566] Internals: EndGroup: Removed unnecesary parameter to ItemSize() --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index c4bf4614..877ca71b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6573,7 +6573,7 @@ void ImGui::EndGroup() if (group_data.AdvanceCursor) { window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. - ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); + ItemSize(group_bb.GetSize(), 0.0f); ItemAdd(group_bb, 0); } From cef4e086ba5979987f7dbd9916291a0d20dbc4ff Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 18:10:33 +0100 Subject: [PATCH 028/566] Internals: Selectable: Fixed rendering width miscalculation when starting pos is not line start pos, which would generally be unnoticeable. Could affect group lock X with a smaller SetCursorPos value but that's unlikely to be used. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f2b58c7c..642f3e14 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5016,7 +5016,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Fill horizontal space. ImVec2 window_padding = window->WindowPadding; float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; - float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); + float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - pos.x); ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); ImRect bb(pos, pos + size_draw); if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) From 97ed97b8ce55163e470929d78f2d83477524861f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 18:59:42 +0100 Subject: [PATCH 029/566] Plot: Register an ID to take the click the same way as other framed widgets. Set HoveredId in the FramePadding zone (between inner_bb and frame_bb). --- imgui_internal.h | 2 +- imgui_widgets.cpp | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b1f5d751..0111df3e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1493,7 +1493,7 @@ namespace ImGui IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags); // Plot - IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); + IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size); // Shade functions (write over already created vertices) IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 642f3e14..35316d69 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5214,7 +5214,7 @@ bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(v // - PlotHistogram() //------------------------------------------------------------------------- -void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -5222,20 +5222,21 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - if (graph_size.x == 0.0f) - graph_size.x = CalcItemWidth(); - if (graph_size.y == 0.0f) - graph_size.y = label_size.y + (style.FramePadding.y * 2); + if (frame_size.x == 0.0f) + frame_size.x = CalcItemWidth(); + if (frame_size.y == 0.0f) + frame_size.y = label_size.y + (style.FramePadding.y * 2); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, 0, &frame_bb)) return; - const bool hovered = ItemHoverable(inner_bb, 0); + const bool hovered = ItemHoverable(frame_bb, id); // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) @@ -5258,12 +5259,12 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge if (values_count > 0) { - int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); // Tooltip on hover int v_hovered = -1; - if (hovered) + if (hovered && inner_bb.Contains(g.IO.MousePos)) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); const int v_idx = (int)(t * item_count); From c59611a3b3c031d253b927f5fa199ff176fd728c Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Feb 2019 23:38:57 +0100 Subject: [PATCH 030/566] InputText: Fixed redo buffer exhaustion handling (rare) which could corrupt the undo character buffer. (#2333) --- docs/CHANGELOG.txt | 2 ++ imstb_textedit.h | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 442b0706..448ad27f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ Other Changes: - Added .editorconfig file for text editors to standardize using spaces. (#2038) [@kudaba] - InputText: Fixed a bug where ESCAPE would not restore the initial value in all situations. (#2321) [@relick] - InputText: Fixed a bug where ESCAPE would be first captured by the Keyboard Navigation code. (#2321, #787) +- InputText: Fixed redo buffer exhaustion handling (rare) which could corrupt the undo character buffer. (#2333) + The way the redo/undo buffers work would have made it generally unnoticeable to the user. - Fixed range-version of PushID() and GetID() not honoring the ### operator to restart from the seed value. - Fixed CloseCurrentPopup() on a child-menu of a modal incorrectly closing the modal. (#2308) - Tabs: Added ImGuiTabBarFlags_TabListPopupButton flag to show a popup button on manual tab bars. (#261, #351) diff --git a/imstb_textedit.h b/imstb_textedit.h index 27e34f74..d79c7730 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -1132,7 +1132,13 @@ static void stb_textedit_discard_redo(StbUndoState *state) state->undo_rec[i].char_storage += n; } // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' - STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, (size_t) ((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); + size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); + const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; + const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; + IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin); + IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end); + STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size); + // now move redo_point to point to the new one ++state->redo_point; } From e3dd95d3350c6a17ac30112233aca2769d2bc020 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Feb 2019 11:52:42 +0100 Subject: [PATCH 031/566] Added IsItemActivated() as an extension to the IsItemDeactivated/IsItemDeactivatedAfterEdit functions which are useful to implement variety of undo patterns. (#820, #956, #1875) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 12 ++++++++++++ imgui.h | 1 + imgui_demo.cpp | 6 ++++-- 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 448ad27f..febb3349 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,10 +43,13 @@ Other Changes: - InputText: Fixed a bug where ESCAPE would be first captured by the Keyboard Navigation code. (#2321, #787) - InputText: Fixed redo buffer exhaustion handling (rare) which could corrupt the undo character buffer. (#2333) The way the redo/undo buffers work would have made it generally unnoticeable to the user. +- Added IsItemActivated() as an extension to the IsItemDeactivated/IsItemDeactivatedAfterEdit functions + which are useful to implement variety of undo patterns. (#820, #956, #1875) - Fixed range-version of PushID() and GetID() not honoring the ### operator to restart from the seed value. - Fixed CloseCurrentPopup() on a child-menu of a modal incorrectly closing the modal. (#2308) - Tabs: Added ImGuiTabBarFlags_TabListPopupButton flag to show a popup button on manual tab bars. (#261, #351) - Tabs: Removed ImGuiTabBarFlags_NoTabListPopupButton which was available in 1.67 but actually had zero use. +- Tabs: Fixed a minor clipping glitch when changing style's FramePadding from frame to frame. - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). - Window: When resizing from an edge, the border is more visible and better follow the rounded corners. - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" diff --git a/imgui.cpp b/imgui.cpp index 877ca71b..f8c7ed69 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4215,6 +4215,18 @@ bool ImGui::IsItemActive() return false; } +bool ImGui::IsItemActivated() +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId) + { + ImGuiWindow* window = g.CurrentWindow; + if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId) + return true; + } + return false; +} + bool ImGui::IsItemDeactivated() { ImGuiContext& g = *GImGui; diff --git a/imgui.h b/imgui.h index c905f6db..35183fd4 100644 --- a/imgui.h +++ b/imgui.h @@ -607,6 +607,7 @@ namespace ImGui IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered() IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. + IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive). IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing. IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). IMGUI_API bool IsAnyItemHovered(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bd4792d5..e80b2d48 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1420,7 +1420,7 @@ static void ShowDemoWindowWidgets() static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; ImGui::RadioButton("Text", &item_type, 0); ImGui::RadioButton("Button", &item_type, 1); - ImGui::RadioButton("CheckBox", &item_type, 2); + ImGui::RadioButton("Checkbox", &item_type, 2); ImGui::RadioButton("SliderFloat", &item_type, 3); ImGui::RadioButton("ColorEdit4", &item_type, 4); ImGui::RadioButton("ListBox", &item_type, 5); @@ -1428,7 +1428,7 @@ static void ShowDemoWindowWidgets() bool ret = false; if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button - if (item_type == 2) { ret = ImGui::Checkbox("ITEM: CheckBox", &b); } // Testing checkbox + if (item_type == 2) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox if (item_type == 3) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item if (item_type == 4) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) if (item_type == 5) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } @@ -1442,6 +1442,7 @@ static void ShowDemoWindowWidgets() "IsItemHovered(_RectOnly) = %d\n" "IsItemActive() = %d\n" "IsItemEdited() = %d\n" + "IsItemActivated() = %d\n" "IsItemDeactivated() = %d\n" "IsItemDeactivatedEdit() = %d\n" "IsItemVisible() = %d\n" @@ -1457,6 +1458,7 @@ static void ShowDemoWindowWidgets() ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly), ImGui::IsItemActive(), ImGui::IsItemEdited(), + ImGui::IsItemActivated(), ImGui::IsItemDeactivated(), ImGui::IsItemDeactivatedAfterEdit(), ImGui::IsItemVisible(), From 5bdc7d7a6f9621d272354a0ffd523266de05af6d Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Feb 2019 12:32:10 +0100 Subject: [PATCH 032/566] Menus: Tweaked horizontal overlap between parent and child menu (to help convey relative depth) from using style.ItemSpacing.x to style.ItemInnerSpacing.x, the later being expected to be smaller. (#1086) --- docs/CHANGELOG.txt | 2 ++ docs/TODO.txt | 1 + imgui.cpp | 4 ++-- imgui_widgets.cpp | 9 ++++++--- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index febb3349..8af1989a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Other Changes: - Tabs: Added ImGuiTabBarFlags_TabListPopupButton flag to show a popup button on manual tab bars. (#261, #351) - Tabs: Removed ImGuiTabBarFlags_NoTabListPopupButton which was available in 1.67 but actually had zero use. - Tabs: Fixed a minor clipping glitch when changing style's FramePadding from frame to frame. +- Menus: Tweaked horizontal overlap between parent and child menu (to help convey relative depth) + from using style.ItemSpacing.x to style.ItemInnerSpacing.x, the later being expected to be smaller. (#1086) - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). - Window: When resizing from an edge, the border is more visible and better follow the rounded corners. - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" diff --git a/docs/TODO.txt b/docs/TODO.txt index a183e67c..114bd995 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -159,6 +159,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - listbox: user may want to initial scroll to focus on the one selected value? - listbox: expose hovered item for a basic ListBox - listbox: keyboard navigation. + - listbox: disable capturing mouse wheel if the listbox has no scrolling. (#1681) - listbox: scrolling should track modified selection. !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) diff --git a/imgui.cpp b/imgui.cpp index f8c7ed69..6380b478 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7078,11 +7078,11 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) ImRect r_outer = GetWindowAllowedExtentRect(window); if (window->Flags & ImGuiWindowFlags_ChildMenu) { - // Child menus typically request _any_ position within the parent menu item, and then our FindBestWindowPosForPopup() function will move the new menu outside the parent bounds. + // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. IM_ASSERT(g.CurrentWindow == window); ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2]; - float horizontal_overlap = g.Style.ItemSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). + float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). ImRect r_avoid; if (parent_window->DC.MenuBarAppending) r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 35316d69..b161015d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5573,7 +5573,9 @@ bool ImGui::BeginMenu(const char* label, bool enabled) if (menuset_is_open) g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent) - // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestWindowPosForPopup). + // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, + // However the final position is going to be different! It is choosen by FindBestWindowPosForPopup(). + // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. ImVec2 popup_pos, pos = window->DC.CursorPos; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { @@ -5613,13 +5615,14 @@ bool ImGui::BeginMenu(const char* label, bool enabled) { if (ImGuiWindow* next_window = g.OpenPopupStack[g.BeginPopupStack.Size].Window) { + // FIXME-DPI: Values should be derived from a master "scale" factor. ImRect next_window_rect = next_window->Rect(); ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. - ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues - tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? + ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug From f366828dd276af1d32fa03747a7e1ce6732159c6 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Feb 2019 13:08:30 +0100 Subject: [PATCH 033/566] Minor tweaks to reduce false positive of PVS Studio static analyzer. --- examples/imgui_impl_opengl3.cpp | 6 +++--- imgui.cpp | 2 +- imgui_demo.cpp | 11 +++++++---- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 5 files changed, 13 insertions(+), 10 deletions(-) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index f217ecf4..70bafe77 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -225,7 +225,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; - const ImDrawIdx* idx_buffer_offset = 0; + size_t idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); @@ -254,10 +254,10 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); - glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)idx_buffer_offset); } } - idx_buffer_offset += pcmd->ElemCount; + idx_buffer_offset += pcmd->ElemCount * sizeof(ImDrawIdx); } } glDeleteVertexArrays(1, &vao_handle); diff --git a/imgui.cpp b/imgui.cpp index 6380b478..3e5989a9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8863,7 +8863,7 @@ void ImGui::LogToFile(int max_depth, const char* filename) g.LogFile = ImFileOpen(filename, "ab"); if (!g.LogFile) { - IM_ASSERT(g.LogFile != NULL); // Consider this an error + IM_ASSERT(0); return; } g.LogEnabled = true; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e80b2d48..796f7355 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2905,7 +2905,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, "%.0f"); ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar); - ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)sqrtf((float)font->MetricsTotalSurface), (int)sqrtf((float)font->MetricsTotalSurface)); + const float surface_sqrt = sqrtf((float)font->MetricsTotalSurface); + ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)surface_sqrt, (int)surface_sqrt); for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) if (ImFontConfig* cfg = &font->ConfigData[config_i]) ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); @@ -3797,10 +3798,12 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) const float DISTANCE = 10.0f; static int corner = 0; ImGuiIO& io = ImGui::GetIO(); - ImVec2 window_pos = ImVec2((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE); - ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); if (corner != -1) + { + ImVec2 window_pos = ImVec2((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE); + ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); + } ImGui::SetNextWindowBgAlpha(0.3f); // Transparent background if (ImGui::Begin("Example: Simple overlay", p_open, (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) { @@ -3893,7 +3896,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) float th = (n == 0) ? 1.0f : thickness; draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 6, th); x += sz+spacing; // Hexagon draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, th); x += sz+spacing; // Circle - draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ImDrawCornerFlags_All, th); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ImDrawCornerFlags_All, th); x += sz+spacing; draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_All, th); x += sz+spacing; draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight, th); x += sz+spacing; draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, th); x += sz+spacing; diff --git a/imgui_internal.h b/imgui_internal.h index 0111df3e..f25d208e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -582,7 +582,7 @@ struct IMGUI_API ImGuiInputTextState void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); } bool HasSelection() const { return StbState.select_start != StbState.select_end; } void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; } - void SelectAll() { StbState.select_start = 0; StbState.cursor = StbState.select_end = CurLenW; StbState.has_preferred_x = false; } + void SelectAll() { StbState.select_start = 0; StbState.cursor = StbState.select_end = CurLenW; StbState.has_preferred_x = 0; } void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b161015d..b479500d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3225,7 +3225,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 select_all = true; } if (flags & ImGuiInputTextFlags_AlwaysInsertMode) - edit_state.StbState.insert_mode = true; + edit_state.StbState.insert_mode = 1; if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) select_all = true; } From 62084aac0f56d05e9fe9cf91bdf1a17136a9b2ac Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Feb 2019 14:39:00 +0100 Subject: [PATCH 034/566] DragScalarN, SliderScalarN, InputScalarN: Removed unnecessary string id after the integer PushID() calls. --- imgui_widgets.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b479500d..e7d0daab 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1930,7 +1930,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int for (int i = 0; i < components; i++) { PushID(i); - value_changed |= DragScalar("##v", data_type, v, v_speed, v_min, v_max, format, power); + value_changed |= DragScalar("", data_type, v, v_speed, v_min, v_max, format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); @@ -2367,7 +2367,7 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i for (int i = 0; i < components; i++) { PushID(i); - value_changed |= SliderScalar("##v", data_type, v, v_min, v_max, format, power); + value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); @@ -2700,7 +2700,7 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, in for (int i = 0; i < components; i++) { PushID(i); - value_changed |= InputScalar("##v", data_type, v, step, step_fast, format, flags); + value_changed |= InputScalar("", data_type, v, step, step_fast, format, flags); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); From 29d38b59d097b952bcff82873e0441aff0976e15 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Feb 2019 14:46:14 +0100 Subject: [PATCH 035/566] ListBox/InputTextMultiline: Better optimized when clipped / non-visible. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 14 +++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8af1989a..9f7f2109 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,8 @@ Other Changes: from using style.ItemSpacing.x to style.ItemInnerSpacing.x, the later being expected to be smaller. (#1086) - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). - Window: When resizing from an edge, the border is more visible and better follow the rounded corners. +- ListBox: Better optimized when clipped / non-visible. +- InputTextMultiline: Better optimized when clipped / non-visible. - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" with a small number of segments (e.g. an hexagon). (#2287) [@baktery] - ImGuiTextBuffer: Added append() function (unformatted). diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e7d0daab..565dbe1a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3138,7 +3138,12 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 ImGuiWindow* draw_window = window; if (is_multiline) { - ItemAdd(total_bb, id, &frame_bb); + if (!ItemAdd(total_bb, id, &frame_bb)) + { + ItemSize(total_bb, style.FramePadding.y); + EndGroup(); + return false; + } if (!BeginChildFrame(id, frame_bb.GetSize())) { EndChildFrame(); @@ -5122,6 +5127,13 @@ bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy. + if (!IsRectVisible(bb.Min, bb.Max)) + { + ItemSize(bb.GetSize(), style.FramePadding.y); + ItemAdd(bb, 0, &frame_bb); + return false; + } + BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); From 1b63ded8fad7ab2e41468d485160b416383e0646 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Feb 2019 12:06:48 +0100 Subject: [PATCH 036/566] Tabs: Fixed border (when enabled) so it is aligned correctly mid-pixel and appears as bright as other borders. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9f7f2109..81c7eb5f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other Changes: - Tabs: Added ImGuiTabBarFlags_TabListPopupButton flag to show a popup button on manual tab bars. (#261, #351) - Tabs: Removed ImGuiTabBarFlags_NoTabListPopupButton which was available in 1.67 but actually had zero use. - Tabs: Fixed a minor clipping glitch when changing style's FramePadding from frame to frame. +- Tabs: Fixed border (when enabled) so it is aligned correctly mid-pixel and appears as bright as other borders. - Menus: Tweaked horizontal overlap between parent and child menu (to help convey relative depth) from using style.ItemSpacing.x to style.ItemInnerSpacing.x, the later being expected to be smaller. (#1086) - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 565dbe1a..667cf3c4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6281,7 +6281,7 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) // - TabItemEx() [Internal] // - SetTabItemClosed() // - TabItemCalcSize() [Internal] -// - TabItemRenderBackground() [Internal] +// - TabItemBackground() [Internal] // - TabItemLabelAndCloseButton() [Internal] //------------------------------------------------------------------------- @@ -6465,7 +6465,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Enlarge tab display when hovering bb.Max.x = bb.Min.x + (float)(int)ImLerp(bb.GetWidth(), tab->WidthContents, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)); display_draw_list = GetOverlayDrawList(window); - TabItemRenderBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive)); + TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive)); } #endif @@ -6540,16 +6540,21 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI IM_UNUSED(flags); IM_ASSERT(width > 0.0f); const float rounding = ImMax(0.0f, ImMin(g.Style.TabRounding, width * 0.5f - 1.0f)); - float y1 = bb.Min.y + 1.0f; - float y2 = bb.Max.y - 1.0f; + const float y1 = bb.Min.y + 1.0f; + const float y2 = bb.Max.y - 1.0f; 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->AddConvexPolyFilled(draw_list->_Path.Data, draw_list->_Path.Size, col); + draw_list->PathFillConvex(col); if (g.Style.TabBorderSize > 0.0f) - draw_list->AddPolyline(draw_list->_Path.Data, draw_list->_Path.Size, GetColorU32(ImGuiCol_Border), false, g.Style.TabBorderSize); - draw_list->PathClear(); + { + 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), false, g.Style.TabBorderSize); + } } // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic From afc36cf80285a37815ab2545d0a9baa7ef483f50 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 Feb 2019 14:34:42 +0100 Subject: [PATCH 037/566] Window: Fixed initial width of collapsed windows not taking account of contents width (broken in 1.67). (#2336, #176) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 81c7eb5f..9ef9ead9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,7 @@ Other Changes: from using style.ItemSpacing.x to style.ItemInnerSpacing.x, the later being expected to be smaller. (#1086) - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). - Window: When resizing from an edge, the border is more visible and better follow the rounded corners. +- Window: Fixed initial width of collapsed windows not taking account of contents width (broken in 1.67). (#2336, #176) - ListBox: Better optimized when clipped / non-visible. - InputTextMultiline: Better optimized when clipped / non-visible. - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" diff --git a/imgui.cpp b/imgui.cpp index 3e5989a9..2ddcf43f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4558,7 +4558,8 @@ static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) static ImVec2 CalcSizeContents(ImGuiWindow* window) { if (window->Collapsed) - return window->SizeContents; + if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + return window->SizeContents; if (window->Hidden && window->HiddenFramesForResize == 0 && window->HiddenFramesRegular > 0) return window->SizeContents; From 00c637961bf06606fc5a1d8122e9bc74c65bb814 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 Feb 2019 14:50:36 +0100 Subject: [PATCH 038/566] Demo: Font selector allow selecting fonts with same debug name. (#2332) --- imgui_demo.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 796f7355..2ce06d6c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2738,8 +2738,13 @@ void ImGui::ShowFontSelector(const char* label) if (ImGui::BeginCombo(label, font_current->GetDebugName())) { for (int n = 0; n < io.Fonts->Fonts.Size; n++) - if (ImGui::Selectable(io.Fonts->Fonts[n]->GetDebugName(), io.Fonts->Fonts[n] == font_current)) - io.FontDefault = io.Fonts->Fonts[n]; + { + ImFont* font = io.Fonts->Fonts[n]; + ImGui::PushID((void*)font); + if (ImGui::Selectable(font->GetDebugName(), font == font_current)) + io.FontDefault = font; + ImGui::PopID(); + } ImGui::EndCombo(); } ImGui::SameLine(); From 539f69b9507cfcc9f1bcd979fa08dd14f87e335a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 Feb 2019 15:24:59 +0100 Subject: [PATCH 039/566] Updated STB libraries to latest (drift has been reduced with nothings/stb as most of our changes were merged). Using [DEAR IMGUI] markers when changed. --- imstb_rectpack.h | 15 +++++--- imstb_textedit.h | 17 +++++---- imstb_truetype.h | 89 +++++++++++++++++++++++++++++++++++------------- 3 files changed, 87 insertions(+), 34 deletions(-) diff --git a/imstb_rectpack.h b/imstb_rectpack.h index 2b07dcc8..23f922a5 100644 --- a/imstb_rectpack.h +++ b/imstb_rectpack.h @@ -1,4 +1,10 @@ -// stb_rect_pack.h - v0.11 - public domain - rectangle packing +// [DEAR IMGUI] +// This is a slightly modified version of stb_rect_pack.h 0.99. +// Those changes would need to be pushed into nothings/stb: +// - Added STBRP__CDECL +// Grep for [DEAR IMGUI] to find the changes. + +// stb_rect_pack.h - v0.99 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -34,6 +40,7 @@ // // Version history: // +// 0.99 (2019-02-07) warning fixes // 0.11 (2017-03-03) return packing success/fail result // 0.10 (2016-10-25) remove cast-away-const to avoid warnings // 0.09 (2016-08-27) fix compiler warnings @@ -204,6 +211,7 @@ struct stbrp_context #define STBRP_ASSERT assert #endif +// [DEAR IMGUI] Added STBRP__CDECL #ifdef _MSC_VER #define STBRP__NOTUSED(v) (void)(v) #define STBRP__CDECL __cdecl @@ -512,6 +520,7 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i return res; } +// [DEAR IMGUI] Added STBRP__CDECL static int STBRP__CDECL rect_height_compare(const void *a, const void *b) { const stbrp_rect *p = (const stbrp_rect *) a; @@ -523,6 +532,7 @@ static int STBRP__CDECL rect_height_compare(const void *a, const void *b) return (p->w > q->w) ? -1 : (p->w < q->w); } +// [DEAR IMGUI] Added STBRP__CDECL static int STBRP__CDECL rect_original_order(const void *a, const void *b) { const stbrp_rect *p = (const stbrp_rect *) a; @@ -543,9 +553,6 @@ STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int nu // we use the 'was_packed' field internally to allow sorting/unsorting for (i=0; i < num_rects; ++i) { rects[i].was_packed = i; - #ifndef STBRP_LARGE_RECTS - STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff); - #endif } // sort according to heuristic diff --git a/imstb_textedit.h b/imstb_textedit.h index d79c7730..d7fcbd62 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -1,9 +1,10 @@ -// [ImGui] this is a slightly modified version of stb_textedit.h 1.12. Those changes would need to be pushed into nothings/stb -// [ImGui] - 2018-06: fixed undo/redo after pasting large amount of text (over 32 kb). Redo will still fail when undo buffers are exhausted, but text won't be corrupted (see nothings/stb issue #620) -// [ImGui] - 2018-06: fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) -// [ImGui] - fixed some minor warnings +// [DEAR IMGUI] +// This is a slightly modified version of stb_textedit.h 1.13. +// Those changes would need to be pushed into nothings/stb: +// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) +// Grep for [DEAR IMGUI] to find the changes. -// stb_textedit.h - v1.12 - public domain - Sean Barrett +// stb_textedit.h - v1.13 - 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 @@ -34,6 +35,7 @@ // // VERSION HISTORY // +// 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 // 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield // 1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual @@ -692,7 +694,7 @@ static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) { if (STB_TEXT_HAS_SELECTION(state)) { - stb_textedit_delete_selection(str,state); // implicity clamps + stb_textedit_delete_selection(str,state); // implicitly clamps state->has_preferred_x = 0; return 1; } @@ -744,7 +746,7 @@ retry: state->has_preferred_x = 0; } } else { - stb_textedit_delete_selection(str,state); // implicity clamps + stb_textedit_delete_selection(str,state); // implicitly clamps if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { stb_text_makeundo_insert(state, state->cursor, 1); ++state->cursor; @@ -1132,6 +1134,7 @@ static void stb_textedit_discard_redo(StbUndoState *state) state->undo_rec[i].char_storage += n; } // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' + // {DEAR IMGUI] size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; diff --git a/imstb_truetype.h b/imstb_truetype.h index 0b65350a..a76a6c2a 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -1,7 +1,9 @@ -// [ImGui] this is a slightly modified version of stb_truetype.h 1.19. Those changes would need to be pushed into nothings/stb -// grep for [ImGui] to find the changes. +// [DEAR IMGUI] +// This is a slightly modified version of stb_truetype.h 1.20. +// Mostly fixing for compiler and static analyzer warnings. +// Grep for [DEAR IMGUI] to find the changes. -// stb_truetype.h - v1.19 - public domain +// stb_truetype.h - v1.20 - public domain // authored from 2009-2016 by Sean Barrett / RAD Game Tools // // This library processes TrueType files: @@ -52,6 +54,7 @@ // // VERSION HISTORY // +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod // 1.18 (2018-01-29) add missing function // 1.17 (2017-07-23) make more arguments const; doc fix @@ -78,7 +81,7 @@ // // USAGE // -// Include this file in whatever places neeed to refer to it. In ONE C/C++ +// Include this file in whatever places need to refer to it. In ONE C/C++ // file, write: // #define STB_TRUETYPE_IMPLEMENTATION // before the #include of this file. This expands out the actual @@ -250,8 +253,8 @@ // Documentation & header file 520 LOC \___ 660 LOC documentation // Sample code 140 LOC / // Truetype parsing 620 LOC ---- 620 LOC TrueType -// Software rasterization 240 LOC \ . -// Curve tesselation 120 LOC \__ 550 LOC Bitmap creation +// Software rasterization 240 LOC \ +// Curve tessellation 120 LOC \__ 550 LOC Bitmap creation // Bitmap management 100 LOC / // Baked bitmap interface 70 LOC / // Font name matching & access 150 LOC ---- 150 @@ -559,6 +562,8 @@ STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int p // // It's inefficient; you might want to c&p it and optimize it. +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); +// Query the font vertical metrics without having to create a font first. ////////////////////////////////////////////////////////////////////////////// @@ -644,6 +649,12 @@ STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h // To use with PackFontRangesGather etc., you must set it before calls // call to PackFontRangesGatherRects. +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); +// If skip != 0, this tells stb_truetype to skip any codepoints for which +// there is no corresponding glyph. If skip=0, which is the default, then +// codepoints without a glyph recived the font's "missing character" glyph, +// typically an empty box by convention. + STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display float *xpos, float *ypos, // pointers to current position in screen pixel space @@ -672,6 +683,7 @@ struct stbtt_pack_context { int height; int stride_in_bytes; int padding; + int skip_missing; unsigned int h_oversample, v_oversample; unsigned char *pixels; void *nodes; @@ -697,7 +709,7 @@ STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // file will only define one font and it always be at offset 0, so it will // return '0' for index 0, and -1 for all other indices. -// The following structure is defined publically so you can declare one on +// The following structure is defined publicly so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. struct stbtt_fontinfo { @@ -736,6 +748,7 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep // and you want a speed-up, call this function with the character you're // going to process, then use glyph-based functions instead of the // codepoint-based functions. +// Returns 0 if the character codepoint is not defined in the font. ////////////////////////////////////////////////////////////////////////////// @@ -823,7 +836,7 @@ STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, s // returns # of vertices and fills *vertices with the pointer to them // these are expressed in "unscaled" coordinates // -// The shape is a series of countours. Each one starts with +// The shape is a series of contours. Each one starts with // a STBTT_moveto, then consists of a series of mixed // STBTT_lineto and STBTT_curveto segments. A lineto // draws a line from previous endpoint to its x,y; a curveto @@ -919,7 +932,7 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); // These functions compute a discretized SDF field for a single character, suitable for storing // in a single-channel texture, sampling with bilinear filtering, and testing against -// larger than some threshhold to produce scalable fonts. +// larger than some threshold to produce scalable fonts. // info -- the font // scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap // glyph/codepoint -- the character to generate the SDF for @@ -2371,7 +2384,7 @@ static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); - // [ImGui: commented to fix static analyzer warning] + // [DEAR IMGUI] Commented to fix static analyzer warning //classDefTable = classDef1ValueArray + 2 * glyphCount; } break; @@ -2396,7 +2409,7 @@ static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) return (stbtt_int32)ttUSHORT(classRangeRecord + 4); } - // [ImGui: commented to fix static analyzer warning] + // [DEAR IMGUI] Commented to fix static analyzer warning //classDefTable = classRangeRecords + 6 * classRangeCount; } break; @@ -3029,6 +3042,7 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, dx = -dx; dy = -dy; t = x0, x0 = xb, xb = t; + // [DEAR IMGUI] Fix static analyzer warning (void)dx; // [ImGui: fix static analyzer warning] } @@ -3167,7 +3181,13 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, if (e->y0 != e->y1) { stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); if (z != NULL) { - STBTT_assert(z->ey >= scan_y_top); + if (j == 0 && off_y != 0) { + if (z->ey < scan_y_top) { + // this can happen due to subpixel positioning and some kind of fp rounding error i think + z->ey = scan_y_top; + } + } + STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds // insert at front z->next = active; active = z; @@ -3236,7 +3256,7 @@ static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) { - /* threshhold for transitioning to insertion sort */ + /* threshold for transitioning to insertion sort */ while (n > 12) { stbtt__edge t; int c01,c12,c,m,i,j; @@ -3371,7 +3391,7 @@ static void stbtt__add_point(stbtt__point *points, int n, float x, float y) points[n].y = y; } -// tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching +// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { // midpoint @@ -3796,6 +3816,7 @@ STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, in spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; spc->h_oversample = 1; spc->v_oversample = 1; + spc->skip_missing = 0; stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); @@ -3821,6 +3842,11 @@ STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h spc->v_oversample = v_oversample; } +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) +{ + spc->skip_missing = skip; +} + #define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) @@ -3974,13 +4000,17 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stb int x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; int glyph = stbtt_FindGlyphIndex(info, codepoint); - stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, - scale * spc->h_oversample, - scale * spc->v_oversample, - 0,0, - &x0,&y0,&x1,&y1); - rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); - rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + if (glyph == 0 && spc->skip_missing) { + rects[k].w = rects[k].h = 0; + } else { + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + } ++k; } } @@ -4033,7 +4063,7 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const sub_y = stbtt__oversample_shift(spc->v_oversample); for (j=0; j < ranges[i].num_chars; ++j) { stbrp_rect *r = &rects[k]; - if (r->was_packed) { + if (r->was_packed && r->w != 0 && r->h != 0) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; @@ -4147,6 +4177,19 @@ STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char * return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); } +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) +{ + int i_ascent, i_descent, i_lineGap; + float scale; + stbtt_fontinfo info; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); + scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); + stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); + *ascent = (float) i_ascent * scale; + *descent = (float) i_descent * scale; + *lineGap = (float) i_lineGap * scale; +} + STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) { float ipw = 1.0f / pw, iph = 1.0f / ph; @@ -4259,7 +4302,7 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex int winding = 0; orig[0] = x; - //orig[1] = y; // [ImGui] commmented double assignment without reading + //orig[1] = y; // [DEAR IMGUI] commmented double assignment // make sure y never passes through a vertex of the shape y_frac = (float) STBTT_fmod(y, 1.0f); From 4b41d3b280ff8700bb62d14ba5e2f8c7f505117f Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 9 Feb 2019 15:54:01 +0100 Subject: [PATCH 040/566] ImFont: Rearranged members toward an optimal CalcTextSize() loop. Removed comments from destructor. Made constructor more explicit. --- imgui.h | 38 ++++++++++++++++++++------------------ imgui_draw.cpp | 26 ++++++++++++-------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/imgui.h b/imgui.h index 35183fd4..bf42eb39 100644 --- a/imgui.h +++ b/imgui.h @@ -2078,24 +2078,26 @@ struct ImFontAtlas // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). struct ImFont { - // Members: Hot ~62/78 bytes - float FontSize; // // Height of characters, set during loading (don't change after loading) - float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() - ImVec2 DisplayOffset; // = (0.f,0.f) // Offset font rendering by xx pixels - ImVector Glyphs; // // All glyphs. - ImVector IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). - ImVector IndexLookup; // // Sparse. Index glyphs by Unicode code-point. - const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) - float FallbackAdvanceX; // == FallbackGlyph->AdvanceX - ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() - - // Members: Cold ~18/26 bytes - short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. - ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData - ImFontAtlas* ContainerAtlas; // // What we has been loaded into - float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] - bool DirtyLookupTables; - int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + // Members: Hot ~24/32 bytes (for CalcTextSize) + ImVector IndexAdvanceX; // 12/16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). + float FontSize; // 4 // in // // Height of characters, set during loading (don't change after loading) + float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX + ImWchar FallbackChar; // 2 // in // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() + + // Members: Hot ~36/48 bytes (for CalcTextSize + render loop) + ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. + ImVector Glyphs; // 12-16 // out // // All glyphs. + ImVec2 DisplayOffset; // 8 // in // = (0,0) // Offset font rendering by xx pixels + const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + + // Members: Cold ~28/40 bytes + ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into + ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData + short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + bool DirtyLookupTables; // 1 // out // + float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() + float Ascent, Descent; // 8 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) // Methods IMGUI_API ImFont(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 90b451e3..844a3e92 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2390,38 +2390,36 @@ void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) ImFont::ImFont() { - Scale = 1.0f; + FontSize = 0.0f; + FallbackAdvanceX = 0.0f; FallbackChar = (ImWchar)'?'; DisplayOffset = ImVec2(0.0f, 0.0f); - ClearOutputData(); + FallbackGlyph = NULL; + ContainerAtlas = NULL; + ConfigData = NULL; + ConfigDataCount = 0; + DirtyLookupTables = false; + Scale = 1.0f; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; } ImFont::~ImFont() { - // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. - // If you want to delete fonts you need to do it between Render() and NewFrame(). - // FIXME-CLEANUP - /* - ImGuiContext& g = *GImGui; - if (g.Font == this) - g.Font = NULL; - */ ClearOutputData(); } void ImFont::ClearOutputData() { FontSize = 0.0f; + FallbackAdvanceX = 0.0f; Glyphs.clear(); IndexAdvanceX.clear(); IndexLookup.clear(); FallbackGlyph = NULL; - FallbackAdvanceX = 0.0f; - ConfigDataCount = 0; - ConfigData = NULL; ContainerAtlas = NULL; - Ascent = Descent = 0.0f; DirtyLookupTables = true; + Ascent = Descent = 0.0f; MetricsTotalSurface = 0; } From ef7940699e269c0da4498de44be78006ebd823e2 Mon Sep 17 00:00:00 2001 From: Omar Cornut Date: Mon, 11 Feb 2019 17:38:34 +0100 Subject: [PATCH 041/566] Examples: Metal: Removed unnecessary loop. Fixed OSX Clang warning in imstb_truetype. (#1929, #1873) --- examples/imgui_impl_metal.mm | 22 +++++++++------------- imstb_truetype.h | 2 +- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index c8373420..6ffe27e5 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -440,17 +440,10 @@ void ImGui_ImplMetal_DestroyDeviceObjects() [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1]; - size_t vertexBufferLength = 0; - size_t indexBufferLength = 0; - for (int n = 0; n < drawData->CmdListsCount; n++) - { - const ImDrawList* cmd_list = drawData->CmdLists[n]; - vertexBufferLength += cmd_list->VtxBuffer.Size * sizeof(ImDrawVert); - indexBufferLength += cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx); - } - - MetalBuffer *vertexBuffer = [self dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; - MetalBuffer *indexBuffer = [self dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; + size_t vertexBufferLength = drawData->TotalVtxCount * sizeof(ImDrawVert); + size_t indexBufferLength = drawData->TotalIdxCount * sizeof(ImDrawIdx); + MetalBuffer* vertexBuffer = [self dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; + MetalBuffer* indexBuffer = [self dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; id renderPipelineState = [self renderPipelineStateForFrameAndDevice:commandBuffer.device]; [commandEncoder setRenderPipelineState:renderPipelineState]; @@ -484,10 +477,13 @@ void ImGui_ImplMetal_DestroyDeviceObjects() if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) { // Apply scissor/clipping rectangle - MTLScissorRect scissorRect = { .x = NSUInteger(clip_rect.x), + MTLScissorRect scissorRect = + { + .x = NSUInteger(clip_rect.x), .y = NSUInteger(clip_rect.y), .width = NSUInteger(clip_rect.z - clip_rect.x), - .height = NSUInteger(clip_rect.w - clip_rect.y) }; + .height = NSUInteger(clip_rect.w - clip_rect.y) + }; [commandEncoder setScissorRect:scissorRect]; diff --git a/imstb_truetype.h b/imstb_truetype.h index a76a6c2a..95631323 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -253,7 +253,7 @@ // Documentation & header file 520 LOC \___ 660 LOC documentation // Sample code 140 LOC / // Truetype parsing 620 LOC ---- 620 LOC TrueType -// Software rasterization 240 LOC \ +// Software rasterization 240 LOC \ // Curve tessellation 120 LOC \__ 550 LOC Bitmap creation // Bitmap management 100 LOC / // Baked bitmap interface 70 LOC / From a79785c0b941aa3918db0e3ce5c55c24673f0a2b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Feb 2019 18:38:07 +0100 Subject: [PATCH 042/566] ImDrawData: Added FramebufferScale field (currently a copy of the value from io.DisplayFramebufferScale). This is to allow render functions being written without pulling any data from ImGuiIO, allowing incoming multi-viewport feature to behave on Retina display and with multiple displays. If you are not using a custom binding, please update your render function code ahead of time, and use draw_data->FramebufferScale instead of io.DisplayFramebufferScale. (#2306, #1676) Examples: Metal, OpenGL2, OpenGL3: Fixed offsetting of clipping rectangle with ImDrawData::DisplayPos != (0,0) when the display frame-buffer scale scale is not (1,1). While this doesn't make a difference when using master branch, this is effectively fixing support for multi-viewport with Mac Retina Displays on those examples. (#2306) Also using ImDrawData::FramebufferScale instead of io.DisplayFramebufferScale. Examples: Clarified the use the ImDrawData::DisplayPos to offset clipping rectangles. --- docs/CHANGELOG.txt | 10 ++++++++++ examples/example_apple_opengl2/main.mm | 7 ++++--- examples/imgui_impl_allegro5.cpp | 5 +++-- examples/imgui_impl_dx10.cpp | 4 ++-- examples/imgui_impl_dx11.cpp | 4 ++-- examples/imgui_impl_dx12.cpp | 4 ++-- examples/imgui_impl_dx9.cpp | 4 ++-- examples/imgui_impl_marmalade.cpp | 9 ++++----- examples/imgui_impl_metal.mm | 21 +++++++++++++++------ examples/imgui_impl_opengl2.cpp | 20 ++++++++++++++------ examples/imgui_impl_opengl3.cpp | 22 +++++++++++++++------- examples/imgui_impl_vulkan.cpp | 6 +++--- imgui.cpp | 1 + imgui.h | 9 +++++---- imgui_draw.cpp | 8 +++++--- 15 files changed, 87 insertions(+), 47 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9ef9ead9..6e371f7e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,11 @@ Breaking Changes: Other Changes: - Added .editorconfig file for text editors to standardize using spaces. (#2038) [@kudaba] +- ImDrawData: Added FramebufferScale field (currently a copy of the value from io.DisplayFramebufferScale). + This is to allow render functions being written without pulling any data from ImGuiIO, allowing incoming + multi-viewport feature to behave on Retina display and with multiple displays. + If you are not using a custom binding, please update your render function code ahead of time, + and use draw_data->FramebufferScale instead of io.DisplayFramebufferScale. (#2306, #1676) - InputText: Fixed a bug where ESCAPE would not restore the initial value in all situations. (#2321) [@relick] - InputText: Fixed a bug where ESCAPE would be first captured by the Keyboard Navigation code. (#2321, #787) - InputText: Fixed redo buffer exhaustion handling (rare) which could corrupt the undo character buffer. (#2333) @@ -65,6 +70,11 @@ Other Changes: - ImFontAtlas: FreeType: Added support for imgui allocators + custom FreeType only SetAllocatorFunctions. (#2285) [@Vuhdo] - ImFontAtlas: FreeType: Fixed using imgui_freetype.cpp in unity builds. (#2302) - Demo: Fixed "Log" demo not initializing properly, leading to the first line not showing before a Clear. (#2318) [@bluescan] +- Examples: Metal, OpenGL2, OpenGL3: Fixed offsetting of clipping rectangle with ImDrawData::DisplayPos != (0,0) when + the display frame-buffer scale scale is not (1,1). While this doesn't make a difference when using master branch, + this is effectively fixing support for multi-viewport with Mac Retina Displays on those examples. (#2306) [@rasky, @ocornut] + Also using ImDrawData::FramebufferScale instead of io.DisplayFramebufferScale. +- Examples: Clarified the use the ImDrawData::DisplayPos to offset clipping rectangles. - Examples: Win32: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. (#1951, #2087, #2156, #2232) [many people] - Examples: Win32: Added support for XInput games (if ImGuiConfigFlags_NavEnableGamepad is enabled). diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index b91cfb96..0d92da50 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -92,13 +92,14 @@ [[self openGLContext] makeCurrentContext]; ImGuiIO& io = ImGui::GetIO(); - GLsizei width = (GLsizei)(io.DisplaySize.x * io.DisplayFramebufferScale.x); - GLsizei height = (GLsizei)(io.DisplaySize.y * io.DisplayFramebufferScale.y); + ImDrawData* draw_data = ImGui::GetDrawData(); + GLsizei width = (GLsizei)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + GLsizei height = (GLsizei)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); glViewport(0, 0, width, height); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); - ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData()); + ImGui_ImplOpenGL2_RenderDrawData(draw_data); // Present [[self openGLContext] flushBuffer]; diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 8d534516..ad0e5a35 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -122,8 +122,9 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) indices = (const int*)cmd_list->IdxBuffer.Data; } + // Render command lists int idx_offset = 0; - ImVec2 pos = draw_data->DisplayPos; + ImVec2 clip_off = draw_data->DisplayPos; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; @@ -134,7 +135,7 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) else { ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->TextureId; - al_set_clipping_rectangle(pcmd->ClipRect.x - pos.x, pcmd->ClipRect.y - pos.y, pcmd->ClipRect.z - pcmd->ClipRect.x, pcmd->ClipRect.w - pcmd->ClipRect.y); + al_set_clipping_rectangle(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y, pcmd->ClipRect.z - pcmd->ClipRect.x, pcmd->ClipRect.w - pcmd->ClipRect.y); al_draw_prim(&vertices[0], g_VertexDecl, texture, idx_offset, idx_offset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST); } idx_offset += pcmd->ElemCount; diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index b381d60a..ac394348 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -199,7 +199,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) // Render command lists int vtx_offset = 0; int idx_offset = 0; - ImVec2 pos = draw_data->DisplayPos; + ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -214,7 +214,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) else { // Apply scissor/clipping rectangle - const D3D10_RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y)}; + const D3D10_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y)}; ctx->RSSetScissorRects(1, &r); // Bind texture, Draw diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index f85f5fd2..a686d6bb 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -204,7 +204,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) // Render command lists int vtx_offset = 0; int idx_offset = 0; - ImVec2 pos = draw_data->DisplayPos; + ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -219,7 +219,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) else { // Apply scissor/clipping rectangle - const D3D11_RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) }; + const D3D11_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) }; ctx->RSSetScissorRects(1, &r); // Bind texture, Draw diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 6bcaf544..f9e1884f 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -199,7 +199,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL // Render command lists int vtx_offset = 0; int idx_offset = 0; - ImVec2 pos = draw_data->DisplayPos; + ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -212,7 +212,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL } else { - const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) }; + const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) }; ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId); ctx->RSSetScissorRects(1, &r); ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, idx_offset, vtx_offset, 0); diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index b85c5242..c0b9c74e 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -166,7 +166,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) // Render command lists int vtx_offset = 0; int idx_offset = 0; - ImVec2 pos = draw_data->DisplayPos; + ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -179,7 +179,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) } else { - const RECT r = { (LONG)(pcmd->ClipRect.x - pos.x), (LONG)(pcmd->ClipRect.y - pos.y), (LONG)(pcmd->ClipRect.z - pos.x), (LONG)(pcmd->ClipRect.w - pos.y) }; + const RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) }; const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId; g_pd3dDevice->SetTexture(0, texture); g_pd3dDevice->SetScissorRect(&r); diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index 45435977..f1eaa99a 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -3,6 +3,8 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'CIwTexture*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// Missing features: +// [ ] Renderer: Clipping rectangles are not honored. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -38,10 +40,6 @@ static ImVec2 g_RenderScale = ImVec2(1.0f,1.0f); // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_Marmalade_RenderDrawData(ImDrawData* draw_data) { - // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) - ImGuiIO& io = ImGui::GetIO(); - draw_data->ScaleClipRects(io.DisplayFramebufferScale); - // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -54,7 +52,7 @@ void ImGui_Marmalade_RenderDrawData(ImDrawData* draw_data) for (int i = 0; i < nVert; i++) { - // TODO: optimize multiplication on gpu using vertex shader/projection matrix. + // FIXME-OPT: optimize multiplication on GPU using vertex shader/projection matrix. pVertStream[i].x = cmd_list->VtxBuffer[i].pos.x * g_RenderScale.x; pVertStream[i].y = cmd_list->VtxBuffer[i].pos.y * g_RenderScale.y; pUVStream[i].x = cmd_list->VtxBuffer[i].uv.x; @@ -76,6 +74,7 @@ void ImGui_Marmalade_RenderDrawData(ImDrawData* draw_data) } else { + // FIXME: Not honoring ClipRect fields. CIwMaterial* pCurrentMaterial = IW_GX_ALLOC_MATERIAL(); pCurrentMaterial->SetShadeMode(CIwMaterial::SHADE_FLAT); pCurrentMaterial->SetCullMode(CIwMaterial::CULL_NONE); diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index 6ffe27e5..95c53236 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -10,6 +10,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-07-05: Metal: Added new Metal backend implementation. @@ -401,12 +402,10 @@ void ImGui_ImplMetal_DestroyDeviceObjects() commandEncoder:(id)commandEncoder { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - ImGuiIO &io = ImGui::GetIO(); - int fb_width = (int)(drawData->DisplaySize.x * io.DisplayFramebufferScale.x); - int fb_height = (int)(drawData->DisplaySize.y * io.DisplayFramebufferScale.y); + int fb_width = (int)(drawData->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(drawData->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0) return; - drawData->ScaleClipRects(io.DisplayFramebufferScale); [commandEncoder setCullMode:MTLCullModeNone]; [commandEncoder setDepthStencilState:g_sharedMetalContext.depthStencilState]; @@ -450,9 +449,13 @@ void ImGui_ImplMetal_DestroyDeviceObjects() [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0]; + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists size_t vertexBufferOffset = 0; size_t indexBufferOffset = 0; - ImVec2 pos = drawData->DisplayPos; for (int n = 0; n < drawData->CmdListsCount; n++) { const ImDrawList* cmd_list = drawData->CmdLists[n]; @@ -473,7 +476,13 @@ void ImGui_ImplMetal_DestroyDeviceObjects() } else { - ImVec4 clip_rect = ImVec4(pcmd->ClipRect.x - pos.x, pcmd->ClipRect.y - pos.y, pcmd->ClipRect.z - pos.x, pcmd->ClipRect.w - pos.y); + // Project scissor/clipping rectangles into framebuffer space + ImVec4 clip_rect; + clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x; + clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y; + clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x; + clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y; + if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) { // Apply scissor/clipping rectangle diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index 9745238c..99ca9690 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -18,6 +18,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications. // 2018-06-08: Misc: Extracted imgui_impl_opengl2.cpp/.h away from the old combined GLFW/SDL+OpenGL2 examples. @@ -76,12 +77,10 @@ void ImGui_ImplOpenGL2_NewFrame() void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - ImGuiIO& io = ImGui::GetIO(); - int fb_width = (int)(draw_data->DisplaySize.x * io.DisplayFramebufferScale.x); - int fb_height = (int)(draw_data->DisplaySize.y * io.DisplayFramebufferScale.y); + int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; - draw_data->ScaleClipRects(io.DisplayFramebufferScale); // We are using the OpenGL fixed pipeline to make the example code simpler to read! // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill. @@ -122,8 +121,11 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) glPushMatrix(); glLoadIdentity(); + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + // Render command lists - ImVec2 pos = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -143,7 +145,13 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) } else { - ImVec4 clip_rect = ImVec4(pcmd->ClipRect.x - pos.x, pcmd->ClipRect.y - pos.y, pcmd->ClipRect.z - pos.x, pcmd->ClipRect.w - pos.y); + // Project scissor/clipping rectangles into framebuffer space + ImVec4 clip_rect; + clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x; + clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y; + clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x; + clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y; + if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) { // Apply scissor/clipping rectangle diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 70bafe77..bd8c94e6 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -11,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT). @@ -137,12 +138,10 @@ void ImGui_ImplOpenGL3_NewFrame() void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - ImGuiIO& io = ImGui::GetIO(); - int fb_width = (int)(draw_data->DisplaySize.x * io.DisplayFramebufferScale.x); - int fb_height = (int)(draw_data->DisplaySize.y * io.DisplayFramebufferScale.y); + int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width <= 0 || fb_height <= 0) return; - draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Backup GL state GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); @@ -220,8 +219,11 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); - // Draw - ImVec2 pos = draw_data->DisplayPos; + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -243,7 +245,13 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) } else { - ImVec4 clip_rect = ImVec4(pcmd->ClipRect.x - pos.x, pcmd->ClipRect.y - pos.y, pcmd->ClipRect.z - pos.x, pcmd->ClipRect.w - pos.y); + // Project scissor/clipping rectangles into framebuffer space + ImVec4 clip_rect; + clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x; + clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y; + clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x; + clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y; + if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) { // Apply scissor/clipping rectangle diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 14807863..15c32b2e 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -289,7 +289,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Render the command lists: int vtx_offset = 0; int idx_offset = 0; - ImVec2 display_pos = draw_data->DisplayPos; + ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -305,8 +305,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Apply scissor/clipping rectangle // FIXME: We could clamp width/height based on clamped min/max values. VkRect2D scissor; - scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0; - scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0; + scissor.offset.x = (int32_t)(pcmd->ClipRect.x - clip_off.x) > 0 ? (int32_t)(pcmd->ClipRect.x - clip_off.x) : 0; + scissor.offset.y = (int32_t)(pcmd->ClipRect.y - clip_off.y) > 0 ? (int32_t)(pcmd->ClipRect.y - clip_off.y) : 0; scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x); scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here? vkCmdSetScissor(command_buffer, 0, 1, &scissor); diff --git a/imgui.cpp b/imgui.cpp index 2ddcf43f..e2ddba18 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3731,6 +3731,7 @@ static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_da draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; draw_data->DisplayPos = ImVec2(0.0f, 0.0f); draw_data->DisplaySize = io.DisplaySize; + draw_data->FramebufferScale = io.DisplayFramebufferScale; for (int n = 0; n < draw_lists->Size; n++) { draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size; diff --git a/imgui.h b/imgui.h index bf42eb39..be3434f3 100644 --- a/imgui.h +++ b/imgui.h @@ -1300,7 +1300,7 @@ struct ImGuiIO float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. - ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For hi-dpi/retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. + ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. // Miscellaneous options bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations. @@ -1893,13 +1893,14 @@ struct ImDrawData int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use) ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use) + ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. // Functions ImDrawData() { Valid = false; Clear(); } ~ImDrawData() { Clear(); } - void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext! - IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! - IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. + void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext! + IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; //----------------------------------------------------------------------------- diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 844a3e92..8ebc36c3 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1287,8 +1287,10 @@ void ImDrawData::DeIndexAllBuffers() } } -// Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. -void ImDrawData::ScaleClipRects(const ImVec2& scale) +// Helper to scale the ClipRect field of each ImDrawCmd. +// Use if your final output buffer is at a different scale than draw_data->DisplaySize, +// or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2& fb_scale) { for (int i = 0; i < CmdListsCount; i++) { @@ -1296,7 +1298,7 @@ void ImDrawData::ScaleClipRects(const ImVec2& scale) for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; - cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x, cmd->ClipRect.w * scale.y); + cmd->ClipRect = ImVec4(cmd->ClipRect.x * fb_scale.x, cmd->ClipRect.y * fb_scale.y, cmd->ClipRect.z * fb_scale.x, cmd->ClipRect.w * fb_scale.y); } } } From d16dbc5b87b5cafd0efd57da3a61441856c52e77 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Feb 2019 18:45:08 +0100 Subject: [PATCH 043/566] Examples: SDL: Using the SDL_WINDOW_ALLOW_HIGHDPI flag. (#2306, #1676) [@rasky] --- docs/CHANGELOG.txt | 1 + examples/example_sdl_opengl2/main.cpp | 3 ++- examples/example_sdl_opengl3/main.cpp | 3 ++- examples/example_sdl_vulkan/main.cpp | 3 ++- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6e371f7e..c8dbff1c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,7 @@ Other Changes: - Examples: Clarified the use the ImDrawData::DisplayPos to offset clipping rectangles. - Examples: Win32: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. (#1951, #2087, #2156, #2232) [many people] +- Examples: SDL: Using the SDL_WINDOW_ALLOW_HIGHDPI flag. (#2306, #1676) [@rasky] - Examples: Win32: Added support for XInput games (if ImGuiConfigFlags_NavEnableGamepad is enabled). - Examples: Win32: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. (#2264) - Examples: DirectX9: Explicitly disable fog (D3DRS_FOGENABLE) before drawing in case user state has it set. (#2288, #2230) diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index 282e5f72..029acefa 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -30,7 +30,8 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, ¤t); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE); + SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(1); // Enable vsync diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 3d66cbf2..246449af 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -54,7 +54,8 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, ¤t); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE); + SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_SetSwapInterval(1); // Enable vsync diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index a7404ec7..c5205750 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -308,7 +308,8 @@ int main(int, char**) // Setup window SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, ¤t); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_VULKAN|SDL_WINDOW_RESIZABLE); + SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); // Setup Vulkan uint32_t extensions_count = 0; From 7f6a025c93063a969d53091d269a846cbfd15db1 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Feb 2019 19:00:33 +0100 Subject: [PATCH 044/566] Viewport: SDL: Inherit SDL_WINDOW_ALLOW_HIGHDPI flag from main viewport. (#2306) --- examples/imgui_impl_sdl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index a1ab790d..902afad1 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -382,9 +382,9 @@ static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport) SDL_GL_MakeCurrent(main_viewport_data->Window, main_viewport_data->GLContext); } - // We don't enable SDL_WINDOW_RESIZABLE because it enforce windows decorations Uint32 sdl_flags = 0; sdl_flags |= use_opengl ? SDL_WINDOW_OPENGL : SDL_WINDOW_VULKAN; + sdl_flags |= SDL_GetWindowFlags(g_Window) & SDL_WINDOW_ALLOW_HIGHDPI; sdl_flags |= SDL_WINDOW_HIDDEN; sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0; sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE; From 169e3981fdf037b179f1c7296548892ba7837dae Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Feb 2019 19:09:54 +0100 Subject: [PATCH 045/566] Examples: OpenGL2: Added #define GL_SILENCE_DEPRECATION to cope with newer XCode warnings. --- docs/CHANGELOG.txt | 1 + examples/example_glfw_opengl2/main.cpp | 3 +++ examples/imgui_impl_opengl2.cpp | 1 + 3 files changed, 5 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c8dbff1c..91436fae 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,7 @@ Other Changes: - Examples: Win32: Added support for XInput games (if ImGuiConfigFlags_NavEnableGamepad is enabled). - Examples: Win32: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. (#2264) - Examples: DirectX9: Explicitly disable fog (D3DRS_FOGENABLE) before drawing in case user state has it set. (#2288, #2230) +- Examples: OpenGL2: Added #define GL_SILENCE_DEPRECATION to cope with newer XCode warnings. - Examples: OpenGL3: Using GLSL 4.10 shaders for any GLSL version over 410 (e.g. 430, 450). (#2329) [@BrutPitt] diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index eae7ed78..08463713 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -10,6 +10,9 @@ #include "imgui_impl_glfw.h" #include "imgui_impl_opengl2.h" #include +#ifdef __APPLE__ +#define GL_SILENCE_DEPRECATION +#endif #include // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers. diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index 99ca9690..5acccc08 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -44,6 +44,7 @@ #define WINGDIAPI __declspec(dllimport) // Some Windows OpenGL headers need this #endif #if defined(__APPLE__) +#define GL_SILENCE_DEPRECATION #include #else #include From cc80d8e118c1295a1bc005d2180b97e4778facb3 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Feb 2019 10:30:09 +0100 Subject: [PATCH 046/566] Examples: Metal: Compilation fix. --- examples/imgui_impl_metal.mm | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index 95c53236..a1ed7d74 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -402,8 +402,8 @@ void ImGui_ImplMetal_DestroyDeviceObjects() commandEncoder:(id)commandEncoder { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(drawData->DisplaySize.x * draw_data->FramebufferScale.x); - int fb_height = (int)(drawData->DisplaySize.y * draw_data->FramebufferScale.y); + int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x); + int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y); if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0) return; @@ -450,8 +450,8 @@ void ImGui_ImplMetal_DestroyDeviceObjects() [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0]; // Will project scissor/clipping rectangles into framebuffer space - ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports - ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists size_t vertexBufferOffset = 0; From 0640b6e67cddbfbbfc9856c12236a78550b310da Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Feb 2019 16:31:49 +0100 Subject: [PATCH 047/566] Shallow tweaks --- imgui.h | 14 +++++++------- imgui_widgets.cpp | 5 +++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/imgui.h b/imgui.h index be3434f3..943dd2f0 100644 --- a/imgui.h +++ b/imgui.h @@ -1948,12 +1948,12 @@ struct ImFontGlyphRangesBuilder ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) ImFontGlyphRangesBuilder() { UsedChars.resize(0x10000 / sizeof(int)); memset(UsedChars.Data, 0, 0x10000 / sizeof(int)); } - bool GetBit(int n) const { int off = (n >> 5); int mask = 1 << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array - void SetBit(int n) { int off = (n >> 5); int mask = 1 << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array - void AddChar(ImWchar c) { SetBit(c); } // Add character - IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) - IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext - IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges + bool GetBit(int n) const { int off = (n >> 5); int mask = 1 << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array + void SetBit(int n) { int off = (n >> 5); int mask = 1 << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array + void AddChar(ImWchar c) { SetBit(c); } // Add character + IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) + IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext + IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; enum ImFontAtlasFlags_ @@ -2096,7 +2096,7 @@ struct ImFont ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. bool DirtyLookupTables; // 1 // out // - float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() + float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() float Ascent, Descent; // 8 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 667cf3c4..17dbeda4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2832,8 +2832,9 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) { - ImFont* font = GImGui->Font; - const float line_height = GImGui->FontSize; + ImGuiContext& g = *GImGui; + ImFont* font = g.Font; + const float line_height = g.FontSize; const float scale = line_height / font->FontSize; ImVec2 text_size = ImVec2(0,0); From 417cf2237f6ad136cf36a9317b6e1af001865363 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Feb 2019 22:43:56 +0100 Subject: [PATCH 048/566] Font: Fixed high-level ImGui::CalcTextSize() used by most widgets from erroneously subtracting 1.0f*scale to calculated text width. Among noticeable side-effects, it would make sequences of repeated Text/SameLine calls not align the same as a single call, and create mismatch between high-level size calculation and those performed with the lower-level ImDrawList api. (#792) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 6 +----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 91436fae..7517c907 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,10 @@ Other Changes: - Window: Fixed initial width of collapsed windows not taking account of contents width (broken in 1.67). (#2336, #176) - ListBox: Better optimized when clipped / non-visible. - InputTextMultiline: Better optimized when clipped / non-visible. +- Font: Fixed high-level ImGui::CalcTextSize() used by most widgets from erroneously subtracting 1.0f*scale to + calculated text width. Among noticeable side-effects, it would make sequences of repeated Text/SameLine calls + not align the same as a single call, and create mismatch between high-level size calculation and those performed + with the lower-level ImDrawList api. (#792) [@SlNPacifist] - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" with a small number of segments (e.g. an hexagon). (#2287) [@baktery] - ImGuiTextBuffer: Added append() function (unformatted). diff --git a/imgui.cpp b/imgui.cpp index e2ddba18..3ca42628 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3909,11 +3909,7 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); - // Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field) - const float font_scale = font_size / font->FontSize; - const float character_spacing_x = 1.0f * font_scale; - if (text_size.x > 0.0f) - text_size.x -= character_spacing_x; + // Round text_size.x = (float)(int)(text_size.x + 0.95f); return text_size; From cbc8e57410ba1620577efd4aca8da79bf0d93bf5 Mon Sep 17 00:00:00 2001 From: Elias Daler Date: Wed, 13 Feb 2019 13:50:14 +0300 Subject: [PATCH 049/566] Update README.md - change imgui-sfml link (#2345) Changed link from https://github.com/EliasD/sfml to https://github.com/eliasdaler/sfml (no redirect + more reliable) --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index dd7aa18a..d1c1c272 100644 --- a/docs/README.md +++ b/docs/README.md @@ -150,7 +150,7 @@ Frameworks: - Magnum: [ImGuiIntegration](https://doc.magnum.graphics/magnum/namespaceMagnum_1_1ImGuiIntegration.html) ([example](https://doc.magnum.graphics/magnum/examples-imgui.html)) - NanoRT: [syoyo/imgui](https://github.com/syoyo/imgui/tree/nanort) - Qt: [imgui-qt3d](https://github.com/alpqr/imgui-qt3d) / [QOpenGLWindow (qtimgui)](https://github.com/ocornut/imgui/issues/1910) / [QtDirect3D](https://github.com/giladreich/QtDirect3D) / [qt6](https://github.com/alpqr/qvk6/tree/imgui/examples/rhi/imguidemo) -- SFML: [imgui-sfml](https://github.com/EliasD/imgui-sfml) +- SFML: [imgui-sfml](https://github.com/eliasdaler/imgui-sfml) - Software renderer: [imgui_software_renderer](https://github.com/emilk/imgui_software_renderer) - Unreal Engine 4: [segross/UnrealImGui](https://github.com/segross/UnrealImGui) or [sronsse/UnrealEngine_ImGui](https://github.com/sronsse/UnrealEngine_ImGui) From fcdf704dfaa71dc8820776afb629fef4d525a3e4 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Feb 2019 12:52:12 +0100 Subject: [PATCH 050/566] Changelog: Added changelog from 1.40 to 1.47 (pasted from the Releases section) + some wrapping. --- docs/CHANGELOG.txt | 597 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 548 insertions(+), 49 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7517c907..a895256a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -280,29 +280,36 @@ Changes: Breaking Changes: -- Style: Renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). +- Style: Renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. + Kept redirection enum (will obsolete). - Changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecision over time. -- Removed per-window ImGuiWindowFlags_ResizeFromAnySide Beta flag in favor `io.ConfigResizeWindowsFromEdges=true` to enable the feature globally. (#1495) +- Removed per-window ImGuiWindowFlags_ResizeFromAnySide Beta flag in favor `io.ConfigResizeWindowsFromEdges=true` to + enable the feature globally. (#1495) The feature is not currently enabled by default because it is not satisfying enough, but will eventually be. -- InputText: Renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. - Kept redirection types (will obsolete). -- InputText: Removed ImGuiTextEditCallbackData::ReadOnly since it is a duplication of (ImGuiTextEditCallbackData::Flags & ImGuiInputTextFlags_ReadOnly). +- InputText: Renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData + for consistency. Kept redirection types (will obsolete). +- InputText: Removed ImGuiTextEditCallbackData::ReadOnly because it is a duplication of (::Flags & ImGuiInputTextFlags_ReadOnly). - Renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent). -- Renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to io.ConfigMacOSXBehaviors for consistency. (#1427, #473) +- Renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to + io.ConfigMacOSXBehaviors for consistency. (#1427, #473) - Removed obsolete redirection functions: CollapsingHeader() variation with 2 bools - marked obsolete in v1.49, May 2016. Other Changes: - ArrowButton: Fixed to honor PushButtonRepeat() setting (and internals' ImGuiItemFlags_ButtonRepeat). - ArrowButton: Setup current line text baseline so that ArrowButton() + SameLine() + Text() are aligned properly. -- Nav: Added a CTRL+TAB window list and changed the highlight system accordingly. The change is motivated by upcoming Docking features. (#787) +- Nav: Added a CTRL+TAB window list and changed the highlight system accordingly. The change is motivated by upcoming + Docking features. (#787) - Nav: Made CTRL+TAB skip menus + skip the current navigation window if is has the ImGuiWindow_NoNavFocus set. (#787) - While it was previously possible, you won't be able to CTRL-TAB out and immediately back in a window with the ImGuiWindow_NoNavFocus flag. + While it was previously possible, you won't be able to CTRL-TAB out and immediately back in a window with the + ImGuiWindow_NoNavFocus flag. - Window: Allow menu and popups windows from ignoring the style.WindowMinSize values so short menus/popups are not padded. (#1909) -- Window: Added global io.ConfigResizeWindowsFromEdges option to enable resizing windows from their edges and from the lower-left corner. (#1495) +- Window: Added global io.ConfigResizeWindowsFromEdges option to enable resizing windows from their edges and from + the lower-left corner. (#1495) - Window: Collapse button shows hovering highlight + clicking and dragging on it allows to drag the window as well. -- Added IsItemEdited() to query if the last item modified its value (or was pressed). This is equivalent to the bool returned by most widgets. +- Added IsItemEdited() to query if the last item modified its value (or was pressed). This is equivalent to the bool + returned by most widgets. It is useful in some situation e.g. using InputText() with ImGuiInputTextFlags_EnterReturnsTrue. (#2034) - InputText: Added support for buffer size/capacity changes via the ImGuiInputTextFlags_CallbackResize flag. (#2006, #1443, #1008). - InputText: Fixed not tracking the cursor horizontally when modifying the text buffer through a callback. @@ -365,11 +372,14 @@ Other Changes: Breaking Changes: -- TreeNodeEx(): The helper ImGuiTreeNodeFlags_CollapsingHeader flag now include ImGuiTreeNodeFlags_NoTreePushOnOpen. The flag was already set by CollapsingHeader(). - The only difference is if you were using TreeNodeEx() manually with ImGuiTreeNodeFlags_CollapsingHeader and without ImGuiTreeNodeFlags_NoTreePushOnOpen. - In this case you can remove the ImGuiTreeNodeFlags_NoTreePushOnOpen flag from your call (ImGuiTreeNodeFlags_CollapsingHeader & ~ImGuiTreeNodeFlags_NoTreePushOnOpen). (#1864) +- TreeNodeEx(): The helper ImGuiTreeNodeFlags_CollapsingHeader flag now include ImGuiTreeNodeFlags_NoTreePushOnOpen. + The flag was already set by CollapsingHeader(). + The only difference is if you were using TreeNodeEx() manually with ImGuiTreeNodeFlags_CollapsingHeader and without + ImGuiTreeNodeFlags_NoTreePushOnOpen. In this case you can remove the ImGuiTreeNodeFlags_NoTreePushOnOpen flag from + your call (ImGuiTreeNodeFlags_CollapsingHeader & ~ImGuiTreeNodeFlags_NoTreePushOnOpen). (#1864) This also apply if you were using internal's TreeNodeBehavior() with the ImGuiTreeNodeFlags_CollapsingHeader flag directly. -- ImFontAtlas: Renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish new smaller variants and discourage using the full set. (#1859) +- ImFontAtlas: Renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish new smaller variants and + discourage using the full set. (#1859) Other Changes: @@ -382,12 +392,13 @@ Other Changes: before: imgui_impl_glfw_vulkan.cpp --> after: imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp before: imgui_impl_sdl_gl3.cpp --> after: imgui_impl_sdl2.cpp + imgui_impl_opengl2.cpp before: imgui_impl_sdl_gl3.cpp --> after: imgui_impl_sdl2.cpp + imgui_impl_opengl3.cpp etc. - - The idea is what we can now easily combine and maintain back-ends and reduce code redundancy. Individual files are smaller and more reusable. - Integration of imgui into a new/custom engine may also be easier as there is less overlap between "windowing / inputs" and "rendering" code, - so you may study or grab one half of the code and not the other. - - This change was motivated by the fact that adding support for the upcoming multi-viewport feature requires more work from the Platform and Renderer - back-ends, and the amount of redundancy across files was becoming too difficult to maintain. If you use default back-ends, you'll benefit from an - easy update path to support multi-viewports later (for future ImGui 1.7x). + - The idea is what we can now easily combine and maintain back-ends and reduce code redundancy. Individual files are + smaller and more reusable. Integration of imgui into a new/custom engine may also be easier as there is less overlap + between "windowing / inputs" and "rendering" code, so you may study or grab one half of the code and not the other. + - This change was motivated by the fact that adding support for the upcoming multi-viewport feature requires more work + from the Platform and Renderer back-ends, and the amount of redundancy across files was becoming too difficult to + maintain. If you use default back-ends, you'll benefit from an easy update path to support multi-viewports later + (for future ImGui 1.7x). - This is not strictly a breaking change if you keep your old bindings, but when you'll want to fully update your bindings, expect to have to reshuffle a few things. - Each example still has its own main.cpp which you may refer you to understand how to initialize and glue everything together. @@ -400,26 +411,36 @@ Other Changes: - Nav: Added support for PageUp/PageDown (explorer-style: first aim at bottom/top most item, when scroll a page worth of contents). (#787) - Nav: To keep the navigated item in view we also attempt to scroll the parent window as well as the current window. (#787) - ColorEdit3, ColorEdit4, ColorButton: Added ImGuiColorEditFlags_NoDragDrop flag to disable ColorEditX as drag target and ColorButton as drag source. (#1826) -- BeginDragDropSource(): Offset tooltip position so it is off the mouse cursor, but also closer to it than regular tooltips, and not clamped by viewport. (#1739) -- BeginDragDropTarget(): Added ImGuiDragDropFlags_AcceptNoPreviewTooltip flag to request hiding the drag source tooltip from the target site. (#143) -- BeginCombo(), BeginMainMenuBar(), BeginChildFrame(): Temporary style modification are restored at the end of BeginXXX instead of EndXXX, to not affect tooltips and child windows. +- BeginDragDropSource(): Offset tooltip position so it is off the mouse cursor, but also closer to it than regular tooltips, + and not clamped by viewport. (#1739) +- BeginDragDropTarget(): Added ImGuiDragDropFlags_AcceptNoPreviewTooltip flag to request hiding the drag source tooltip + from the target site. (#143) +- BeginCombo(), BeginMainMenuBar(), BeginChildFrame(): Temporary style modification are restored at the end of BeginXXX + instead of EndXXX, to not affect tooltips and child windows. - Popup: Improved handling of (erroneously) repeating calls to OpenPopup() to not close the popup's child popups. (#1497, #1533, #1865). - InputTextMultiline(): Fixed double navigation highlight when scrollbar is active. (#787) -- InputText(): Fixed Undo corruption after pasting large amount of text (Redo will still fail when undo buffers are exhausted, but text won't be corrupted). +- InputText(): Fixed Undo corruption after pasting large amount of text (Redo will still fail when undo buffers are exhausted, + but text won't be corrupted). - SliderFloat(): When using keyboard/gamepad and a zero precision format string (e.g. "%.0f"), always step in integer units. (#1866) -- ImFontConfig: Added GlyphMinAdvanceX/GlyphMaxAdvanceX settings useful to make a font appears monospaced, particularly useful for icon fonts. (#1869) -- ImFontAtlas: Added GetGlyphRangesChineseSimplifiedCommon() helper that returns a list of ~2500 most common Simplified Chinese characters. (#1859) [@JX-Master, @ocornut] +- ImFontConfig: Added GlyphMinAdvanceX/GlyphMaxAdvanceX settings useful to make a font appears monospaced, particularly useful + for icon fonts. (#1869) +- ImFontAtlas: Added GetGlyphRangesChineseSimplifiedCommon() helper that returns a list of ~2500 most common Simplified Chinese + characters. (#1859) [@JX-Master, @ocornut] - Examples: OSX: Added imgui_impl_osx.mm binding to be used along with e.g. imgui_impl_opengl2.cpp. (#281, #1870) [@pagghiu, @itamago, @ocornut] - Examples: GLFW: Made it possible to Shutdown/Init the backend again (by reseting the time storage properly). (#1827) [@ice1000] - Examples: Win32: Fixed handling of mouse wheel messages to support sub-unit scrolling messages (typically sent by track-pads). (#1874) [@zx64] - Examples: SDL+Vulkan: Added SDL+Vulkan example. - Examples: Allegro5: Added support for ImGuiConfigFlags_NoMouseCursorChange flag. Added clipboard support. -- Examples: Allegro5: Unindexing buffers ourselves as Allegro indexed drawing primitives are buggy in the DirectX9 back-end (will be fixed in Allegro 5.2.5+). +- Examples: Allegro5: Unindexing buffers ourselves as Allegro indexed drawing primitives are buggy in the DirectX9 back-end + (will be fixed in Allegro 5.2.5+). - Examples: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from ImGui_ImplDX12_NewFrame() to ImGui_ImplDX12_RenderDrawData() which makes a lots more sense. (#301) -- Examples: Vulkan: Reordered parameters ImGui_ImplVulkan_RenderDrawData() to be consistent with other bindings, a good occasion since we refactored the code. +- Examples: Vulkan: Reordered parameters ImGui_ImplVulkan_RenderDrawData() to be consistent with other bindings, + a good occasion since we refactored the code. - Examples: FreeGLUT: Added FreeGLUT bindings. Added FreeGLUT+OpenGL2 example. (#801) -- Examples: The functions in imgui_impl_xxx.cpp are prefixed with IMGUI_IMPL_API (which defaults to IMGUI_API) to facilitate some uses. (#1888) -- Examples: Fixed bindings to use ImGuiMouseCursor_COUNT instead of old name ImGuiMouseCursor_Count_ so they can compile with IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#1887) +- Examples: The functions in imgui_impl_xxx.cpp are prefixed with IMGUI_IMPL_API (which defaults to IMGUI_API) to facilitate + some uses. (#1888) +- Examples: Fixed bindings to use ImGuiMouseCursor_COUNT instead of old name ImGuiMouseCursor_Count_ so they can compile + with IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#1887) - Misc: Updated stb_textedit from 1.09 + patches to 1.12 + minor patches. - Internals: PushItemFlag() flags are inherited by BeginChild(). @@ -430,41 +451,56 @@ Other Changes: Breaking Changes: -- DragInt(): The default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. - If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format. - To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code. - If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to you find them. -- InputFloat(): Obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format", - consistent with other functions. Kept redirection functions (will obsolete). -- Misc: IM_DELETE() helper function added in 1.60 doesn't set the input pointer to NULL, more consistent with standard expectation and allows passing r-values. +- DragInt(): The default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally + any more. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format. + To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, + giving time to users to upgrade their code. + If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your + codebase for e.g. "DragInt.*%f" to you find them. +- InputFloat(): Obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more + flexible "const char* format", consistent with other functions. Kept redirection functions (will obsolete). +- Misc: IM_DELETE() helper function added in 1.60 doesn't set the input pointer to NULL, more consistent with standard + expectation and allows passing r-values. Other Changes: - Added DragScalar, DragScalarN: supports signed/unsigned, 32/64 bits, float/double data types. (#643, #320, #708, #1011) - Added InputScalar, InputScalarN: supports signed/unsigned, 32/64 bits, float/double data types. (#643, #320, #708, #1011) - Added SliderScalar, SliderScalarN: supports signed/unsigned, 32/64 bits, float/double data types. (#643, #320, #708, #1011) -- Window: Fixed pop-ups/tooltips/menus not honoring style.DisplaySafeAreaPadding as well as it should have (part of menus displayed outside the safe area, etc.). +- Window: Fixed pop-ups/tooltips/menus not honoring style.DisplaySafeAreaPadding as well as it should have (part of menus + displayed outside the safe area, etc.). - Window: Fixed windows using the ImGuiWindowFlags_NoSavedSettings flag from not using the same default position as other windows. (#1760) - Window: Relaxed the internal stack size checker to allow Push/Begin/Pop/.../End patterns to be used with PushStyleColor, PushStyleVar, PushFont without causing a false positive assert. (#1767) - Window: Fixed the default proportional item width lagging by one frame on resize. -- Columns: Fixed a bug introduced in 1.51 where columns would affect the contents size of their container, often creating feedback loops when ImGuiWindowFlags_AlwaysAutoResize was used. (#1760) +- Columns: Fixed a bug introduced in 1.51 where columns would affect the contents size of their container, often creating + feedback loops when ImGuiWindowFlags_AlwaysAutoResize was used. (#1760) - Settings: Fixed saving an empty .ini file if CreateContext/DestroyContext are called without a single call to NewFrame(). (#1741) -- Settings: Added LoadIniSettingsFromDisk(), LoadIniSettingsFromMemory(), SaveIniSettingsToDisk(), SaveIniSettingsToMemory() to manually load/save .ini settings. (#923, #993) -- Settings: Added io.WantSaveIniSettings flag, which is set to notify the application that e.g. SaveIniSettingsToMemory() should be called. (#923, #993) -- Scrolling: Fixed a case where using SetScrollHere(1.0f) at the bottom of a window on the same frame the window height has been growing would have the scroll clamped using the previous height. (#1804) -- MenuBar: Made BeginMainMenuBar() honor style.DisplaySafeAreaPadding so the text can be made visible on TV settings that don't display all pixels. (#1439) [@dougbinks] +- Settings: Added LoadIniSettingsFromDisk(), LoadIniSettingsFromMemory(), SaveIniSettingsToDisk(), SaveIniSettingsToMemory() + to manually load/save .ini settings. (#923, #993) +- Settings: Added io.WantSaveIniSettings flag, which is set to notify the application that e.g. SaveIniSettingsToMemory() + should be called. (#923, #993) +- Scrolling: Fixed a case where using SetScrollHere(1.0f) at the bottom of a window on the same frame the window height + has been growing would have the scroll clamped using the previous height. (#1804) +- MenuBar: Made BeginMainMenuBar() honor style.DisplaySafeAreaPadding so the text can be made visible on TV settings that + don't display all pixels. (#1439) [@dougbinks] - InputText: On Mac OS X, filter out characters when the CMD modifier is held. (#1747) [@sivu] - InputText: On Mac OS X, support CMD+SHIFT+Z for Redo. CMD+Y is also supported as major apps seems to default to support both. (#1765) [@lfnoise] - InputText: Fixed returning true when edition is cancelled with ESC and the current buffer matches the initial value. -- InputFloat,InputFloat2,InputFloat3,InputFloat4: Added variations taking a more flexible and consistent optional "const char* format" parameter instead of "int decimal_precision". - This allow using custom formats to display values in scientific notation, and is generally more consistent with other API. Obsoleted functions using the optional "int decimal_precision" parameter. (#648) -- DragFloat, DragInt: Cancel mouse tweak when current value is initially past the min/max boundaries and mouse is pushing in the same direction (keyboard/gamepad version already did this). +- InputFloat,InputFloat2,InputFloat3,InputFloat4: Added variations taking a more flexible and consistent optional + "const char* format" parameter instead of "int decimal_precision". This allow using custom formats to display values + in scientific notation, and is generally more consistent with other API. + Obsoleted functions using the optional "int decimal_precision" parameter. (#648) +- DragFloat, DragInt: Cancel mouse tweak when current value is initially past the min/max boundaries and mouse is pushing + in the same direction (keyboard/gamepad version already did this). - DragFloat, DragInt: Honor natural type limits (e.g. INT_MAX, FLT_MAX) instead of wrapping around. (#708, #320) - DragFloat, SliderFloat: Fixes to allow input of scientific notation numbers when using CTRL+Click to input the value. (~#648, #1011) -- DragFloat, SliderFloat: Rounding-on-write uses the provided format string instead of parsing the precision from the string, which allows for finer uses of %e %g etc. (#648, #642) -- DragFloat: Improved computation when using the power curve. Improved lost of input precision with very small steps. Added an assert than power-curve requires a min/max range. (~#642) +- DragFloat, SliderFloat: Rounding-on-write uses the provided format string instead of parsing the precision from the string, + which allows for finer uses of %e %g etc. (#648, #642) +- DragFloat: Improved computation when using the power curve. Improved lost of input precision with very small steps. + Added an assert than power-curve requires a min/max range. (~#642) - DragFloat: The 'power' parameter is only honored if the min/max parameter are also setup. -- DragInt, SliderInt: Fixed handling of large integers (we previously passed data around internally as float, which reduced the range of valid integers). +- DragInt, SliderInt: Fixed handling of large integers (we previously passed data around internally as float, which reduced + the range of valid integers). - ColorEdit: Fixed not being able to pass the ImGuiColorEditFlags_NoAlpha or ImGuiColorEditFlags_HDR flags to SetColorEditOptions(). - Nav: Fixed hovering a Selectable() with the mouse so that it update the navigation cursor (as it happened in the pre-1.60 navigation branch). (#787) - Style: Changed default style.DisplaySafeAreaPadding values from (4,4) to (3,3) so it is smaller than FramePadding and has no effect on main menu bar on a computer. (#1439) @@ -1201,6 +1237,469 @@ Other Changes: - Various extra comments and clarification in the code. - Various other fixes and optimizations. + +----------------------------------------------------------------------- + VERSION 1.47 (2015-12-25) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.47 + +Changes: + +- Rebranding "ImGui" -> "dear imgui" as an optional first name to reduce ambiguity with IMGUI term. (#21) +- Added ProgressBar(). (#333) +- InputText(): Added ImGuiInputTextFlags_Password mode: hide display, disable logging/copying to clipboard. (#237, #363, #374) +- Added GetColorU32() helper to retrieve color given enum with global alpha and extra applied. +- Added ImGuiIO::ClearInputCharacters() superfluous helper. +- Fixed ImDrawList draw command merging bug where using PopClipRect() along with PushTextureID()/PopTextureID() functions + would occasionally restore an incorrect clipping rectangle. +- Fixed ImDrawList draw command merging so PushTextureID(XXX)/PopTextureID()/PushTextureID(XXX) sequence are now properly merged. +- Fixed large popups positioning issues when their contents on either axis is larger than DisplaySize, + and WindowPadding < DisplaySafeAreaPadding. +- Fixed border rendering in various situations when using non-pixel aligned glyphs. +- Fixed border rendering of windows to always contain the border within the window. +- Fixed Shutdown() leaking font atlas data if NewFrame() was never called. (#396, #303) +- Fixed int>void\* warnings for 64-bits architectures with fancy warnings enabled. +- Renamed the dubious Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. +- InputText(): Fixed and better handling of using keyboard while mouse button if being held and dragging. (#429) +- InputText(): Replace OS IME (Input Method Editor) cursor on top-left when we are not text editing. +- TreeNode(), CollapsingHeader(), Bullet(), BulletText(): various sizing and layout fixes to better support laying out + multiple item with different height on same line. (#414, #282) +- Begin(): Initial window creation with ImGuiWindowFlags_NoBringToFrontOnFocus flag pushes it at the front of global window list. +- BeginPopupContextWindow() and BeginPopupContextVoid() reopen window on subsequent click. (#439) +- ColorEdit4(): Fixed broken tooltip on hovering the color button. (actually fixes #373, #380) +- ImageButton(): uses FrameRounding up to a maximum of available framing size. (#394) +- Columns: Fixed bug with indentation within columns, also making code a bit shorter/faster. (#414, #125) +- Columns: Columns set with no implicit id include the columns count within the id to reduce collisions. (#125) +- Columns: Removed one unnecessary allocation when columns are not used by a window. (#125) +- ImFontAtlas: Tweaked GetGlyphRangesJapanese() so it is easier to modify. +- ImFontAtlas: Updated stb_rect_pack.h to 0.08. +- Metrics: Fixed computing ImDrawCmd bounding box when the draw buffer have been unindexed. +- Demo: Added a simple "Property Editor" demo applet. (#125, #414) +- Demo: Fixed assertion in "Custom Rendering" demo when holding both mouse buttons. (#393) +- Demo: Lots of extra comments, fixes. +- Demo: Tweaks to Style Editor. +- Examples: Not clearing input data/tex data in atlas (will be required for dynamic atlas anyway). +- Examples: Added /Zi (output debug information) to Win32 batch files. +- Examples: Various fixes for resizing window and recreating graphic context. +- Examples: OpenGL2/3: Save/restore viewport as part of default render function. (#392, #441). +- Examples; OpenGL3: Fixed gl3w.c for Linux when compiled with a C++ compiler. (#411) +- Examples: DirectX: Removed assumption about Unicode build in example main.cpp. (#399) +- Examples: DirectX10: Added DirectX10 example. (#424) +- Examples: DirectX11: Downgraded requirement from shader model 5.0 to 4.0. (#420) +- Examples: DirectX11: Removed Debug flag from graphics context. (#415) +- Examples: Added SDL+OpenGL3 example. (#356) + + +----------------------------------------------------------------------- + VERSION 1.46 (2015-10-18) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.46 + +Changes: + +- Begin*(): added ImGuiWindowFlags_NoFocusOnAppearing flag. (#314) +- Begin*(): added ImGuiWindowFlags_NoBringToFrontOnFocus flag. +- Added GetDrawData() alternative to setting a Render function pointer in ImGuiIO structure. +- Added SetClipboardText(), GetClipboardText() helper shortcuts that user code can call directly without reading + from the ImGuiIO structure (to match MemAlloc/MemFree) +- Fixed handling of malformed UTF-8 at the end of a non-zero terminated string range. +- Fixed mouse click detection when passing DeltaTime 0.0. (#338) +- Fixed IsKeyReleased() and IsMouseReleased() returning true on the first frame. +- Fixed using SetNextWindow\* functions on Modal windows with a ImGuiSetCond_Appearing condition. (#377) +- IsMouseHoveringRect(): Added 'bool clip' parameter to disable clipping provided rectangle. (#316) +- InputText(): added ImGuiInputTextFlags_ReadOnly flag. (#211) +- InputText(): lose cursor/undo-stack when reactivating focus is buffer has changed size. +- InputText(): fixed ignoring text inputs when ALT or ALTGR are pressed. (#334) +- InputText(): fixed mouse-dragging not tracking the cursor when text doesn't fit. (#339) +- InputText(): fixed cursor pixel-perfect alignment when horizontally scrolling. +- InputText(): fixed crash when passing a buf_size==0 (which can be of use for read-only selectable text boxes). (#360) +- InputFloat() fixed explicit precision modifier, both display and input were broken. +- PlotHistogram(): improved rendering of histogram with a lot of values. +- Dummy(): creates an item so functions such as IsItemHovered() can be used. +- BeginChildFrame() helper: added the extra_flags parameter. +- Scrollbar: fixed rounding of background + child window consistenly have ChildWindowBg color under ScrollbarBg fill. (#355). +- Scrollbar: background color less translucent in default style so it works better when changing background color. +- Scrollbar: fixed minor rendering offset when borders are enabled. (#365) +- ImDrawList: fixed 1 leak per ImDrawList using the ChannelsSplit() API (via Columns). (#318) +- ImDrawList: fixed rectangle rendering glitches with width/height <= 1/2 and rounding enabled. +- ImDrawList: AddImage() uv parameters default to (0,0) and (1,1). +- ImFontAtlas: Added TexDesiredWidth and tweaked default cheapo best-width choice. (#327) +- ImFontAtlas: Added GetGlyphRangesKorean() helper to retrieve unicode ranges for Korean. (#348) +- ImGuiTextFilter::Draw() helper return bool and build when filter is modified. +- ImGuiTextBuffer: added c_str() helper. +- ColorEdit4(): fixed hovering the color button always showing 1.0 alpha. (#373) +- ColorConvertFloat4ToU32() round the floats instead of truncating them. +- Window: Fixed window lower-right clipping limit so it plays more friendly with both OpenGL and DirectX coordinates. +- Internal: Extracted a EndFrame() function out of Render() but kept it internal/private + clarified some asserts. (#335) +- Internal: Added missing IMGUI_API definitions in imgui_internal.h (#326) +- Internal: ImLoadFileToMemory() return void\* instead of taking void*\* + allow optional int\* file_size. +- Demo: Horizontal scrollbar demo allows to enable simultanaeous scrollbars on both axises. +- Tools: binary_to_compressed_c.cpp: added -nocompress option. +- Examples: Added example for the Marmalade platform. +- Examples: Added batch files to build Windows examples with VS. +- Examples: OpenGL3: Saving/restoring more GL state correctly. (#347) +- Examples: OpenGL2/3: Added msys2/mingw64 target to Makefiles. + + +----------------------------------------------------------------------- + VERSION 1.45 (2015-09-01) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.45 + +Breaking Changes: + +- With the addition of better horizontal scrolling primitives I had to make some consistency fixes. + `GetCursorPos()` `SetCursorPos()` `GetContentRegionMax()` `GetWindowContentRegionMin()` `GetWindowContentRegionMax()` + are now incorporating the scrolling amount. They were incorrectly not incorporating this amount previously. + It PROBABLY shouldn't break anything, but that depends on how you used them. Namely: + - If you always used SetCursorPos() with values relative to GetCursorPos() there shouldn't be a problem. + However if you used absolute coordinates, note that SetCursorPosY(100.0f) will put you at +100 from the initial Y position (which may be scrolled out of the view), NOT at +100 from the window top border. Since there wasn't any official scrolling value on X axis (past just manually moving the cursor) this can only affect you if you used to set absolute coordinates on the Y axis which is hopefully rare/unlikely, and trivial to fix. + - The value of GetWindowContentRegionMax() isn't necessarily close to GetWindowWidth() if horizontally scrolling. + Previously they were roughly interchangeable (roughly because the content region exclude window padding). + +Other Changes: + +- Added Horizontal Scrollbar via ImGuiWindowFlags_HorizontalScroll (#246). +- Added GetScrollX(), GetScrollX(), GetScrollMaxX() apis (#246). +- Added SetNextWindowContentSize(), SetNextWindowContentWidth() to explicitly set the content size of a window, which + define the range of scrollbar. When set explicitly it also define the base value from which widget width are derived. +- Added IO.WantTextInput telling when ImGui is expecting text input, so that e.g. OS on-screen keyboard can be enabled. +- Added printf attribute to printf-like text formatting functions (Clang/GCC). +- Added GetMousePosOnOpeningCurrentPopup() helper. +- Added GetContentRegionAvailWidth() helper. +- Malformed UTF-8 data don't terminate string, output 0xFFFD instead (#307). +- ImDrawList: Added AddBezierCurve(), PathBezierCurveTo() API for cubic bezier curves (#311). +- ImDrawList: Allow to override ImDrawIdx type (#292). +- ImDrawList: Added an assert on overflowing index value (#292). +- ImDrawList: Fixed issues with channels split/merge. Now functional without manually adding a draw cmd. Added comments. +- ImDrawData: Added ScaleClipRects() helper useful when rendering scaled. (#287). +- Fixed Bullet() inconsistent layout behaviour when clipped. +- Fixed IsWindowHovered() not taking account of window hoverability (may be disabled because of a popup). +- Fixed InvisibleButton() not honoring negative size consistently with other widgets that do so. +- Fixed OpenPopup() accessing current window, effectively opening "Debug" when called from an empty window stack. +- TreeNode(): Fixed IsItemHovered() result being inconsistent with interaction visuals (#282). +- TreeNode(): Fixed mouse interaction padding past the node label being accounted for in layout (#282). +- BeginChild(): Passing a ImGuiWindowFlags_NoMove inhibits moving parent window from this child. +- BeginChild() fixed missing rounding for child sizes which leaked into layout and have items misaligned. +- Begin(): Removed default name = "Debug" parameter. We already have a "Debug" window pushed to the stack in the first place so it's not really a useful default. +- Begin(): Minor fixes with windows main clipping rectangle (e.g. child window with border). +- Begin(): Window flags are only read on the first call of the frame. Subsequent calls ignore flags, which allows appending to a window without worryin about flags. +- InputText(): ignore character input when ctrl/alt are held. (Normally those text input are ignored by most wrappers.) (#279). +- Demo: Fixed incorrectly formed string passed to Combo (#298). +- Demo: Added simple Log demo. +- Demo: Added horizontal scrolling example + enabled in console, log and child examples (#246). +- Style: made scrollbars rounded by default. Because nice. Minor menu bar background alpha tweak. (#246) +- Metrics: display indices along with triangles count (#299) and some internal state. +- ImGuiTextFilter::PassFilter() supports string range. Added [] helper to ImGuiTextBuffer. +- ImGuiTextFilter::Draw() default parameter width=0.0f for no override, allow override with negative values. +- Examples: OpenGL2/OpenGL3: fix for retina displays. Default font current lack crispness. +- Examples: OpenGL2/OpenGL3: save/restore more GL state correctly. +- Examples: DirectX9/DirectX11: resizing buffers dynamically (#299). +- Examples: DirectX9/DirectX11: added missing middle mouse button to Windows event handler. +- Examples: DirectX11: fix for Visual Studio 2015 presumably shipping with an updated version of DX11. +- Examples: iOS: fixed missing files in project. + + +----------------------------------------------------------------------- + VERSION 1.44 (2015-08-08) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.44 + +Breaking Changes: + +- imgui.cpp has been split intro extra files: imgui_demo.cpp, imgui_draw.cpp, imgui_internal.h. + Add the two extra .cpp to your project or #include them from another .cpp file. (#219) + +Other Changes: + +- Internal data structure and several useful functions are now exposed in imgui_internal.h. This should make it easier + and more natural to extend ImGui. However please note that none of the content in imgui_internal.h is guaranteed + for forward-compatibility and code using those types/functions may occasionally break. (#219) +- All sample code is in imgui_demo.cpp. Please keep this file in your project and consider allowing your code to call + the ShowTestWindow() function as de-facto guide to ImGui features. It will be stripped out by the linker when unused. +- Added GetContentRegionAvail() helper (basically GetContentRegionMax() - GetCursorPos()). +- Added ImGuiWindowFlags_NoInputs for totally input-passthru window. +- Button(): honor negative size consistently with other widgets that do so (width -100 to align the button 100 pixels + before the right-most position of the contents region). +- InputTextMultiline(): honor negative size consistently with other widgets that do so. +- Combo() clamp popup to lower edge of visible area. +- InputInt(): value doesn't pass through an int>float>int casting chain, fix handling lost of precision with "large" integer. +- InputInt() allow hexadecimal input (awkwardly via ImGuiInputTextFlags_CharsHexadecimal but we will allow format + string in InputInt* later). +- Checkbox(), RadioButton(): fixed scaling of checkbox and radio button for the filling of "active" visual. +- Columns: never assume horizontal space for scrollbar if NoScrollbar flag is explicitly set. +- Slider: fixed using FramePadding between frame and grab visual. Scaling that spacing would look odd. +- Fixed lower-right resize grip hit box not scaling along with its rendered size (#287) +- ImDrawList: Fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (v1.43) being off by an extra PI for no reason. +- ImDrawList: Added ImDrawList::AddText() shorthand helper. +- ImDrawList: Add missing support for anti-aliased thick-lines (#133, also ref #288) +- ImFontAtlas: Added AddFontFromMemoryCompressedBase85TTF() to load base85 encoded font string. Default font encoded + as base85 saves ~100 lines / 26 KB of source code. Added base85 output to the binary_to_compressed_c tool. +- Build fix for MinGW (#276). +- Examples: OpenGL3: Fixed running on script core profiles for OSX (#277). +- Examples: OpenGL3: Simplified code using glBufferData for vertices as well (#277, #278) +- Examples: DirectX11: Clear font texture view to ensure Release() doesn't get called twice (#290). +- Updated to stb_truetype 1.07 (back to vanilla version as our minor changes are now in master & fix unlikely assert + with odd fonts (#280) + + +----------------------------------------------------------------------- + VERSION 1.43 (2015-07-17) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.43 + +Breaking Changes: + +- This is a rather important release and we unfortunately had to break the rendering API. + ImGui now requires you to render indexed vertices instead of non-indexed ones. The fix should be very easy. + Sorry for that! This change is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. + Each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles + using indices from the index buffer. +- If you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update + your copy and you can ignore the rest. +- The signature of the io.RenderDrawListsFn handler has changed + From: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) + To: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data) + With: argument 'cmd_lists' -> 'draw_data->CmdLists' + argument 'cmd_lists_count' -> 'draw_data->CmdListsCount' + ImDrawList 'commands' -> 'CmdBuffer' + ImDrawList 'vtx_buffer' -> 'VtxBuffer' + ImDrawList n/a -> 'IdxBuffer' (new) + ImDrawCmd 'vtx_count' -> 'ElemCount' + ImDrawCmd 'clip_rect' -> 'ClipRect' + ImDrawCmd 'user_callback' -> 'UserCallback' + ImDrawCmd 'texture_id' -> 'TextureId' +- If you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index + the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! + Refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. Please upgrade! + +Other Changes: + +- Added anti-aliasing on lines and shapes based on primitives by @MikkoMononen (#133). + Between the use of indexed-rendering and the fact that the entire rendering codebase has been optimized and massaged + enough, with anti-aliasing enabled ImGui 1.43 is now running FASTER than 1.41. + Made some extra effort in making the code run faster in your typical Debug build. +- Anti-aliasing can be disabled in the ImGuiStyle structure via the AntiAliasedLines/AntiAliasedShapes fields for further gains. +- ImDrawList: Added AddPolyline(), AddConvexPolyFilled() with optional anti-aliasing. +- ImDrawList: Added stateful path building and stroking API. PathLineTo(), PathArcTo(), PathRect(), PathFill(), PathStroke() + with optional anti-aliasing. +- ImDrawList: Added AddRectFilledMultiColor() helper. +- ImDrawList: Added multi-channel rendering so out of order elements can be rendered in separate channels and then merged + back together (used by columns). +- ImDrawList: Fixed merging draw commands when equal clip rectangles are in the two first commands. +- ImDrawList: Fixed window draw lists not destructed properly on Shutdown(). +- ImDrawData: Added DeIndexAllBuffers() helper. +- Added lots of new font options ImFontAtlas::AddFont() and the new ImFontConfig structure. + - Added support for oversampling (ImFontConfig: OversampleH, OversampleV) and sub-pixel positioning (ImFontConfig: PixelSnapH). + Oversampling allows sub-pixel positioning but can also be used as a way to get some leeway with scaling fonts without re-rasterizing. + - Added GlyphExtraSpacing option to add extra horizontal spacing between characters (#242). + - Added MergeMode option to merge glyphs from different font inputs into a same font (#182, #232). + - Added FontDataOwnedByAtlas option to keep ownership from the TTF data buffer and request the atlas to make a copy (#220). +- Updated to stb_truetype 1.06 (+ minor mods) with better font rasterization. +- InputText: Added ImGuiInputTextFlags_NoHorizontalScroll flag. +- InputText: Added ImGuiInputTextFlags_AlwaysInsertMode flag. +- InputText: Added HasSelection() helper in ImGuiTextEditCallbackData as a clarification. +- InputText: Fix for using END key on a multi-line text editor (#275) +- Columns: Dispatch render of each column in a sub-draw list and merge on closure, saving a lot of draw calls! (#125) +- Popups: Fixed Combo boxes inside menus. (#272) +- Style: Added GrabRounding setting to make the sliders etc. grabs rounded. +- Changed SameLine() parameters from int to float. +- Fixed incorrect assert triggering when code stole ActiveID from user moving a window by calling e.g. SetKeyboardFocusHere(). +- Fixed CollapsingHeader() label rendering outside its frame in columns context where ClipRect max isn't aligned with the + right-side of the header. +- Metrics window: calculate bounding box of actual vertices when hovering a draw list. +- Examples: Showing more information in the Fonts section. +- Examples: Added a gratuitous About window. +- Examples: Updated all examples code (OpenGL/DX9/DX11/SDL/Allegro/iOS) to use indexed rendering. +- Examples: Fixed the SDL2 example to support Unicode text input (#274). + + +----------------------------------------------------------------------- + VERSION 1.42 (2015-07-08) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.42 + +Breaking Changes: + +- Renamed SetScrollPosHere() to SetScrollHere(). Kept inline redirection function (will obsolete). +- Renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion and make scrolling API consistent, + because positions (e.g. cursor position) are not equivalent to scrolling amount. +- Removed obsolete GetDefaultFontData() function that would assert anyway. + If you are updating from <1.30 you'll get a compile error instead of an assertion. (obsoleted 2015/01/11) + +Other Changes: + +- Added SDL2 example application (courtesy of @CedricGuillemet) +- Added iOS example application (courtesy of @joeld42) +- Added Allegro 5 example application (courtesy of @bggd) +- Added TitleBgActive color in style so focused window is made visible. (#253) +- Added CaptureKeyboardFromApp() / CaptureMouseFromApp() to manually enforce inputs capturing. +- Added DragFloatRange2() DragIntRange2() helpers. (#76) +- Added a Y centering ratio to SetScrollFromCursorPos() which can be used to aim the top or bottom of the window. (#150) +- Added SetScrollY(), SetScrollFromPos(), GetCursorStartPos() for manual scrolling manipulations. (#150). +- Added GetKeyIndex() helper for converting from ImGuiKey_\* enum to user's keycodes. Basically pulls from io.KeysMap[]. +- Added missing ImGuiKey_PageUp, ImGuiKey_PageDown so more UI code can be written without referring to implementation-side keycodes. +- MenuItem() can be activated on release. (#245) +- Allowing NewFrame() with DeltaTime==0.0f to not assert. +- Fixed IsMouseDragging(). (#260) +- Fixed PlotLines(), PlotHistogram() using incorrect hovering test so they would show their tooltip even when there is + a popup between mouse and the graph. +- Fixed window padding being reported incorrectly for child windows with borders when parent have no borders. +- Fixed a bug with TextUnformatted() clipping of long text blob when clipping y1 line sits on the first line of text. (#257) +- Fixed text baseline alignment of small button (no padding) after regular buttons. +- Fixed ListBoxHeader() not honoring negative sizes the same way as BeginChild() or BeginChildFrame(). (#263) +- Fixed warnings for more pedantic compiler settings (#258). +- ImVector<> cannot be re-defined anymore, cannot be replaced with std::vector<>. Allowed us to clean up and optimize + lots of code. Yeah! (#262) +- ImDrawList: store pointer to their owner name for easier auditing/debugging. +- Examples: added scroll tracking example with SetScrollFromCursorPos(). +- Examples: metrics windows render clip rectangle when hovering over a draw call. +- Lots of small optimization (particularly to run faster on unoptimized builds) and tidying up. +- Added font links in extra_fonts/ + instructions for using compressed fonts in C array. + + +----------------------------------------------------------------------- + VERSION 1.41 (2015-06-26) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.41 + +Breaking Changes: + +- Changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent). + Only makes a difference when texture have transparency. +- Changed Selectable() API from (label, selected, size) to (label, selected, flags, size). + Size override should be used very rarely so hopefully it doesn't affect many people. Sorry! + +Other Changes: + +- Added InputTextMultiline() multi-line text editor, vertical scrolling, selection, optimized enough to handle rather + big chunks of text in stateless context (thousands of lines are ok), option for allowing Tab to be input, option + for validating with Return or Ctrl+Return (#200). +- Added modal window API, BeginPopupModal(), follows the popup api scheme. Modal windows can be closed by clicking + outside. By default the rest of the screen is dimmed (using ImGuiCol_ModalWindowDarkening). Modal windows can be stacked. +- Added GetGlyphRangesCyrillic() helper (#237). +- Added SetNextWindowPosCenter() to center a window prior to knowing its size. (#249) +- Added IsWindowHovered() helper. +- Added IsMouseReleased(), IsKeyReleased() helpers to allow to user to avoid tracking them. (#248) +- Allow Set*WindowSize() calls to be used with popups. +- Window: AutoFit can be triggered on each axis separately via SetNextWindowSize(), etc. +- Window: fixed scrolling with mouse wheel while window was collapsed. +- Window: fixed mouse wheel scroll issues. +- DragFloat(), SliderFloat(): Fixed rounding of negative numbers which sometime made the negative lower bound unreachable. +- InputText(): lifted character count limit. +- InputText(): fixes in case of using per-window font scaling. +- Selectable(), MenuItem(): do not use frame rounding for hovering/selection. +- Selectable(): Added flag ImGuiSelectableFlags_DontClosePopups. +- Selectable(): Added flag ImGuiSelectableFlags_SpanAllColumns (#125). +- Combo(): Fixed issue with activating a Combo() not taking active id (#241). +- ColorButton(), ColorEdit4(): fix to ensure that the colored square stays square when non-default padding settings are used. +- BeginChildFrame(): returns bool like BeginChild() for clipping. +- SetScrollPosHere(): takes account of item height + more accurate centering + fixed precision issue. +- ImFont: ignoring '\r'. +- ImFont: added GetCharAdvance() helper. Exposed font Ascent and font Descent. +- ImFont: additional rendering optimizations. +- Metrics windows display storage size. + + +----------------------------------------------------------------------- + VERSION 1.40 (2015-05-31) +----------------------------------------------------------------------- + +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.40 + +Breaking Changes: + +- The BeginPopup() API (introduced in 1.37) had to be changed to allow for stacked popups and menus. + Use OpenPopup() to toggle the opened state and BeginPopup() to append.** +- The third parameter of Button(), 'repeat_if_held' has been removed. While it's been very rarely used, + some code will possibly break if you didn't rely on the default parameter. + Use PushButtonRepeat()/PopButtonRepeat() to configure repeat. +- Renamed IsRectClipped() to !IsRectVisible() for consistency (opposite return value!). Kept inline redirection function (will obsolete) +- Renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline indirection function (will obsolete). + +Other Changes: + +- Menus: Added a menu system! Menus are typically populated with menu items and sub-menus, but you can add any sort of + widgets in them (buttons, text inputs, sliders, etc.). (#126) +- Menus: Added MenuItem() to append a menu item. Optional shortcut display, acts a button & toggle with checked/unchecked state, + disabled mode. Menu items can be used in any window. +- Menus: Added BeginMenu() to append a sub-menu. Note that you generally want to add sub-menu inside a popup or a menu-bar. + They will work inside a normal window but it will be a bit unusual. +- Menus: Added BeginMenuBar() to append to window menu-bar (set ImGuiWindowFlags_MenuBar to enable). +- Menus: Added BeginMainMenuBar() helper to append to a fullscreen main menu-bar. +- Popups: Support for stacked popups. Each popup level inhibit inputs to lower levels. The menus system is based on this. (#126). +- Popups: Added BeginPopupContextItem(), BeginPopupContextWindow(), BeginPopupContextVoid() to create a popup window on mouse-click. +- Popups: Popups have borders by default (#197), attenuated border alpha in default theme. +- Popups & Tooltip: Fit within display. Handling various positioning/sizing/scrolling edge cases. Better hysteresis when moving + in corners. Tooltip always tries to stay away from mouse-cursor. +- Added ImGuiStorage::GetVoidPtrRef() for manipulating stored void*. +- Added IsKeyDown() IsMouseDown() as convenience and for consistency with existing functions (instead of reading them from IO structures). +- Added Dummy() helper to advance layout by a given size. Unlike InvisibleButton() this doesn't catch any click. +- Added configurable io.KeyRepeatDelay, io.KeyRepeatRate keyboard and mouse repeat rate. +- Added PushButtonRepeat() / PopButtonRepeat() to enable hold-button-to-repeat press on any button. +- Removed the third 'repeat' parameter of Button(). +- Added IsAnyItemHovered() helper. +- Added GetItemsLineHeightWithSpacing() helper. +- Added ImGuiListClipper helper for clipping large list of evenly sized items, to avoid using CalcListClipping() directly. +- Separator: within group start on group horizontal offset. (#205) +- InputText: Fixed incorrect edit state after text buffer is appended to by user via the callback. (#206) +- InputText: CTRL+letter-key shortcuts (e.g. CTRL+C/V/X) makes sure only CTRL is pressed. (#214) +- InputText: Fixed cursor generating a zero-width wire-frame rectangle turning into a division by zero (would go unnoticed + unless you trapped exceptions). +- InputFloatN/InputIntN: Flags parameter added to match scalar versions. (#218) +- Selectable: Horizontal filling not declared to ItemSize() so Selectable(),SameLine() works and we can better auto-fit the window. +- Selectable: Handling text baseline alignment for line that aren't of text height. +- Combo: Empty label doesn't add ItemInnerSpacing alignment, matching other widgets. +- EndGroup: Carries the text base offset from the last line of the group (sort of incorrect but better than nothing, + should use the first line of the group, will implement in the future). +- Columns: distinguish columns-set ID from other widgets as a convenience, added asserts and sailors. +- ListBox: ListBox() function only use public API to encourage creating custom versions. ListBoxHeader() can return false. +- ListBox: Uses ImGuiListClipper and assume items of matching height, so large lists can be handled. +- Plot: overlay label clipped within frame when not fitting. +- Window: Added ImGuiSetCond_Appearing to test the hidden->visible transition in SetWindow***/SetNextWindow*** functions. +- Window: Auto-fitting cancel out one worth of vertical spacing for vertical symmetry (like what group and tooltip do). +- Window: Default item width for auto-resizing windows expressed as a factor of font height, scales better with different font. +- Window: Fixed auto-fit calculation mismatch of whether a scrollbar will be added by maximum height clamping. Also honor NoScrollBar in the case of height clamping, not adding extra horizontal space. +- Window: Hovering require to hover same child window. Reverted 860cf57 (December 3). Might break something if you have + child overlapping items in parent window. +- Window: Fixed appending multiple times to an existing child via multiple BeginChild/EndChild calls to same child name. + Allows a simple form of out-of-order appending. +- Window: Fixed auto-filling child window using WindowMinSize at their minimum size, irrelevant. +- Metrics: Added io.MetricsActiveWindows counter. (#213. +- Metrics: Added io.MetricsAllocs counter (number of active memory allocations). +- Metrics: ShowMetricsWindow() shows popups stack, allocations. +- Style: Added style.DisplayWindowPadding to prevent windows from reaching edges of display (similar to style.DisplaySafeAreaPadding which is still in effect and also affect popups/tooltips). +- Style: Removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). +- Style: Added style.ScrollbarRounding. (#212) +- Style: Added ImGuiCol_TextDisabled for disabled text. Added TextDisabled() helper. +- Style: Added style.WindowTitleAlign alignment options, to e.g. center title on windows. (#222) +- ImVector: tweak growth strategy, matches vector from VS2010. +- ImFontAtlas: Added ClearFonts(), making the different clear funcs more explicit. (#224) +- ImFontAtlas: Fixed appending new fonts without clearing existing fonts. Clearing input data left to application. (#224) +- ImDrawList: Merge draw command better, cases of multiple Begin/End gets merged properly. +- Store common stacked settings contiguously in memory to avoid heap allocation for unused features, and reduce cache misses. +- Shutdown() tests for g.IO.Fonts not being NULL to ease use of multiple ImGui contexts. (#207) +- Added IMGUI_DISABLE_OBSOLETE_FUNCTIONS define to disable the functions that are meant to be removed. +- Examples: Added ? marks with tooltips next to various widgets. Added more comments in the demo window. +- Examples: Added Menu-bar example. +- Examples: Added Simple Layout example. +- Examples: AutoResize demo doesn't use TextWrapped(). +- Examples: Console example uses standard malloc/free, makes more sense as a copy & pastable example. +- Examples: DirectX9/11: Fixed key mapping for down arrow. +- Examples: DirectX9/11: hide OS cursor if ImGui is drawing it. (#155) +- Examples: DirectX11: explicitly set rasterizer state. +- Examples: OpenGL3: Add conditional compilation of forward compat as required by glfw on OSX. (#229) +- Fixed build with Visual Studio 2008 (possibly earlier versions as well). +- Other fixes, comments, tweaks. + + ----------------------------------------------------------------------- For older version, see https://github.com/ocornut/imgui/releases From 57a586b4f144a78996c57b03df4b7a65c039faa9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Feb 2019 18:21:21 +0100 Subject: [PATCH 051/566] Font: Moved functions to internal block (not enforced). Made ConfigData pointer const. Added link to stb's notes. --- imgui.cpp | 4 ++-- imgui.h | 20 ++++++++++---------- imgui_demo.cpp | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3ca42628..7fdff284 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -805,9 +805,9 @@ CODE // Options ImFontConfig config; - config.OversampleH = 3; + config.OversampleH = 2; config.OversampleV = 1; - config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up + config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config); diff --git a/imgui.h b/imgui.h index 943dd2f0..e83ac23c 100644 --- a/imgui.h +++ b/imgui.h @@ -1914,8 +1914,8 @@ struct ImFontConfig bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). int FontNo; // 0 // Index of font within TTF/OTF file float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). - int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. - int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. + int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. + int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. @@ -2080,7 +2080,7 @@ struct ImFontAtlas struct ImFont { // Members: Hot ~24/32 bytes (for CalcTextSize) - ImVector IndexAdvanceX; // 12/16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). + ImVector IndexAdvanceX; // 12/16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI). float FontSize; // 4 // in // // Height of characters, set during loading (don't change after loading) float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX ImWchar FallbackChar; // 2 // in // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() @@ -2093,21 +2093,18 @@ struct ImFont // Members: Cold ~28/40 bytes ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into - ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData + const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. bool DirtyLookupTables; // 1 // out // float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() - float Ascent, Descent; // 8 // out // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] - int MetricsTotalSurface;// 4 // out // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + float Ascent, Descent; // 8 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); - IMGUI_API void ClearOutputData(); - IMGUI_API void BuildLookupTable(); IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const; IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const; - IMGUI_API void SetFallbackChar(ImWchar c); float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; } @@ -2119,10 +2116,13 @@ struct ImFont IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const; IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; - // [Internal] + // [Internal] Don't use! + IMGUI_API void BuildLookupTable(); + IMGUI_API void ClearOutputData(); IMGUI_API void GrowIndex(int new_size); IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. + IMGUI_API void SetFallbackChar(ImWchar c); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontGlyph Glyph; // OBSOLETE 1.52+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2ce06d6c..37cb0b9f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2913,7 +2913,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) const float surface_sqrt = sqrtf((float)font->MetricsTotalSurface); ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)surface_sqrt, (int)surface_sqrt); for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) - if (ImFontConfig* cfg = &font->ConfigData[config_i]) + if (const ImFontConfig* cfg = &font->ConfigData[config_i]) ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) { From b46076458c66ebd3e0de6f7ec9bd27b4db33586e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Feb 2019 18:29:49 +0100 Subject: [PATCH 052/566] Examples: Win32: Removed unused code left-over from merge e9c625a1dc91818385aea650716200e6119fa5f6 --- examples/imgui_impl_win32.cpp | 8 -------- 1 file changed, 8 deletions(-) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index f34d8405..d9c43676 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -197,14 +197,6 @@ static void ImGui_ImplWin32_UpdateMousePos() if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hovered_hwnd)) if ((viewport->Flags & ImGuiViewportFlags_NoInputs) == 0) // FIXME: We still get our NoInputs window with WM_NCHITTEST/HTTRANSPARENT code when decorated? io.MouseHoveredViewport = viewport->ID; - -#if 0 - POINT pos; - if (HWND active_window = ::GetForegroundWindow()) - if (active_window == g_hWnd || ::IsChild(active_window, g_hWnd)) - if (::GetCursorPos(&pos) && ::ScreenToClient(g_hWnd, &pos)) - io.MousePos = ImVec2((float)pos.x, (float)pos.y); -#endif } #ifdef _MSC_VER From 0236bc246fa0ddf9c139c6e5fe960d46f75bb1e0 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 Feb 2019 13:25:23 +0100 Subject: [PATCH 053/566] Scrollbar: Fade out and disable interaction when too small, in order to facilitate using the resize grab on very small window, as well as reducing visual noise/overlap. (+1 squashed commits) Internals: Added GetScrollbarID(). (#1185) --- docs/CHANGELOG.txt | 2 ++ imgui_internal.h | 1 + imgui_widgets.cpp | 31 +++++++++++++++++++++++++------ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a895256a..2c6574ad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,8 @@ Other Changes: - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). - Window: When resizing from an edge, the border is more visible and better follow the rounded corners. - Window: Fixed initial width of collapsed windows not taking account of contents width (broken in 1.67). (#2336, #176) +- Scrollbar: Fade out and disable interaction when too small, in order to facilitate using the resize grab on very + small window, as well as reducing visual noise/overlap. - ListBox: Better optimized when clipped / non-visible. - InputTextMultiline: Better optimized when clipped / non-visible. - Font: Fixed high-level ImGui::CalcTextSize() used by most widgets from erroneously subtracting 1.0f*scale to diff --git a/imgui_internal.h b/imgui_internal.h index f25d208e..e2bbfbf1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1464,6 +1464,7 @@ namespace ImGui IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags); IMGUI_API void Scrollbar(ImGuiLayoutType direction); + IMGUI_API ImGuiID GetScrollbarID(ImGuiLayoutType direction); IMGUI_API void VerticalSeparator(); // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. // Widgets low-level behaviors diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 17dbeda4..64ce6c48 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -710,6 +710,13 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) return pressed; } +ImGuiID ImGui::GetScrollbarID(ImGuiLayoutType direction) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + return window->GetID((direction == ImGuiLayoutType_Horizontal) ? "#SCROLLX" : "#SCROLLY"); +} + // Vertical/Horizontal scrollbar // The entire piece of code below is rather confusing because: // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) @@ -722,8 +729,8 @@ void ImGui::Scrollbar(ImGuiLayoutType direction) const bool horizontal = (direction == ImGuiLayoutType_Horizontal); const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); - + const ImGuiID id = GetScrollbarID(direction); + // Render background bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; @@ -734,9 +741,21 @@ void ImGui::Scrollbar(ImGuiLayoutType direction) : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); if (!horizontal) bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); - if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f) + + const float bb_height = bb.GetHeight(); + if (bb.GetWidth() <= 0.0f || bb_height <= 0.0f) return; + // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab) + float alpha = 1.0f; + if ((direction == ImGuiLayoutType_Vertical) && bb_height < g.FontSize + g.Style.FramePadding.y * 2.0f) + { + alpha = ImSaturate((bb_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f)); + if (alpha <= 0.0f) + return; + } + const bool allow_interaction = (alpha >= 1.0f); + int window_rounding_corners; if (horizontal) window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); @@ -767,7 +786,7 @@ void ImGui::Scrollbar(ImGuiLayoutType direction) float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); float scroll_ratio = ImSaturate(scroll_v / scroll_max); float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; - if (held && grab_h_norm < 1.0f) + if (held && allow_interaction && grab_h_norm < 1.0f) { float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; @@ -810,8 +829,8 @@ void ImGui::Scrollbar(ImGuiLayoutType direction) *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } - // Render - const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); + // Render grab + const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha); ImRect grab_rect; if (horizontal) grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y); From 8522a4bbea620a8e4d8753bd64e65ea113c713e6 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 Feb 2019 13:42:14 +0100 Subject: [PATCH 054/566] Fixed Clang warning ("multi-line comment"). XCode also also "space between \ and carriage return". Perhaps it would work with 2 spaces? Adding a dot for now.. --- imstb_truetype.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imstb_truetype.h b/imstb_truetype.h index 95631323..c1cdb180 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -253,7 +253,7 @@ // Documentation & header file 520 LOC \___ 660 LOC documentation // Sample code 140 LOC / // Truetype parsing 620 LOC ---- 620 LOC TrueType -// Software rasterization 240 LOC \ +// Software rasterization 240 LOC \. // Curve tessellation 120 LOC \__ 550 LOC Bitmap creation // Bitmap management 100 LOC / // Baked bitmap interface 70 LOC / From 2206df9e7a092f15e7a5c552d4691c232fbf1007 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 Feb 2019 14:00:30 +0100 Subject: [PATCH 055/566] Demo: Added Auto-Scroll option in Log/Console. Comments. Removed some ImColor() uses. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 2 +- imgui_demo.cpp | 85 +++++++++++++++++++++++++++++++++++----------- 3 files changed, 67 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2c6574ad..b3e3b74e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,7 @@ Other Changes: - ImFontAtlas: FreeType: Added support for imgui allocators + custom FreeType only SetAllocatorFunctions. (#2285) [@Vuhdo] - ImFontAtlas: FreeType: Fixed using imgui_freetype.cpp in unity builds. (#2302) - Demo: Fixed "Log" demo not initializing properly, leading to the first line not showing before a Clear. (#2318) [@bluescan] +- Demo: Added "Auto-scroll" option in Log/Console demos. (#2300) [@nicolasnoble, @ocornut] - Examples: Metal, OpenGL2, OpenGL3: Fixed offsetting of clipping rectangle with ImDrawData::DisplayPos != (0,0) when the display frame-buffer scale scale is not (1,1). While this doesn't make a difference when using master branch, this is effectively fixing support for multi-viewport with Mac Retina Displays on those examples. (#2306) [@rasky, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index 7fdff284..d55c3b1c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9301,7 +9301,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); - ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) if (node_open) ImGui::TreePop(); return; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 37cb0b9f..e3785d34 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1005,7 +1005,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Color/Picker Widgets")) { - static ImVec4 color = ImColor(114, 144, 154, 200); + static ImVec4 color = ImVec4(114.0f/255.0f, 144.0f/255.0f, 154.0f/255.0f, 200.0f/255.0f); static bool alpha_preview = true; static bool alpha_half_preview = false; @@ -3095,10 +3095,12 @@ struct ExampleAppConsole { char InputBuf[256]; ImVector Items; - bool ScrollToBottom; + ImVector Commands; ImVector History; int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. - ImVector Commands; + ImGuiTextFilter Filter; + bool AutoScroll; + bool ScrollToBottom; ExampleAppConsole() { @@ -3109,6 +3111,8 @@ struct ExampleAppConsole Commands.push_back("HISTORY"); Commands.push_back("CLEAR"); Commands.push_back("CLASSIFY"); // "classify" is only here to provide an example of "C"+[tab] completing to "CL" and displaying matches. + AutoScroll = true; + ScrollToBottom = true; AddLog("Welcome to Dear ImGui!"); } ~ExampleAppConsole() @@ -3142,7 +3146,8 @@ struct ExampleAppConsole buf[IM_ARRAYSIZE(buf)-1] = 0; va_end(args); Items.push_back(Strdup(buf)); - ScrollToBottom = true; + if (AutoScroll) + ScrollToBottom = true; } void Draw(const char* title, bool* p_open) @@ -3168,7 +3173,7 @@ struct ExampleAppConsole // TODO: display items starting from the bottom - if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); if (ImGui::SmallButton("Add Dummy Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::SameLine(); @@ -3177,10 +3182,20 @@ struct ExampleAppConsole ImGui::Separator(); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); - static ImGuiTextFilter filter; - filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); - ImGui::PopStyleVar(); + // Options menu + if (ImGui::BeginPopup("Options")) + { + if (ImGui::Checkbox("Auto-scroll", &AutoScroll)) + if (AutoScroll) + ScrollToBottom = true; + ImGui::EndPopup(); + } + + // Options, Filter + if (ImGui::Button("Options")) + ImGui::OpenPopup("Options"); + ImGui::SameLine(); + Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); ImGui::Separator(); const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); // 1 separator, 1 input text @@ -3205,18 +3220,19 @@ struct ExampleAppConsole ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); - ImVec4 col_default_text = ImGui::GetStyleColorVec4(ImGuiCol_Text); for (int i = 0; i < Items.Size; i++) { const char* item = Items[i]; - if (!filter.PassFilter(item)) + if (!Filter.PassFilter(item)) continue; - ImVec4 col = col_default_text; - if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f); - else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f); - ImGui::PushStyleColor(ImGuiCol_Text, col); + + // Normally you would store more information in your item (e.g. make Items[] an array of structure, store color/type etc.) + bool pop_color = false; + if (strstr(item, "[error]")) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); pop_color = true; } + else if (strncmp(item, "# ", 2) == 0) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.8f, 0.6f, 1.0f)); pop_color = true; } ImGui::TextUnformatted(item); - ImGui::PopStyleColor(); + if (pop_color) + ImGui::PopStyleColor(); } if (copy_to_clipboard) ImGui::LogFinish(); @@ -3283,6 +3299,9 @@ struct ExampleAppConsole { AddLog("Unknown command: '%s'\n", command_line); } + + // On commad input, we scroll to bottom even if AutoScroll==false + ScrollToBottom = true; } static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks @@ -3411,10 +3430,12 @@ struct ExampleAppLog ImGuiTextBuffer Buf; ImGuiTextFilter Filter; ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines + bool AutoScroll; bool ScrollToBottom; ExampleAppLog() { + AutoScroll = true; ScrollToBottom = false; Clear(); } @@ -3436,7 +3457,8 @@ struct ExampleAppLog for (int new_size = Buf.size(); old_size < new_size; old_size++) if (Buf[old_size] == '\n') LineOffsets.push_back(old_size + 1); - ScrollToBottom = true; + if (AutoScroll) + ScrollToBottom = true; } void Draw(const char* title, bool* p_open = NULL) @@ -3446,13 +3468,31 @@ struct ExampleAppLog ImGui::End(); return; } - if (ImGui::Button("Clear")) Clear(); + + // Options menu + if (ImGui::BeginPopup("Options")) + { + if (ImGui::Checkbox("Auto-scroll", &AutoScroll)) + if (AutoScroll) + ScrollToBottom = true; + ImGui::EndPopup(); + } + + // Main window + if (ImGui::Button("Options")) + ImGui::OpenPopup("Options"); + ImGui::SameLine(); + bool clear = ImGui::Button("Clear"); ImGui::SameLine(); bool copy = ImGui::Button("Copy"); ImGui::SameLine(); Filter.Draw("Filter", -100.0f); + ImGui::Separator(); ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); + + if (clear) + Clear(); if (copy) ImGui::LogToClipboard(); @@ -3461,6 +3501,10 @@ struct ExampleAppLog const char* buf_end = Buf.end(); if (Filter.IsActive()) { + // In this example we don't use the clipper when Filter is enabled. + // This is because we don't have a random access on the result on our filter. + // A real application processing logs with ten of thousands of entries may want to store the result of search/filter. + // especially if the filtering function is not trivial (e.g. reg-exp). for (int line_no = 0; line_no < LineOffsets.Size; line_no++) { const char* line_start = buf + LineOffsets[line_no]; @@ -3508,11 +3552,12 @@ static void ShowExampleAppLog(bool* p_open) { static ExampleAppLog log; - // For the demo: add a debug button before the normal log window contents + // For the demo: add a debug button _BEFORE_ the normal log window contents // We take advantage of the fact that multiple calls to Begin()/End() are appending to the same window. + // Most of the contents of the window will be added by the log.Draw() call. ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver); ImGui::Begin("Example: Log", p_open); - if (ImGui::SmallButton("Add 5 entries")) + if (ImGui::SmallButton("[Debug] Add 5 entries")) { static int counter = 0; for (int n = 0; n < 5; n++) From 3c07ec6a6126fb6b98523a9685d1f0f78ca3c40c Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 Feb 2019 17:14:29 +0100 Subject: [PATCH 056/566] Made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). Causing too many subtle side-effect, e.g. IsNavInputPressed() would return true multiple times in a row. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 9 +++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b3e3b74e..d270ecdd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,8 @@ HOW TO UPDATE? Breaking Changes: - Removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). +- Made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). + If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! Other Changes: - Added .editorconfig file for text editors to standardize using spaces. (#2038) [@kudaba] diff --git a/imgui.cpp b/imgui.cpp index d55c3b1c..afc6458d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -364,6 +364,7 @@ CODE When you are not sure about a 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. + - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete). @@ -3364,12 +3365,12 @@ void ImGui::NewFrame() // Check user data // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) IM_ASSERT(g.Initialized); - IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)"); - IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value"); + IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); + IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); - IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting"); - IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)"); + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); + IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!"); IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); From 93d117980565a3f72f23bc3bfd7178ff8138c5c3 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 Feb 2019 18:55:08 +0100 Subject: [PATCH 057/566] Examples: Extracted gamepad code into ImGui_ImplGlfw_UpdateGamepads(). Renamed matching Win32 function for consistency. Added more link to nothing's oversample document. Spacing bits. --- examples/imgui_impl_glfw.cpp | 70 +++++++++++++++++++---------------- examples/imgui_impl_win32.cpp | 4 +- imgui_draw.cpp | 2 +- imgui_internal.h | 14 +++---- misc/fonts/README.txt | 7 +++- 5 files changed, 53 insertions(+), 44 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 5f123c88..d5c0b13b 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -265,6 +265,43 @@ static void ImGui_ImplGlfw_UpdateMouseCursor() } } +static void ImGui_ImplGlfw_UpdateGamepads() +{ + ImGuiIO& io = ImGui::GetIO(); + memset(io.NavInputs, 0, sizeof(io.NavInputs)); + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + return; + + // Update gamepad inputs + #define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; } + #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; } + int axes_count = 0, buttons_count = 0; + const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count); + const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count); + MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A + MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B + MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X + MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y + MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left + MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right + MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up + MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down + MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB + MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB + MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB + MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB + MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f); + MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f); + MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f); + MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f); + #undef MAP_BUTTON + #undef MAP_ANALOG + if (axes_count > 0 && buttons_count > 0) + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + else + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; +} + void ImGui_ImplGlfw_NewFrame() { ImGuiIO& io = ImGui::GetIO(); @@ -287,36 +324,5 @@ void ImGui_ImplGlfw_NewFrame() ImGui_ImplGlfw_UpdateMouseCursor(); // Gamepad navigation mapping - memset(io.NavInputs, 0, sizeof(io.NavInputs)); - if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) - { - // Update gamepad inputs - #define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; } - #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; } - int axes_count = 0, buttons_count = 0; - const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count); - const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count); - MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A - MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B - MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X - MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y - MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left - MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right - MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up - MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down - MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB - MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB - MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB - MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB - MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f); - MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f); - MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f); - MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f); - #undef MAP_BUTTON - #undef MAP_ANALOG - if (axes_count > 0 && buttons_count > 0) - io.BackendFlags |= ImGuiBackendFlags_HasGamepad; - else - io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; - } + ImGui_ImplGlfw_UpdateGamepads(); } diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 83c20c05..4690f3e7 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -150,7 +150,7 @@ static void ImGui_ImplWin32_UpdateMousePos() #endif // Gamepad navigation mapping -void ImGui_ImplWin32_UpdateGameControllers() +static void ImGui_ImplWin32_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); memset(io.NavInputs, 0, sizeof(io.NavInputs)); @@ -231,7 +231,7 @@ void ImGui_ImplWin32_NewFrame() } // Update game controllers (if available) - ImGui_ImplWin32_UpdateGameControllers(); + ImGui_ImplWin32_UpdateGamepads(); } // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8ebc36c3..ab79be9a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1361,7 +1361,7 @@ ImFontConfig::ImFontConfig() FontDataOwnedByAtlas = true; FontNo = 0; SizePixels = 0.0f; - OversampleH = 3; + OversampleH = 3; // FIXME: 2 may be a better default? OversampleV = 1; PixelSnapH = false; GlyphExtraSpacing = ImVec2(0.0f, 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index e2bbfbf1..48a8b0a4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -349,13 +349,13 @@ enum ImGuiSeparatorFlags_ // This is going to be exposed in imgui.h when stabilized enough. enum ImGuiItemFlags_ { - ImGuiItemFlags_NoTabStop = 1 << 0, // false - ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. - ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211 - ImGuiItemFlags_NoNav = 1 << 3, // false - ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false - ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window - ImGuiItemFlags_Default_ = 0 + ImGuiItemFlags_NoTabStop = 1 << 0, // false + ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. + ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211 + ImGuiItemFlags_NoNav = 1 << 3, // false + ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false + ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window + ImGuiItemFlags_Default_ = 0 }; // Storage for LastItem data diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index fd4ed1bf..a69bc19f 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -25,7 +25,7 @@ If you have other loading/merging/adding fonts, you can post on the Dear ImGui " - Building Custom Glyph Ranges - Embedding Fonts in Source Code - Credits/Licences for fonts included in this folder -- Links, Other fonts +- Fonts Links --------------------------------------- @@ -106,11 +106,14 @@ Load .TTF/.OTF file with: For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally): ImFontConfig config; - config.OversampleH = 3; + config.OversampleH = 2; config.OversampleV = 1; config.GlyphExtraSpacing.x = 1.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); +Read about oversampling here: + https://github.com/nothings/stb/blob/master/tests/oversample + If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. The typical result of failing to upload a texture is if every glyphs appears as white rectangles. In particular, using a large range such as GetGlyphRangesChineseSimplifiedCommon() is not recommended unless you From b277cfffc846976f15579ec5cca20cce3d76e6db Mon Sep 17 00:00:00 2001 From: haldean Date: Wed, 13 Feb 2019 14:56:21 -0800 Subject: [PATCH 058/566] Selectable: add support for specifying text alignment on selectables (#2347) Adds a style variable to Selectable that allows clients to specify the text alignment within Selectables, adds a section in the demo to demonstrate selectable text alignment, and a pair of sliders in the style editor to change selectable alignment on the fly. In terms of implementation, this one is extremely simple: Selectable was already calling an API that supports text alignment, but had hard-coded it to top-left. This changes that to just pass the style variable straight through to RenderTextClipped. Backwards-compatibility is preserved by defaulting the text_align parameter to (0, 0), i.e., top-left. This also fixes a bug with selectable text rendering that caused right-aligned text in a selectable to be clipped incorrectly, because the wrong clipping rectangle was being used. --- imgui.cpp | 46 ++++++++++++++++++++++++---------------------- imgui.h | 2 ++ imgui_demo.cpp | 20 ++++++++++++++++++++ imgui_widgets.cpp | 2 +- 4 files changed, 47 insertions(+), 23 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index afc6458d..19cb784a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1109,6 +1109,7 @@ ImGuiStyle::ImGuiStyle() AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + SelectableTextAlign = ImVec2(0,0); // Alignment of selectable text when button is larger than text. // Default theme ImGui::StyleColorsDark(this); @@ -5794,28 +5795,29 @@ struct ImGuiStyleVarInfo static const ImGuiStyleVarInfo GStyleVarInfo[] = { - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha - { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize - { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize - { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize - { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize - { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing - { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding - { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding - { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding + { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign }; static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) diff --git a/imgui.h b/imgui.h index e83ac23c..6073c6e2 100644 --- a/imgui.h +++ b/imgui.h @@ -1082,6 +1082,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_GrabRounding, // float GrabRounding ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_COUNT // Obsolete names (will be removed) @@ -1263,6 +1264,7 @@ struct ImGuiStyle bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + ImVec2 SelectableTextAlign; // Alignment of selectable text when selectable is larger than text. Defaults to (0,0) for top-left alignment. ImVec4 Colors[ImGuiCol_COUNT]; IMGUI_API ImGuiStyle(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e3785d34..c2c3726c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -893,6 +893,25 @@ static void ShowDemoWindowWidgets() } ImGui::TreePop(); } + if (ImGui::TreeNode("Alignment")) + { + static bool selected[3*3] = { true, false, true, false, true, false, true, false, true }; + static char name[16]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 3; j++) + { + float x = (float) i / 2.f; + float y = (float) j / 2.f; + snprintf(name, IM_ARRAYSIZE(name), "(%.1f,%.1f)", x, y); + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(x, y)); + ImGui::Selectable(name, &selected[3*i+j], 0, ImVec2(70,70)); + ImGui::PopStyleVar(); + if (j != 2) ImGui::SameLine(); + } + } + ImGui::TreePop(); + } ImGui::TreePop(); } @@ -2825,6 +2844,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::Text("Alignment"); ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a button is larger than its text content."); + ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a selectable is larger than its text content."); ImGui::Text("Safe Area Padding"); ImGui::SameLine(); ShowHelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); ImGui::EndTabItem(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 64ce6c48..ee18ea90 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5100,7 +5100,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); - RenderTextClipped(bb_inner.Min, bb.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f)); + RenderTextClipped(bb_inner.Min, bb_inner.Max, label, NULL, &label_size, style.SelectableTextAlign, &bb); if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); // Automatically close popups From 76dbff37cd9ae5ca10c76c508a5d26864954c4f2 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 Feb 2019 20:29:50 +0100 Subject: [PATCH 059/566] Selectable: Tweaks for #2347 (demo, changelog, member position) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- imgui.h | 4 ++-- imgui_demo.cpp | 26 ++++++++++++++------------ 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d270ecdd..78f99aae 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,7 @@ Breaking Changes: If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! Other Changes: + - Added .editorconfig file for text editors to standardize using spaces. (#2038) [@kudaba] - ImDrawData: Added FramebufferScale field (currently a copy of the value from io.DisplayFramebufferScale). This is to allow render functions being written without pulling any data from ImGuiIO, allowing incoming @@ -58,6 +59,7 @@ Other Changes: - Tabs: Removed ImGuiTabBarFlags_NoTabListPopupButton which was available in 1.67 but actually had zero use. - Tabs: Fixed a minor clipping glitch when changing style's FramePadding from frame to frame. - Tabs: Fixed border (when enabled) so it is aligned correctly mid-pixel and appears as bright as other borders. +- Style, Selectable: Added ImGuiStyle::SelectableTextAlign and ImGuiStyleVar_SelectableTextAlign. (#2347) [@haldean] - Menus: Tweaked horizontal overlap between parent and child menu (to help convey relative depth) from using style.ItemSpacing.x to style.ItemInnerSpacing.x, the later being expected to be smaller. (#1086) - RadioButton: Fixed label horizontal alignment to precisely match Checkbox(). diff --git a/imgui.cpp b/imgui.cpp index 19cb784a..f1b626dc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1103,13 +1103,13 @@ ImGuiStyle::ImGuiStyle() TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. + SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. 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. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. - SelectableTextAlign = ImVec2(0,0); // Alignment of selectable text when button is larger than text. // Default theme ImGui::StyleColorsDark(this); diff --git a/imgui.h b/imgui.h index 6073c6e2..c677d25a 100644 --- a/imgui.h +++ b/imgui.h @@ -1257,14 +1257,14 @@ struct ImGuiStyle float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. - ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). + ImVec2 SelectableTextAlign; // Alignment of selectable text when selectable is larger than text. Defaults to (0.0f, 0.0f) (top-left aligned). ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. - ImVec2 SelectableTextAlign; // Alignment of selectable text when selectable is larger than text. Defaults to (0,0) for top-left alignment. ImVec4 Colors[ImGuiCol_COUNT]; IMGUI_API ImGuiStyle(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c2c3726c..8618a9ee 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -62,7 +62,6 @@ Index of this file: #ifdef _MSC_VER #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen -#define vsnprintf _vsnprintf #endif #ifdef __clang__ #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. @@ -70,6 +69,7 @@ Index of this file: #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' #pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wunused-macros" // warning : warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 #endif @@ -91,9 +91,11 @@ Index of this file: // Play it nice with Windows users. Notepad in 2017 still doesn't display text data with Unix-style \n. #ifdef _WIN32 -#define IM_NEWLINE "\r\n" +#define IM_NEWLINE "\r\n" +#define snprintf _snprintf +#define vsnprintf _vsnprintf #else -#define IM_NEWLINE "\n" +#define IM_NEWLINE "\n" #endif #define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) @@ -895,19 +897,19 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Alignment")) { + ShowHelpMarker("Alignment applies when a selectable is larger than its text content.\nBy default, Selectables uses style.SelectableTextAlign but it can be overriden on a per-item basis using PushStyleVar()."); static bool selected[3*3] = { true, false, true, false, true, false, true, false, true }; - static char name[16]; - for (int i = 0; i < 3; i++) + for (int y = 0; y < 3; y++) { - for (int j = 0; j < 3; j++) + for (int x = 0; x < 3; x++) { - float x = (float) i / 2.f; - float y = (float) j / 2.f; - snprintf(name, IM_ARRAYSIZE(name), "(%.1f,%.1f)", x, y); - ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(x, y)); - ImGui::Selectable(name, &selected[3*i+j], 0, ImVec2(70,70)); + ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f); + char name[32]; + sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y); + if (x > 0) ImGui::SameLine(); + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment); + ImGui::Selectable(name, &selected[3*y+x], ImGuiSelectableFlags_None, ImVec2(80,80)); ImGui::PopStyleVar(); - if (j != 2) ImGui::SameLine(); } } ImGui::TreePop(); From f977871854af941289f2a9090dcc90f7aa3449a8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 15 Feb 2019 13:10:22 +0100 Subject: [PATCH 060/566] ImFont: Minor adjustment to the structure. Examples: Removed unused variable. --- examples/example_apple_opengl2/main.mm | 1 - imgui.h | 16 ++++++++-------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 0d92da50..2c4622f1 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -91,7 +91,6 @@ ImGui::Render(); [[self openGLContext] makeCurrentContext]; - ImGuiIO& io = ImGui::GetIO(); ImDrawData* draw_data = ImGui::GetDrawData(); GLsizei width = (GLsizei)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); GLsizei height = (GLsizei)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); diff --git a/imgui.h b/imgui.h index c677d25a..b8be7621 100644 --- a/imgui.h +++ b/imgui.h @@ -2081,26 +2081,26 @@ struct ImFontAtlas // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). struct ImFont { - // Members: Hot ~24/32 bytes (for CalcTextSize) - ImVector IndexAdvanceX; // 12/16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI). - float FontSize; // 4 // in // // Height of characters, set during loading (don't change after loading) + // Members: Hot ~20/24 bytes (for CalcTextSize) + ImVector IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI). float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX - ImWchar FallbackChar; // 2 // in // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() + float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) // Members: Hot ~36/48 bytes (for CalcTextSize + render loop) ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // // All glyphs. - ImVec2 DisplayOffset; // 8 // in // = (0,0) // Offset font rendering by xx pixels const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) + ImVec2 DisplayOffset; // 8 // in // = (0,0) // Offset font rendering by xx pixels - // Members: Cold ~28/40 bytes + // Members: Cold ~32/40 bytes ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. - bool DirtyLookupTables; // 1 // out // + ImWchar FallbackChar; // 2 // in // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() - float Ascent, Descent; // 8 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] int MetricsTotalSurface;// 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + bool DirtyLookupTables; // 1 // out // // Methods IMGUI_API ImFont(); From dd14adc73166d6089b08f25f622f479a7d1980fe Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 Feb 2019 12:27:46 +0100 Subject: [PATCH 061/566] Examples: Vulkan: Support draw_data->FramebufferScale correctly matching a79785c for on Metal/GL2/GL3. (#2306, #1676) --- docs/CHANGELOG.txt | 4 ++-- examples/imgui_impl_vulkan.cpp | 27 +++++++++++++++++++-------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 78f99aae..93d094cb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,8 +81,8 @@ Other Changes: - ImFontAtlas: FreeType: Fixed using imgui_freetype.cpp in unity builds. (#2302) - Demo: Fixed "Log" demo not initializing properly, leading to the first line not showing before a Clear. (#2318) [@bluescan] - Demo: Added "Auto-scroll" option in Log/Console demos. (#2300) [@nicolasnoble, @ocornut] -- Examples: Metal, OpenGL2, OpenGL3: Fixed offsetting of clipping rectangle with ImDrawData::DisplayPos != (0,0) when - the display frame-buffer scale scale is not (1,1). While this doesn't make a difference when using master branch, +- Examples: Metal, OpenGL2, OpenGL3, Vulkan: Fixed offsetting of clipping rectangle with ImDrawData::DisplayPos != (0,0) + when the display frame-buffer scale scale is not (1,1). While this doesn't make a difference when using master branch, this is effectively fixing support for multi-viewport with Mac Retina Displays on those examples. (#2306) [@rasky, @ocornut] Also using ImDrawData::FramebufferScale instead of io.DisplayFramebufferScale. - Examples: Clarified the use the ImDrawData::DisplayPos to offset clipping rectangles. diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 15c32b2e..c60c23c2 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case. // 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other bindings. @@ -266,8 +267,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm VkViewport viewport; viewport.x = 0; viewport.y = 0; - viewport.width = draw_data->DisplaySize.x; - viewport.height = draw_data->DisplaySize.y; + viewport.width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x; + viewport.height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; vkCmdSetViewport(command_buffer, 0, 1, &viewport); @@ -286,10 +287,13 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate); } - // Render the command lists: + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists int vtx_offset = 0; int idx_offset = 0; - ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -302,13 +306,20 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm } else { + // Project scissor/clipping rectangles into framebuffer space + ImVec4 clip_rect; + clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x; + clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y; + clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x; + clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y; + // Apply scissor/clipping rectangle // FIXME: We could clamp width/height based on clamped min/max values. VkRect2D scissor; - scissor.offset.x = (int32_t)(pcmd->ClipRect.x - clip_off.x) > 0 ? (int32_t)(pcmd->ClipRect.x - clip_off.x) : 0; - scissor.offset.y = (int32_t)(pcmd->ClipRect.y - clip_off.y) > 0 ? (int32_t)(pcmd->ClipRect.y - clip_off.y) : 0; - scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x); - scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here? + scissor.offset.x = ((int32_t)clip_rect.x > 0) ? (int32_t)(clip_rect.x) : 0; + scissor.offset.y = ((int32_t)clip_rect.y > 0) ? (int32_t)(clip_rect.y) : 0; + scissor.extent.width = (uint32_t)(clip_rect.z - clip_rect.x); + scissor.extent.height = (uint32_t)(clip_rect.w - clip_rect.y + 1); // FIXME: Why +1 here? vkCmdSetScissor(command_buffer, 0, 1, &scissor); // Draw From d972533d0973b0057beed3799a4985e4a4cc4260 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 Feb 2019 12:33:38 +0100 Subject: [PATCH 062/566] Examples: Vulkan: Rewrote scissor processing to match other examples more closely. Removed extraneous +1 of scissor extent height. --- examples/imgui_impl_vulkan.cpp | 35 +++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index c60c23c2..eabc49ea 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -203,10 +203,13 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer) { - VkResult err; - if (draw_data->TotalVtxCount == 0) + // 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); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount == 0) return; + VkResult err; FrameDataForRender* fd = &g_FramesDataBuffers[g_FrameIndex]; g_FrameIndex = (g_FrameIndex + 1) % IMGUI_VK_QUEUED_FRAMES; @@ -267,8 +270,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm VkViewport viewport; viewport.x = 0; viewport.y = 0; - viewport.width = draw_data->DisplaySize.x * draw_data->FramebufferScale.x; - viewport.height = draw_data->DisplaySize.y * draw_data->FramebufferScale.y; + viewport.width = (float)fb_width; + viewport.height = (float)fb_height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; vkCmdSetViewport(command_buffer, 0, 1, &viewport); @@ -313,17 +316,19 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x; clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y; - // Apply scissor/clipping rectangle - // FIXME: We could clamp width/height based on clamped min/max values. - VkRect2D scissor; - scissor.offset.x = ((int32_t)clip_rect.x > 0) ? (int32_t)(clip_rect.x) : 0; - scissor.offset.y = ((int32_t)clip_rect.y > 0) ? (int32_t)(clip_rect.y) : 0; - scissor.extent.width = (uint32_t)(clip_rect.z - clip_rect.x); - scissor.extent.height = (uint32_t)(clip_rect.w - clip_rect.y + 1); // FIXME: Why +1 here? - vkCmdSetScissor(command_buffer, 0, 1, &scissor); - - // Draw - vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0); + if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) + { + // Apply scissor/clipping rectangle + VkRect2D scissor; + scissor.offset.x = (int32_t)(clip_rect.x); + scissor.offset.y = (int32_t)(clip_rect.y); + scissor.extent.width = (uint32_t)(clip_rect.z - clip_rect.x); + scissor.extent.height = (uint32_t)(clip_rect.w - clip_rect.y); + vkCmdSetScissor(command_buffer, 0, 1, &scissor); + + // Draw + vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0); + } } idx_offset += pcmd->ElemCount; } From db40699990928b95584dbab953a2b1a179f48f7e Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 18 Feb 2019 12:08:19 +0100 Subject: [PATCH 063/566] imgui_freeetype: Updated suggested test code. --- misc/freetype/README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/misc/freetype/README.md b/misc/freetype/README.md index 156e6511..4c53cd9c 100644 --- a/misc/freetype/README.md +++ b/misc/freetype/README.md @@ -67,6 +67,7 @@ struct FreeTypeTest FontBuildMode BuildMode; bool WantRebuild; float FontsMultiply; + int FontsPadding; unsigned int FontsFlags; FreeTypeTest() @@ -74,6 +75,7 @@ struct FreeTypeTest BuildMode = FontBuildMode_FreeType; WantRebuild = true; FontsMultiply = 1.0f; + FontsPadding = 1; FontsFlags = 0; } @@ -85,8 +87,10 @@ struct FreeTypeTest ImGuiIO& io = ImGui::GetIO(); for (int n = 0; n < io.Fonts->Fonts.Size; n++) { - io.Fonts->Fonts[n]->ConfigData->RasterizerMultiply = FontsMultiply; - io.Fonts->Fonts[n]->ConfigData->RasterizerFlags = (BuildMode == FontBuildMode_FreeType) ? FontsFlags : 0x00; + ImFontConfig* font_config = (ImFontConfig*)io.Fonts->Fonts[n]->ConfigData; + io.Fonts->TexGlyphPadding = FontsPadding; + font_config->RasterizerMultiply = FontsMultiply; + font_config->RasterizerFlags = (BuildMode == FontBuildMode_FreeType) ? FontsFlags : 0x00; } if (BuildMode == FontBuildMode_FreeType) ImGuiFreeType::BuildFontAtlas(io.Fonts, FontsFlags); @@ -105,6 +109,7 @@ struct FreeTypeTest ImGui::SameLine(); WantRebuild |= ImGui::RadioButton("Stb (Default)", (int*)&BuildMode, FontBuildMode_Stb); WantRebuild |= ImGui::DragFloat("Multiply", &FontsMultiply, 0.001f, 0.0f, 2.0f); + WantRebuild |= ImGui::DragInt("Padding", &FontsPadding, 0.1f, 0, 16); if (BuildMode == FontBuildMode_FreeType) { WantRebuild |= ImGui::CheckboxFlags("NoHinting", &FontsFlags, ImGuiFreeType::NoHinting); From f5bf6e38d22b962bf465621bd4d46068f18eb12c Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 18 Feb 2019 12:11:46 +0100 Subject: [PATCH 064/566] Font: Fixed assert when specifying duplicate/overlapping ranges within a same font. (#2353, #2233) --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 8 +++----- misc/freetype/imgui_freetype.cpp | 8 +++----- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 93d094cb..1d49b4c0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -73,6 +73,7 @@ Other Changes: calculated text width. Among noticeable side-effects, it would make sequences of repeated Text/SameLine calls not align the same as a single call, and create mismatch between high-level size calculation and those performed with the lower-level ImDrawList api. (#792) [@SlNPacifist] +- Font: Fixed building atlas when specifying duplicate/overlapping ranges within a same font. (#2353, #2233) - ImDrawList: Fixed AddCircle(), AddCircleFilled() angle step being off, which was visible when drawing a "circle" with a small number of segments (e.g. an hexagon). (#2287) [@baktery] - ImGuiTextBuffer: Added append() function (unformatted). diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ab79be9a..7c513f6f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1840,15 +1840,14 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) { ImFontBuildSrcData& src_tmp = src_tmp_array[src_i]; ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - ImFontConfig& cfg = atlas->ConfigData[src_i]; src_tmp.GlyphsSet.Resize(src_tmp.GlyphsHighest + 1); - if (dst_tmp.SrcCount > 1 && dst_tmp.GlyphsSet.Storage.empty()) + if (dst_tmp.GlyphsSet.Storage.empty()) dst_tmp.GlyphsSet.Resize(dst_tmp.GlyphsHighest + 1); for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) for (int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++) { - if (cfg.MergeMode && dst_tmp.GlyphsSet.GetBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite) + if (dst_tmp.GlyphsSet.GetBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true) continue; if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint)) // It is actually in the font? continue; @@ -1857,8 +1856,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) src_tmp.GlyphsCount++; dst_tmp.GlyphsCount++; src_tmp.GlyphsSet.SetBit(codepoint, true); - if (dst_tmp.SrcCount > 1) - dst_tmp.GlyphsSet.SetBit(codepoint, true); + dst_tmp.GlyphsSet.SetBit(codepoint, true); total_glyphs_count++; } } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index f7523644..012eae75 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -336,15 +336,14 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns { ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i]; ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; - ImFontConfig& cfg = atlas->ConfigData[src_i]; src_tmp.GlyphsSet.Resize(src_tmp.GlyphsHighest + 1); - if (dst_tmp.SrcCount > 1 && dst_tmp.GlyphsSet.Storage.empty()) + if (dst_tmp.GlyphsSet.Storage.empty()) dst_tmp.GlyphsSet.Resize(dst_tmp.GlyphsHighest + 1); for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2) for (int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++) { - if (cfg.MergeMode && dst_tmp.GlyphsSet.GetBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite) + if (dst_tmp.GlyphsSet.GetBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite) continue; uint32_t glyph_index = FT_Get_Char_Index(src_tmp.Font.Face, codepoint); // It is actually in the font? (FIXME-OPT: We are not storing the glyph_index..) if (glyph_index == 0) @@ -354,8 +353,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns src_tmp.GlyphsCount++; dst_tmp.GlyphsCount++; src_tmp.GlyphsSet.SetBit(codepoint, true); - if (dst_tmp.SrcCount > 1) - dst_tmp.GlyphsSet.SetBit(codepoint, true); + dst_tmp.GlyphsSet.SetBit(codepoint, true); total_glyphs_count++; } } From 3de440fda225160f6c1bf2435d245a8947a18bdb Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 18 Feb 2019 16:13:17 +0100 Subject: [PATCH 065/566] Docking: Fixed assert in DockContextProcessDock() preventing some uses of DockNodeBuilder api. (#2357, #2109) --- imgui.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 08223e3e..8f09219b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10624,8 +10624,9 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) } // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well + // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. if (target_node) - IM_ASSERT(target_node->LastFrameAlive < g.FrameCount); + IM_ASSERT(target_node->LastFrameAlive <= g.FrameCount); if (target_node && target_window && target_node == target_window->DockNodeAsHost) IM_ASSERT(target_node->Windows.Size > 0 || target_node->IsSplitNode() || target_node->IsCentralNode); @@ -11975,7 +11976,7 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG parent_node->VisibleWindow = NULL; float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE); - IM_ASSERT(size_avail > 0.0f); + IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. child_0->SizeRef = child_1->SizeRef = parent_node->Size; child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio); child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]); @@ -12476,7 +12477,6 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) { DockSpace(id, ImVec2(0, 0), flags | ImGuiDockNodeFlags_KeepAliveOnly); node = DockContextFindNodeByID(ctx, id); - node->LastFrameAlive = -1; } else { @@ -12484,8 +12484,8 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) node = DockContextFindNodeByID(ctx, id); if (!node) node = DockContextAddNode(ctx, id); - node->LastFrameAlive = ctx->FrameCount; } + node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame. return node->ID; } From 5412cdf2c865c08a6713ed1fbd860e21de411996 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 18 Feb 2019 16:23:54 +0100 Subject: [PATCH 066/566] Docking: Made DockBuilderSplitNode/DockNodeTreeSplit work even if the node doesn't have a size yet. (#2357, #2109) Followup to fa0ce4b7d, at that time I came to the conclusion that programmatic split couldn't work without knowing the size ahead of it. I forgot the reason for that. May bite us back! --- imgui.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 8f09219b..b03f5bfb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11959,6 +11959,7 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node) { + ImGuiContext& g = *GImGui; IM_ASSERT(split_axis != ImGuiAxis_None); ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0); @@ -11976,6 +11977,7 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG parent_node->VisibleWindow = NULL; float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE); + size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f); IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. child_0->SizeRef = child_1->SizeRef = parent_node->Size; child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio); From 7573d10a4ad3a09dfba9f32d2df0bb1d49f5f2a2 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 18 Feb 2019 16:50:39 +0100 Subject: [PATCH 067/566] Docking: Fixed bad ever-growing/ leak (accumulating text into TabsNames forever, fix d38f4dc14 from February 5th, affected docking branch only). (#2109) --- imgui_widgets.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8f4b7391..6d2250c8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6452,8 +6452,17 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab->Window = docked_window; // Append name with zero-terminator - tab->NameOffset = tab_bar->TabsNames.size(); - tab_bar->TabsNames.append(label, label + strlen(label) + 1); + if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) + { + IM_ASSERT(tab->Window != NULL); + tab->NameOffset = -1; + } + else + { + IM_ASSERT(tab->Window == NULL); + tab->NameOffset = tab_bar->TabsNames.size(); + tab_bar->TabsNames.append(label, label + strlen(label) + 1); // Append name _with_ the zero-terminator. + } // If we are not reorderable, always reset offset based on submission order. // (We already handled layout and sizing using the previous known order, but sizing is not affected by order!) From 3c15dffc944419eb4bb17984548468270ca90486 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 19 Feb 2019 12:17:28 +0100 Subject: [PATCH 068/566] Version 1.68 --- docs/CHANGELOG.txt | 6 +++--- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1d49b4c0..350752fb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -30,7 +30,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.68 (In progress) + VERSION 1.68 (Released 2019-02-19) ----------------------------------------------------------------------- Breaking Changes: @@ -47,12 +47,12 @@ Other Changes: multi-viewport feature to behave on Retina display and with multiple displays. If you are not using a custom binding, please update your render function code ahead of time, and use draw_data->FramebufferScale instead of io.DisplayFramebufferScale. (#2306, #1676) +- Added IsItemActivated() as an extension to the IsItemDeactivated/IsItemDeactivatedAfterEdit functions + which are useful to implement variety of undo patterns. (#820, #956, #1875) - InputText: Fixed a bug where ESCAPE would not restore the initial value in all situations. (#2321) [@relick] - InputText: Fixed a bug where ESCAPE would be first captured by the Keyboard Navigation code. (#2321, #787) - InputText: Fixed redo buffer exhaustion handling (rare) which could corrupt the undo character buffer. (#2333) The way the redo/undo buffers work would have made it generally unnoticeable to the user. -- Added IsItemActivated() as an extension to the IsItemDeactivated/IsItemDeactivatedAfterEdit functions - which are useful to implement variety of undo patterns. (#820, #956, #1875) - Fixed range-version of PushID() and GetID() not honoring the ### operator to restart from the seed value. - Fixed CloseCurrentPopup() on a child-menu of a modal incorrectly closing the modal. (#2308) - Tabs: Added ImGuiTabBarFlags_TabListPopupButton flag to show a popup button on manual tab bars. (#261, #351) diff --git a/imgui.cpp b/imgui.cpp index f1b626dc..da0b068d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 WIP +// dear imgui, v1.68 // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index b8be7621..3cd00a35 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.68 WIP +// dear imgui, v1.68 // (headers) // See imgui.cpp file for documentation. @@ -45,8 +45,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY00 then bounced up to XYY01 when release tagging happens) -#define IMGUI_VERSION "1.68 WIP" -#define IMGUI_VERSION_NUM 16800 +#define IMGUI_VERSION "1.68" +#define IMGUI_VERSION_NUM 16801 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8618a9ee..d2fa3a3b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 WIP +// dear imgui, v1.68 // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7c513f6f..075ea0d2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 WIP +// dear imgui, v1.68 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 48a8b0a4..e5b65040 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.68 WIP +// dear imgui, v1.68 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ee18ea90..2ac389c1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 WIP +// dear imgui, v1.68 // (widgets code) /* From ff0f9aa8565e2b5092cbe05e44798e9e04dd445e Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 19 Feb 2019 16:36:06 +0100 Subject: [PATCH 069/566] Comments for Linux/Mac (#2117) --- examples/imgui_impl_glfw.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index e67af822..45b2d0e7 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -471,6 +471,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) viewport->PlatformUserData = viewport->PlatformHandle = NULL; } +// FIXME-VIEWPORT: Implement same work-around for Linux/OSX in the meanwhile. #if defined(_WIN32) && GLFW_HAS_GLFW_HOVERED static WNDPROC g_GlfwWndProc = NULL; static LRESULT CALLBACK WndProcNoInputs(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) @@ -513,7 +514,9 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) #endif // GLFW hack: GLFW 3.2 has a bug where glfwShowWindow() also activates/focus the window. - // The fix was pushed to GLFW repository on 2018/01/09 and should be included in GLFW 3.3. See https://github.com/glfw/glfw/issues/1179 + // The fix was pushed to GLFW repository on 2018/01/09 and should be included in GLFW 3.3 via a GLFW_FOCUS_ON_SHOW window attribute. + // See https://github.com/glfw/glfw/issues/1189 + // FIXME-VIEWPORT: Implement same work-around for Linux/OSX in the meanwhile. if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) { ::ShowWindow(hwnd, SW_SHOWNA); From 77833003ffb69f4cb769eebccd3c1a89f0c1c337 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 19 Feb 2019 17:32:14 +0100 Subject: [PATCH 070/566] Fixed unused argument warning when compiling with IM_ASERT() evaluating to an empty macro. --- imgui_widgets.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ac389c1..f48a55bc 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2616,6 +2616,7 @@ int ImParseFormatPrecision(const char* fmt, int default_precision) // FIXME: Facilitate using this in variety of other situations. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format) { + IM_UNUSED(id); ImGuiContext& g = *GImGui; // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id. From d0c98bf8805bb04782dff84ead37a38c220cbc7d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 19 Feb 2019 20:13:06 +0100 Subject: [PATCH 071/566] Examples: VS: Made project paths independant of SolutionDir so they can be built aside from the solution. --- .../example_glfw_opengl2.vcxproj | 16 ++++++++-------- .../example_glfw_opengl3.vcxproj | 16 ++++++++-------- .../example_glfw_vulkan.vcxproj | 18 +++++++++--------- .../example_sdl_opengl2.vcxproj | 8 ++++---- .../example_sdl_opengl3.vcxproj | 8 ++++---- .../example_win32_directx9.vcxproj | 8 ++++---- 6 files changed, 37 insertions(+), 37 deletions(-) diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index 73c7ba9d..7f6c2cbb 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -85,11 +85,11 @@ Level4 Disabled - ..\..;..;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) true - $(SolutionDir)\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -99,11 +99,11 @@ Level4 Disabled - ..\..;..;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) true - $(SolutionDir)\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -115,14 +115,14 @@ MaxSpeed true true - ..\..;..;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) false true true true - $(SolutionDir)\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console @@ -135,14 +135,14 @@ MaxSpeed true true - ..\..;..;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) false true true true - $(SolutionDir)\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 172a34d8..b80ca54e 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -85,11 +85,11 @@ Level4 Disabled - ..\..;..;$(SolutionDir)\libs\glfw\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true - $(SolutionDir)\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -99,11 +99,11 @@ Level4 Disabled - ..\..;..;$(SolutionDir)\libs\glfw\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true - $(SolutionDir)\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -115,14 +115,14 @@ MaxSpeed true true - ..\..;..;$(SolutionDir)\libs\glfw\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false true true true - $(SolutionDir)\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console @@ -135,14 +135,14 @@ MaxSpeed true true - ..\..;..;$(SolutionDir)\libs\glfw\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false true true true - $(SolutionDir)\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) + ..\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) opengl32.lib;glfw3.lib;%(AdditionalDependencies) Console diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index b0305e8f..53e09a8c 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -1,4 +1,4 @@ - + @@ -85,11 +85,11 @@ Level4 Disabled - ..\..;..;%VULKAN_SDK%\include;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) true - %VULKAN_SDK%\lib32;$(SolutionDir)\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) + %VULKAN_SDK%\lib32;..\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) vulkan-1.lib;glfw3.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -99,11 +99,11 @@ Level4 Disabled - ..\..;..;%VULKAN_SDK%\include;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) true - %VULKAN_SDK%\lib;$(SolutionDir)\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) + %VULKAN_SDK%\lib;..\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) vulkan-1.lib;glfw3.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -115,14 +115,14 @@ MaxSpeed true true - ..\..;..;%VULKAN_SDK%\include;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) false true true true - %VULKAN_SDK%\lib32;$(SolutionDir)\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) + %VULKAN_SDK%\lib32;..\libs\glfw\lib-vc2010-32;%(AdditionalLibraryDirectories) vulkan-1.lib;glfw3.lib;%(AdditionalDependencies) Console @@ -135,14 +135,14 @@ MaxSpeed true true - ..\..;..;%VULKAN_SDK%\include;$(SolutionDir)\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) false true true true - %VULKAN_SDK%\lib;$(SolutionDir)\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) + %VULKAN_SDK%\lib;..\libs\glfw\lib-vc2010-64;%(AdditionalLibraryDirectories) vulkan-1.lib;glfw3.lib;%(AdditionalDependencies) Console diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index fa6b8d3a..bcc9de95 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -85,7 +85,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -99,7 +99,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -115,7 +115,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false @@ -135,7 +135,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj index 9fda1897..2bc265b0 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj @@ -85,7 +85,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true @@ -99,7 +99,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true @@ -115,7 +115,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false @@ -135,7 +135,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index 08f21c87..b1c40c27 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -85,7 +85,7 @@ true - $(DXSDK_DIR)Lib\x86;%(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) d3d9.lib;%(AdditionalDependencies) Console @@ -98,7 +98,7 @@ true - $(DXSDK_DIR)Lib\x64;%(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) d3d9.lib;%(AdditionalDependencies) Console @@ -116,7 +116,7 @@ true true true - $(DXSDK_DIR)Lib\x86;%(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) d3d9.lib;%(AdditionalDependencies) Console @@ -134,7 +134,7 @@ true true true - $(DXSDK_DIR)Lib\x64;%(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) d3d9.lib;%(AdditionalDependencies) Console From 91cc32379dc28907e068d6c97cb562706c510d8b Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 19 Feb 2019 20:27:47 +0100 Subject: [PATCH 072/566] Updated binaries (now auto-generated by a script! next step would be to slowly transition all this stuff into a public repo) --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index d1c1c272..ebf7f926 100644 --- a/docs/README.md +++ b/docs/README.md @@ -102,7 +102,7 @@ Demo Binaries ------------- You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me 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-20181008.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20181008.zip) (Windows binaries, Dear ImGui 1.66 WIP built 2018/10/08, master branch, 5 executables) +- [imgui-demo-binaries-20190219.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20190219.zip) (Windows binaries, Dear ImGui 1.68 built 2019/02/19, master branch, 5 executables) The demo applications are unfortunately not yet DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your Style with `style.ScaleAllSizes()`. From 93b06e6e7c7295c442c464ebec8d4b0c344b0d28 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 19 Feb 2019 23:39:44 +0100 Subject: [PATCH 073/566] Internal: Changed Scrollbar() signature. Using GetScrollbarID() in InputTextMultiline(). Removed multiple semi-colons (#2368) --- imgui.cpp | 8 ++++---- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 21 ++++++++++----------- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index da0b068d..d04fe1ac 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5265,9 +5265,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Scrollbars if (window->ScrollbarX) - Scrollbar(ImGuiLayoutType_Horizontal); + Scrollbar(ImGuiAxis_X); if (window->ScrollbarY) - Scrollbar(ImGuiLayoutType_Vertical); + Scrollbar(ImGuiAxis_Y); // Render resize grips (after their input handling so we don't have a frame of latency) if (!(flags & ImGuiWindowFlags_NoResize)) @@ -6528,13 +6528,13 @@ ImGuiID ImGui::GetID(const void* ptr_id) bool ImGui::IsRectVisible(const ImVec2& size) { - ImGuiWindow* window = GImGui->CurrentWindow;; + ImGuiWindow* window = GImGui->CurrentWindow; return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) { - ImGuiWindow* window = GImGui->CurrentWindow;; + ImGuiWindow* window = GImGui->CurrentWindow; return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } diff --git a/imgui_internal.h b/imgui_internal.h index e5b65040..4ebbaa81 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1463,8 +1463,8 @@ namespace ImGui IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags); - IMGUI_API void Scrollbar(ImGuiLayoutType direction); - IMGUI_API ImGuiID GetScrollbarID(ImGuiLayoutType direction); + IMGUI_API void Scrollbar(ImGuiAxis axis); + IMGUI_API ImGuiID GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API void VerticalSeparator(); // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. // Widgets low-level behaviors diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f48a55bc..943a2792 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -710,11 +710,9 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) return pressed; } -ImGuiID ImGui::GetScrollbarID(ImGuiLayoutType direction) +ImGuiID ImGui::GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - return window->GetID((direction == ImGuiLayoutType_Horizontal) ? "#SCROLLX" : "#SCROLLY"); + return window->GetIDNoKeepAlive(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY"); } // Vertical/Horizontal scrollbar @@ -722,15 +720,16 @@ ImGuiID ImGui::GetScrollbarID(ImGuiLayoutType direction) // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. -void ImGui::Scrollbar(ImGuiLayoutType direction) +void ImGui::Scrollbar(ImGuiAxis axis) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - const bool horizontal = (direction == ImGuiLayoutType_Horizontal); + const bool horizontal = (axis == ImGuiAxis_X); const ImGuiStyle& style = g.Style; - const ImGuiID id = GetScrollbarID(direction); - + const ImGuiID id = GetScrollbarID(window, axis); + KeepAliveID(id); + // Render background bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; @@ -748,7 +747,7 @@ void ImGui::Scrollbar(ImGuiLayoutType direction) // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab) float alpha = 1.0f; - if ((direction == ImGuiLayoutType_Vertical) && bb_height < g.FontSize + g.Style.FramePadding.y * 2.0f) + if ((axis == ImGuiAxis_Y) && bb_height < g.FontSize + g.Style.FramePadding.y * 2.0f) { alpha = ImSaturate((bb_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f)); if (alpha <= 0.0f) @@ -3210,7 +3209,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool user_clicked = hovered && io.MouseClicked[0]; - const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.ID == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY"); + const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.ID == id && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y); const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard)); bool clear_active_id = false; @@ -3622,7 +3621,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.f, 0.f); - const bool is_currently_scrolling = (edit_state.ID == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY")); + const bool is_currently_scrolling = (edit_state.ID == id && is_multiline && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y)); if (g.ActiveId == id || is_currently_scrolling) { edit_state.CursorAnim += io.DeltaTime; From 257f5d204e411ea49e2eac04603451f87fe8eb8f Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 Feb 2019 00:11:36 +0100 Subject: [PATCH 074/566] Version 1.69 WIP --- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 7 files changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 350752fb..e2119884 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -29,6 +29,11 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.69 (In Progress) +----------------------------------------------------------------------- + + ----------------------------------------------------------------------- VERSION 1.68 (Released 2019-02-19) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index d04fe1ac..19dfb983 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 +// dear imgui, v1.69 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index 3cd00a35..e109f3a4 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.68 +// dear imgui, v1.69 WIP // (headers) // See imgui.cpp file for documentation. @@ -45,8 +45,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY00 then bounced up to XYY01 when release tagging happens) -#define IMGUI_VERSION "1.68" -#define IMGUI_VERSION_NUM 16801 +#define IMGUI_VERSION "1.69 WIP" +#define IMGUI_VERSION_NUM 16899 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d2fa3a3b..560224f1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 +// dear imgui, v1.69 WIP // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 075ea0d2..05480266 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 +// dear imgui, v1.69 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 4ebbaa81..b5d72ae8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.68 +// dear imgui, v1.69 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 943a2792..327e3d83 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.68 +// dear imgui, v1.69 WIP // (widgets code) /* From 7c51cba74f4a871c502cf291bc0d134cf41e3bd4 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 Feb 2019 00:20:11 +0100 Subject: [PATCH 075/566] InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) --- docs/CHANGELOG.txt | 6 ++++++ imgui_widgets.cpp | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e2119884..16664518 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -33,6 +33,12 @@ HOW TO UPDATE? VERSION 1.69 (In Progress) ----------------------------------------------------------------------- +Other Changes: + +- InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when + style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are + meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) + ----------------------------------------------------------------------- VERSION 1.68 (Released 2019-02-19) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 327e3d83..1fb7dd6d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2648,7 +2648,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p return false; ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiStyle& style = g.Style; IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) @@ -2674,6 +2674,8 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p PopItemWidth(); // Step buttons + const ImVec2 backup_frame_padding = style.FramePadding; + style.FramePadding.x = style.FramePadding.y; ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups; if (flags & ImGuiInputTextFlags_ReadOnly) button_flags |= ImGuiButtonFlags_Disabled; @@ -2691,6 +2693,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p } SameLine(0, style.ItemInnerSpacing.x); TextUnformatted(label, FindRenderedTextEnd(label)); + style.FramePadding = backup_frame_padding; PopID(); EndGroup(); From 782b747a17299ec9018257d0671d472d4cbdf355 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 Feb 2019 00:40:09 +0100 Subject: [PATCH 076/566] InputText: Renamed some local variables to clarify code. Should be a no-op functionality wise. TODO items. --- docs/TODO.txt | 7 +++++-- imgui_widgets.cpp | 12 +++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 114bd995..01b54716 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -72,8 +72,11 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725) - input text: display bug when clicking a drag/slider after an input text in a different window has all-selected text (order dependent). actually a very old bug but no one appears to have noticed it. - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. - - input text: what's the easiest way to implement a nice IP/Mac address input editor? - - input text: Global callback system so user can plug in an expression evaluator easily. + - input text: decorrelate layout from inputs - e.g. what's the easiest way to implement a nice IP/Mac address input editor? + - input text: global callback system so user can plug in an expression evaluator easily. + - input text: force scroll to end or scroll to a given line/contents (so user can implement a log or a search feature) + - input text: a side bar that could e.g. preview where errors are. probably left to the user to draw but we'd need to give them the info there. + - input text: a way for the user to provide syntax coloring. - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). - input text multi-line: support for cut/paste without selection (cut/paste the current line) - input text multi-line: line numbers? status bar? (follow up on #200) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1fb7dd6d..57cd25a3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3212,13 +3212,14 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool user_clicked = hovered && io.MouseClicked[0]; - const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.ID == id && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y); const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard)); + const bool user_scroll_finish = is_multiline && edit_state.ID == id && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y); + const bool user_scroll_active = is_multiline && edit_state.ID == id && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y); bool clear_active_id = false; bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline); - if (focus_requested || user_clicked || user_scrolled || user_nav_input_start) + if (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start) { if (g.ActiveId != id) { @@ -3624,9 +3625,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.f, 0.f); - const bool is_currently_scrolling = (edit_state.ID == id && is_multiline && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y)); - if (g.ActiveId == id || is_currently_scrolling) + if (g.ActiveId == id || user_scroll_active) { + // Animate cursor edit_state.CursorAnim += io.DeltaTime; // This is going to be messy. We need to: @@ -3707,7 +3708,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - size.y >= scroll_y) scroll_y = cursor_offset.y - size.y; - draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag + draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; render_pos.y = draw_window->DC.CursorPos.y; } @@ -3751,6 +3752,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } } + // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. const int buf_display_len = edit_state.CurLenA; if (is_multiline || buf_display_len < buf_display_max_length) draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + buf_display_len, 0.0f, is_multiline ? NULL : &clip_rect); From 2068dd509c6599d0b4339d610e6e68eaa9b0d61e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 Feb 2019 14:31:19 +0100 Subject: [PATCH 077/566] Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_opengl3.cpp | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 16664518..199882b9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,6 +38,8 @@ Other Changes: - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) +- Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN + even if the OpenGL headers/loader happens to define the value. (#2366, #2186) ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index bd8c94e6..9a53d3c6 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -11,10 +11,11 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. -// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT). +// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN. // 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used. // 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES". // 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation. @@ -169,7 +170,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); bool clip_origin_lower_left = true; -#ifdef GL_CLIP_ORIGIN +#if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__) GLenum last_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&last_clip_origin); // Support for GL 4.5's glClipControl(GL_UPPER_LEFT) if (last_clip_origin == GL_UPPER_LEFT) clip_origin_lower_left = false; From 79f7778e48fb262b3c8cd52a97bbdd91533ec459 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 Feb 2019 15:10:23 +0100 Subject: [PATCH 078/566] Moved binaries to dearimgui.org/binaries --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index ebf7f926..7e041181 100644 --- a/docs/README.md +++ b/docs/README.md @@ -102,7 +102,7 @@ Demo Binaries ------------- You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me 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-20190219.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20190219.zip) (Windows binaries, Dear ImGui 1.68 built 2019/02/19, master branch, 5 executables) +- [imgui-demo-binaries-20190219.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20190219.zip) (Windows binaries, Dear ImGui 1.68 built 2019/02/19, master branch, 5 executables) The demo applications are unfortunately not yet DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your Style with `style.ScaleAllSizes()`. From 677e64e71eba79a74496ac1aae40f180aa936213 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 Feb 2019 21:25:17 +0100 Subject: [PATCH 079/566] Internal: InputText: Comments. Renamed internal member. Renamed ImGuiStb->ImStb. --- imgui_draw.cpp | 4 ++-- imgui_internal.h | 20 +++++++++--------- imgui_widgets.cpp | 53 ++++++++++++++++++++++++----------------------- 3 files changed, 39 insertions(+), 38 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 05480266..37e8ff51 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -83,7 +83,7 @@ Index of this file: //------------------------------------------------------------------------- // Compile time options: -//#define IMGUI_STB_NAMESPACE ImGuiStb +//#define IMGUI_STB_NAMESPACE ImStb //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION @@ -163,7 +163,7 @@ namespace IMGUI_STB_NAMESPACE #endif #ifdef IMGUI_STB_NAMESPACE -} // namespace ImGuiStb +} // namespace ImStb using namespace IMGUI_STB_NAMESPACE; #endif diff --git a/imgui_internal.h b/imgui_internal.h index b5d72ae8..ac36ba61 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -96,7 +96,7 @@ typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: // STB libraries includes //------------------------------------------------------------------------- -namespace ImGuiStb +namespace ImStb { #undef STB_TEXTEDIT_STRING @@ -106,7 +106,7 @@ namespace ImGuiStb #define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f #include "imstb_textedit.h" -} // namespace ImGuiStb +} // namespace ImStb //----------------------------------------------------------------------------- // Context pointer @@ -567,10 +567,10 @@ struct IMGUI_API ImGuiInputTextState int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. int BufCapacityA; // end-user buffer capacity float ScrollX; - ImGuiStb::STB_TexteditState StbState; - float CursorAnim; - bool CursorFollow; - bool SelectedAllMouseLock; + ImStb::STB_TexteditState Stb; // state for stb_textedit.h + float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately + bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) + bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection // Temporarily set when active ImGuiInputTextFlags UserFlags; @@ -579,10 +579,10 @@ struct IMGUI_API ImGuiInputTextState ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking - void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); } - bool HasSelection() const { return StbState.select_start != StbState.select_end; } - void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; } - void SelectAll() { StbState.select_start = 0; StbState.cursor = StbState.select_end = CurLenW; StbState.has_preferred_x = 0; } + void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } + bool HasSelection() const { return Stb.select_start != Stb.select_end; } + void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } + void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 57cd25a3..86fa6d1b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2898,7 +2898,7 @@ static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* t } // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) -namespace ImGuiStb +namespace ImStb { static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } @@ -3001,7 +3001,7 @@ static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const Im void ImGuiInputTextState::OnKeyPressed(int key) { - stb_textedit_key(this, &StbState, key); + stb_textedit_key(this, &Stb, key); CursorFollow = true; CursorAnimReset(); } @@ -3249,12 +3249,12 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { edit_state.ID = id; edit_state.ScrollX = 0.0f; - stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); + stb_textedit_initialize_state(&edit_state.Stb, !is_multiline); if (!is_multiline && focus_requested_by_code) select_all = true; } if (flags & ImGuiInputTextFlags_AlwaysInsertMode) - edit_state.StbState.insert_mode = 1; + edit_state.Stb.insert_mode = 1; if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) select_all = true; } @@ -3318,13 +3318,13 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { if (hovered) { - stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + stb_textedit_click(&edit_state, &edit_state.Stb, mouse_x, mouse_y); edit_state.CursorAnimReset(); } } else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { - stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + stb_textedit_drag(&edit_state, &edit_state.Stb, mouse_x, mouse_y); edit_state.CursorAnimReset(); edit_state.CursorFollow = true; } @@ -3424,8 +3424,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Cut, Copy if (io.SetClipboardTextFn) { - const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; - const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; + const int ib = edit_state.HasSelection() ? ImMin(edit_state.Stb.select_start, edit_state.Stb.select_end) : 0; + const int ie = edit_state.HasSelection() ? ImMax(edit_state.Stb.select_start, edit_state.Stb.select_end) : edit_state.CurLenW; edit_state.TempBuffer.resize((ie-ib) * 4 + 1); ImTextStrToUtf8(edit_state.TempBuffer.Data, edit_state.TempBuffer.Size, edit_state.TextW.Data+ib, edit_state.TextW.Data+ie); SetClipboardText(edit_state.TempBuffer.Data); @@ -3435,7 +3435,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (!edit_state.HasSelection()) edit_state.SelectAll(); edit_state.CursorFollow = true; - stb_textedit_cut(&edit_state, &edit_state.StbState); + stb_textedit_cut(&edit_state, &edit_state.Stb); } } else if (is_paste) @@ -3459,7 +3459,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation { - stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); + stb_textedit_paste(&edit_state, &edit_state.Stb, clipboard_filtered, clipboard_filtered_len); edit_state.CursorFollow = true; } MemFree(clipboard_filtered); @@ -3538,9 +3538,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) ImWchar* text = edit_state.TextW.Data; - const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); - const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); - const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.Stb.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.Stb.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.Stb.select_end); // Call user code callback(&callback_data); @@ -3549,9 +3549,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 IM_ASSERT(callback_data.Buf == edit_state.TempBuffer.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == edit_state.BufCapacityA); IM_ASSERT(callback_data.Flags == flags); - if (callback_data.CursorPos != utf8_cursor_pos) { edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); edit_state.CursorFollow = true; } - if (callback_data.SelectionStart != utf8_selection_start) { edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } - if (callback_data.SelectionEnd != utf8_selection_end) { edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } + if (callback_data.CursorPos != utf8_cursor_pos) { edit_state.Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); edit_state.CursorFollow = true; } + if (callback_data.SelectionStart != utf8_selection_start) { edit_state.Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } + if (callback_data.SelectionEnd != utf8_selection_end) { edit_state.Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } if (callback_data.BufDirty) { IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! @@ -3607,15 +3607,16 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (clear_active_id && g.ActiveId == id) ClearActiveID(); - // Render - // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on. - const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempBuffer.Data : buf; buf = NULL; - // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. const int buf_display_max_length = 2 * 1024 * 1024; + // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. + const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempBuffer.Data : buf; + buf = NULL; + + // Render if (!is_multiline) { RenderNavHighlight(frame_bb, id); @@ -3642,13 +3643,13 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. const ImWchar* searches_input_ptr[2]; - searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; + searches_input_ptr[0] = text_begin + edit_state.Stb.cursor; searches_input_ptr[1] = NULL; int searches_remaining = 1; int searches_result_line_number[2] = { -1, -999 }; - if (edit_state.StbState.select_start != edit_state.StbState.select_end) + if (edit_state.Stb.select_start != edit_state.Stb.select_end) { - searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + searches_input_ptr[1] = text_begin + ImMin(edit_state.Stb.select_start, edit_state.Stb.select_end); searches_result_line_number[1] = -1; searches_remaining++; } @@ -3717,10 +3718,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); // Draw selection - if (edit_state.StbState.select_start != edit_state.StbState.select_end) + if (edit_state.Stb.select_start != edit_state.Stb.select_end) { - const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); - const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); + const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.Stb.select_start, edit_state.Stb.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(edit_state.Stb.select_start, edit_state.Stb.select_end); float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; From 2e9a175057fa9e983332aa5b0683203b5bb42317 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 21 Feb 2019 12:24:50 +0100 Subject: [PATCH 080/566] Internal: InputText: Refactor to clarify access pattern to the InputTextState (we are now accessing via a pointer which can be NULL, shortened its name while we are at it) + added an assert to track an issue that existed already before. --- imgui_widgets.cpp | 243 ++++++++++++++++++++++++---------------------- 1 file changed, 128 insertions(+), 115 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 86fa6d1b..4598194f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3205,7 +3205,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // NB: we are only allowed to access 'edit_state' if we are the active widget. - ImGuiInputTextState& edit_state = g.InputTextState; + ImGuiInputTextState* state = NULL; + if (g.InputTextState.ID == id) + state = &g.InputTextState; const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); @@ -3213,8 +3215,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const bool user_clicked = hovered && io.MouseClicked[0]; const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard)); - const bool user_scroll_finish = is_multiline && edit_state.ID == id && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y); - const bool user_scroll_active = is_multiline && edit_state.ID == id && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y); + const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y); + const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y); bool clear_active_id = false; @@ -3223,41 +3225,46 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { if (g.ActiveId != id) { + // Access state even if we don't own it yet. + state = &g.InputTextState; + // Start edition // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) - const int prev_len_w = edit_state.CurLenW; + const int prev_len_w = state->CurLenW; const int init_buf_len = (int)strlen(buf); - edit_state.TextW.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. - edit_state.InitialText.resize(init_buf_len + 1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. - memcpy(edit_state.InitialText.Data, buf, init_buf_len + 1); + state->TextW.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + state->InitialText.resize(init_buf_len + 1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + memcpy(state->InitialText.Data, buf, init_buf_len + 1); const char* buf_end = NULL; - edit_state.CurLenW = ImTextStrFromUtf8(edit_state.TextW.Data, buf_size, buf, NULL, &buf_end); - edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. - edit_state.CursorAnimReset(); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. + state->CursorAnimReset(); // Preserve cursor position and undo/redo stack if we come back to same widget // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). - const bool recycle_state = (edit_state.ID == id) && (prev_len_w == edit_state.CurLenW); + const bool recycle_state = (state->ID == id) && (prev_len_w == state->CurLenW); if (recycle_state) { // Recycle existing cursor/selection/undo stack but clamp position // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. - edit_state.CursorClamp(); + state->CursorClamp(); } else { - edit_state.ID = id; - edit_state.ScrollX = 0.0f; - stb_textedit_initialize_state(&edit_state.Stb, !is_multiline); + state->ID = id; + state->ScrollX = 0.0f; + stb_textedit_initialize_state(&state->Stb, !is_multiline); if (!is_multiline && focus_requested_by_code) select_all = true; } if (flags & ImGuiInputTextFlags_AlwaysInsertMode) - edit_state.Stb.insert_mode = 1; + state->Stb.insert_mode = 1; if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) select_all = true; } + + IM_ASSERT(state && state->ID == id); SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); @@ -3277,21 +3284,22 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (g.ActiveId == id) { + IM_ASSERT(state != NULL); if (!is_editable && !g.ActiveIdIsJustActivated) { // When read-only we always use the live data passed to the function - edit_state.TextW.resize(buf_size+1); const char* buf_end = NULL; - edit_state.CurLenW = ImTextStrFromUtf8(edit_state.TextW.Data, edit_state.TextW.Size, buf, NULL, &buf_end); - edit_state.CurLenA = (int)(buf_end - buf); - edit_state.CursorClamp(); + state->TextW.resize(buf_size+1); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); + state->CursorClamp(); } - backup_current_text_length = edit_state.CurLenA; - edit_state.BufCapacityA = buf_size; - edit_state.UserFlags = flags; - edit_state.UserCallback = callback; - edit_state.UserCallbackData = callback_user_data; + backup_current_text_length = state->CurLenA; + state->BufCapacityA = buf_size; + state->UserFlags = flags; + state->UserCallback = callback; + state->UserCallbackData = callback_user_data; // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. // Down the line we should have a cleaner library-wide concept of Selected vs Active. @@ -3299,37 +3307,37 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 g.WantTextInputNextFrame = 1; // Edit in progress - const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX; const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); const bool is_osx = io.ConfigMacOSXBehaviors; if (select_all || (hovered && !is_osx && io.MouseDoubleClicked[0])) { - edit_state.SelectAll(); - edit_state.SelectedAllMouseLock = true; + state->SelectAll(); + state->SelectedAllMouseLock = true; } else if (hovered && is_osx && io.MouseDoubleClicked[0]) { // Double-click select a word only, OS X style (by simulating keystrokes) - edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); - edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); } - else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) + else if (io.MouseClicked[0] && !state->SelectedAllMouseLock) { if (hovered) { - stb_textedit_click(&edit_state, &edit_state.Stb, mouse_x, mouse_y); - edit_state.CursorAnimReset(); + stb_textedit_click(state, &state->Stb, mouse_x, mouse_y); + state->CursorAnimReset(); } } - else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { - stb_textedit_drag(&edit_state, &edit_state.Stb, mouse_x, mouse_y); - edit_state.CursorAnimReset(); - edit_state.CursorFollow = true; + stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y); + state->CursorAnimReset(); + state->CursorFollow = true; } - if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) - edit_state.SelectedAllMouseLock = false; + if (state->SelectedAllMouseLock && !io.MouseDown[0]) + state->SelectedAllMouseLock = false; if (io.InputQueueCharacters.Size > 0) { @@ -3342,7 +3350,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Insert character if they pass filtering unsigned int c = (unsigned int)io.InputQueueCharacters[n]; if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) - edit_state.OnKeyPressed((int)c); + state->OnKeyPressed((int)c); } // Consume characters @@ -3354,6 +3362,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id) { // Handle key-presses + IM_ASSERT(state != NULL); const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_osx = io.ConfigMacOSXBehaviors; const bool is_shortcut_key = (is_osx ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl @@ -3363,27 +3372,29 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper; const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper; - const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection()); - const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection()); + const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || state->HasSelection()); + const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection()); const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable; const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && is_editable && is_undoable); const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && is_editable && is_undoable; - if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) { - if (!edit_state.HasSelection()) + if (!state->HasSelection()) { - if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); - else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); + if (is_wordmove_key_down) + state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); + else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) + state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); } - edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); + state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Enter)) { @@ -3396,14 +3407,14 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { unsigned int c = '\n'; // Insert new line if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) - edit_state.OnKeyPressed((int)c); + state->OnKeyPressed((int)c); } } else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) { unsigned int c = '\t'; // Insert TAB if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) - edit_state.OnKeyPressed((int)c); + state->OnKeyPressed((int)c); } else if (IsKeyPressedMap(ImGuiKey_Escape)) { @@ -3411,31 +3422,31 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } else if (is_undo || is_redo) { - edit_state.OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO); - edit_state.ClearSelection(); + state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO); + state->ClearSelection(); } else if (is_shortcut_key && IsKeyPressedMap(ImGuiKey_A)) { - edit_state.SelectAll(); - edit_state.CursorFollow = true; + state->SelectAll(); + state->CursorFollow = true; } else if (is_cut || is_copy) { // Cut, Copy if (io.SetClipboardTextFn) { - const int ib = edit_state.HasSelection() ? ImMin(edit_state.Stb.select_start, edit_state.Stb.select_end) : 0; - const int ie = edit_state.HasSelection() ? ImMax(edit_state.Stb.select_start, edit_state.Stb.select_end) : edit_state.CurLenW; - edit_state.TempBuffer.resize((ie-ib) * 4 + 1); - ImTextStrToUtf8(edit_state.TempBuffer.Data, edit_state.TempBuffer.Size, edit_state.TextW.Data+ib, edit_state.TextW.Data+ie); - SetClipboardText(edit_state.TempBuffer.Data); + const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; + const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; + state->TempBuffer.resize((ie-ib) * 4 + 1); + ImTextStrToUtf8(state->TempBuffer.Data, state->TempBuffer.Size, state->TextW.Data+ib, state->TextW.Data+ie); + SetClipboardText(state->TempBuffer.Data); } if (is_cut) { - if (!edit_state.HasSelection()) - edit_state.SelectAll(); - edit_state.CursorFollow = true; - stb_textedit_cut(&edit_state, &edit_state.Stb); + if (!state->HasSelection()) + state->SelectAll(); + state->CursorFollow = true; + stb_textedit_cut(state, &state->Stb); } } else if (is_paste) @@ -3459,8 +3470,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation { - stb_textedit_paste(&edit_state, &edit_state.Stb, clipboard_filtered, clipboard_filtered_len); - edit_state.CursorFollow = true; + stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len); + state->CursorFollow = true; } MemFree(clipboard_filtered); } @@ -3469,15 +3480,16 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (g.ActiveId == id) { + IM_ASSERT(state != NULL); const char* apply_new_text = NULL; int apply_new_text_length = 0; if (cancel_edit) { // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents. - if (is_editable && strcmp(buf, edit_state.InitialText.Data) != 0) + if (is_editable && strcmp(buf, state->InitialText.Data) != 0) { - apply_new_text = edit_state.InitialText.Data; - apply_new_text_length = edit_state.InitialText.Size - 1; + apply_new_text = state->InitialText.Data; + apply_new_text_length = state->InitialText.Size - 1; } } @@ -3492,8 +3504,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. if (is_editable) { - edit_state.TempBuffer.resize(edit_state.TextW.Size * 4 + 1); - ImTextStrToUtf8(edit_state.TempBuffer.Data, edit_state.TempBuffer.Size, edit_state.TextW.Data, NULL); + state->TempBuffer.resize(state->TextW.Size * 4 + 1); + ImTextStrToUtf8(state->TempBuffer.Data, state->TempBuffer.Size, state->TextW.Data, NULL); } // User callback @@ -3531,44 +3543,44 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 callback_data.UserData = callback_user_data; callback_data.EventKey = event_key; - callback_data.Buf = edit_state.TempBuffer.Data; - callback_data.BufTextLen = edit_state.CurLenA; - callback_data.BufSize = edit_state.BufCapacityA; + callback_data.Buf = state->TempBuffer.Data; + callback_data.BufTextLen = state->CurLenA; + callback_data.BufSize = state->BufCapacityA; callback_data.BufDirty = false; // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) - ImWchar* text = edit_state.TextW.Data; - const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.Stb.cursor); - const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.Stb.select_start); - const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.Stb.select_end); + ImWchar* text = state->TextW.Data; + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end); // Call user code callback(&callback_data); // Read back what user may have modified - IM_ASSERT(callback_data.Buf == edit_state.TempBuffer.Data); // Invalid to modify those fields - IM_ASSERT(callback_data.BufSize == edit_state.BufCapacityA); + IM_ASSERT(callback_data.Buf == state->TempBuffer.Data); // Invalid to modify those fields + IM_ASSERT(callback_data.BufSize == state->BufCapacityA); IM_ASSERT(callback_data.Flags == flags); - if (callback_data.CursorPos != utf8_cursor_pos) { edit_state.Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); edit_state.CursorFollow = true; } - if (callback_data.SelectionStart != utf8_selection_start) { edit_state.Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } - if (callback_data.SelectionEnd != utf8_selection_end) { edit_state.Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } + if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } + if (callback_data.SelectionStart != utf8_selection_start) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } + if (callback_data.SelectionEnd != utf8_selection_end) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } if (callback_data.BufDirty) { IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! if (callback_data.BufTextLen > backup_current_text_length && is_resizable) - edit_state.TextW.resize(edit_state.TextW.Size + (callback_data.BufTextLen - backup_current_text_length)); - edit_state.CurLenW = ImTextStrFromUtf8(edit_state.TextW.Data, edit_state.TextW.Size, callback_data.Buf, NULL); - edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() - edit_state.CursorAnimReset(); + state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length)); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL); + state->CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() + state->CursorAnimReset(); } } } // Will copy result string if modified - if (is_editable && strcmp(edit_state.TempBuffer.Data, buf) != 0) + if (is_editable && strcmp(state->TempBuffer.Data, buf) != 0) { - apply_new_text = edit_state.TempBuffer.Data; - apply_new_text_length = edit_state.CurLenA; + apply_new_text = state->TempBuffer.Data; + apply_new_text_length = state->CurLenA; } } @@ -3598,9 +3610,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // Clear temporary user storage - edit_state.UserFlags = 0; - edit_state.UserCallback = NULL; - edit_state.UserCallbackData = NULL; + state->UserFlags = 0; + state->UserCallback = NULL; + state->UserCallbackData = NULL; } // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value) @@ -3613,7 +3625,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const int buf_display_max_length = 2 * 1024 * 1024; // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. - const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempBuffer.Data : buf; + const char* buf_display = (state != NULL && is_editable) ? state->TempBuffer.Data : buf; buf = NULL; // Render @@ -3629,7 +3641,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (g.ActiveId == id || user_scroll_active) { // Animate cursor - edit_state.CursorAnim += io.DeltaTime; + IM_ASSERT(state != NULL); + state->CursorAnim += io.DeltaTime; // This is going to be messy. We need to: // - Display the text (this alone can be more easily clipped) @@ -3637,19 +3650,19 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. - const ImWchar* text_begin = edit_state.TextW.Data; + const ImWchar* text_begin = state->TextW.Data; ImVec2 cursor_offset, select_start_offset; { // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. const ImWchar* searches_input_ptr[2]; - searches_input_ptr[0] = text_begin + edit_state.Stb.cursor; + searches_input_ptr[0] = text_begin + state->Stb.cursor; searches_input_ptr[1] = NULL; int searches_remaining = 1; int searches_result_line_number[2] = { -1, -999 }; - if (edit_state.Stb.select_start != edit_state.Stb.select_end) + if (state->Stb.select_start != state->Stb.select_end) { - searches_input_ptr[1] = text_begin + ImMin(edit_state.Stb.select_start, edit_state.Stb.select_end); + searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); searches_result_line_number[1] = -1; searches_remaining++; } @@ -3685,20 +3698,20 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // Scroll - if (edit_state.CursorFollow) + if (state->CursorFollow) { // Horizontal scroll in chunks of quarter width if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) { const float scroll_increment_x = size.x * 0.25f; - if (cursor_offset.x < edit_state.ScrollX) - edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); - else if (cursor_offset.x - size.x >= edit_state.ScrollX) - edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); + if (cursor_offset.x < state->ScrollX) + state->ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); + else if (cursor_offset.x - size.x >= state->ScrollX) + state->ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); } else { - edit_state.ScrollX = 0.0f; + state->ScrollX = 0.0f; } // Vertical scroll @@ -3714,14 +3727,14 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 render_pos.y = draw_window->DC.CursorPos.y; } } - edit_state.CursorFollow = false; - const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); + state->CursorFollow = false; + const ImVec2 render_scroll = ImVec2(state->ScrollX, 0.0f); // Draw selection - if (edit_state.Stb.select_start != edit_state.Stb.select_end) + if (state->Stb.select_start != state->Stb.select_end) { - const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.Stb.select_start, edit_state.Stb.select_end); - const ImWchar* text_selected_end = text_begin + ImMax(edit_state.Stb.select_start, edit_state.Stb.select_end); + const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end); float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; @@ -3754,7 +3767,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. - const int buf_display_len = edit_state.CurLenA; + const int buf_display_len = state->CurLenA; if (is_multiline || buf_display_len < buf_display_max_length) draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + buf_display_len, 0.0f, is_multiline ? NULL : &clip_rect); From cc3be5d4289587c7e1b0b29bfe37ab1c94e3aea8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 21 Feb 2019 12:25:21 +0100 Subject: [PATCH 081/566] InputText: Fixed an edge case crash that would happen if another widget sharing the same ID is being swapped with an InputText that has yet to be activated. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 199882b9..3634bf2c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,6 +38,8 @@ Other Changes: - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) +- InputText: Fixed an edge case crash that would happen if another widget sharing the same ID + is being swapped with an InputText that has yet to be activated. - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4598194f..6bbd417a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3278,6 +3278,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 clear_active_id = true; } + // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped) + if (g.ActiveId == id && state == NULL) + ClearActiveID(); + bool value_changed = false; bool enter_pressed = false; int backup_current_text_length = 0; From 81a8730022266791b0ba5cee56cea7b4e6bde78a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 21 Feb 2019 12:35:21 +0100 Subject: [PATCH 082/566] Internal: InputText: Renamed is_editable to !is_readonly, Hopefully more explicit. Renamed internal member. Shuffled some code. Added comments, assert (_will_ trigger on !readonly > readonly edge, old bug). --- imgui.cpp | 14 +++--- imgui_internal.h | 7 +-- imgui_widgets.cpp | 122 ++++++++++++++++++++++++---------------------- 3 files changed, 73 insertions(+), 70 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 19dfb983..ddcd10c2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -58,9 +58,9 @@ CODE // [SECTION] FORWARD DECLARATIONS // [SECTION] CONTEXT AND MEMORY ALLOCATORS // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) -// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions) -// [SECTION] MISC HELPER/UTILITIES (ImText* functions) -// [SECTION] MISC HELPER/UTILITIES (Color functions) +// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions) +// [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +// [SECTION] MISC HELPERS/UTILITIES (Color functions) // [SECTION] ImGuiStorage // [SECTION] ImGuiTextFilter // [SECTION] ImGuiTextBuffer @@ -1226,7 +1226,7 @@ void ImGuiIO::ClearInputCharacters() } //----------------------------------------------------------------------------- -// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions) +// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions) //----------------------------------------------------------------------------- ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p) @@ -1749,7 +1749,7 @@ int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_e } //----------------------------------------------------------------------------- -// [SECTION] MISC HELPER/UTILTIES (Color functions) +// [SECTION] MISC HELPERS/UTILTIES (Color functions) // Note: The Convert functions are early design which are not consistent with other API. //----------------------------------------------------------------------------- @@ -3603,9 +3603,7 @@ void ImGui::Shutdown(ImGuiContext* context) g.DrawDataBuilder.ClearFreeMemory(); g.OverlayDrawList.ClearFreeMemory(); g.PrivateClipboard.clear(); - g.InputTextState.TextW.clear(); - g.InputTextState.InitialText.clear(); - g.InputTextState.TempBuffer.clear(); + g.InputTextState.ClearFreeMemory(); for (int i = 0; i < g.SettingsWindows.Size; i++) IM_DELETE(g.SettingsWindows[i].Name); diff --git a/imgui_internal.h b/imgui_internal.h index ac36ba61..2f39967a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -562,11 +562,11 @@ struct IMGUI_API ImGuiInputTextState { ImGuiID ID; // widget id owning the text state ImVector TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. - ImVector InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) - ImVector TempBuffer; // temporary buffer for callback and other other operations. size=capacity. + ImVector InitialTextA; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) + ImVector TempBufferA; // temporary buffer for callbacks and other operations. size=capacity. int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. int BufCapacityA; // end-user buffer capacity - float ScrollX; + float ScrollX; // horizontal scrolling/offset ImStb::STB_TexteditState Stb; // state for stb_textedit.h float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) @@ -578,6 +578,7 @@ struct IMGUI_API ImGuiInputTextState void* UserCallbackData; ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } + void ClearFreeMemory() { TextW.clear(); InitialTextA.clear(); TempBufferA.clear(); } void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } bool HasSelection() const { return Stb.select_start != Stb.select_end; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6bbd417a..7673491b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2637,7 +2637,7 @@ bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const c g.ScalarAsInputTextId = g.ActiveId; } if (value_changed) - return DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialText.Data, data_type, data_ptr, NULL); + return DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, NULL); return false; } @@ -2670,7 +2670,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p PushID(label); PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view - value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialText.Data, data_type, data_ptr, format); + value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format); PopItemWidth(); // Step buttons @@ -2701,7 +2701,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p else { if (InputText(label, buf, IM_ARRAYSIZE(buf), flags)) - value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialText.Data, data_type, data_ptr, format); + value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format); } return value_changed; @@ -3045,10 +3045,10 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons ImGuiContext& g = *GImGui; ImGuiInputTextState* edit_state = &g.InputTextState; IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); - IM_ASSERT(Buf == edit_state->TempBuffer.Data); + IM_ASSERT(Buf == edit_state->TempBufferA.Data); int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; - edit_state->TempBuffer.reserve(new_buf_size + 1); - Buf = edit_state->TempBuffer.Data; + edit_state->TempBufferA.reserve(new_buf_size + 1); + Buf = edit_state->TempBufferA.Data; BufSize = edit_state->BufCapacityA = new_buf_size; } @@ -3128,7 +3128,8 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f // Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator. // - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. // - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h -// (FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188) +// (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are +// doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188) bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) { ImGuiWindow* window = GetCurrentWindow(); @@ -3143,7 +3144,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const ImGuiStyle& style = g.Style; const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; - const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; + const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0; const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0; const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0; @@ -3228,17 +3229,18 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Access state even if we don't own it yet. state = &g.InputTextState; - // Start edition // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int buf_len = (int)strlen(buf); + state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. + memcpy(state->InitialTextA.Data, buf, buf_len + 1); + + // Start edition const int prev_len_w = state->CurLenW; - const int init_buf_len = (int)strlen(buf); - state->TextW.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. - state->InitialText.resize(init_buf_len + 1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. - memcpy(state->InitialText.Data, buf, init_buf_len + 1); const char* buf_end = NULL; + state->TextW.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string. state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end); - state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. + state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. state->CursorAnimReset(); // Preserve cursor position and undo/redo stack if we come back to same widget @@ -3286,10 +3288,11 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 bool enter_pressed = false; int backup_current_text_length = 0; + // Process mouse inputs and character inputs if (g.ActiveId == id) { IM_ASSERT(state != NULL); - if (!is_editable && !g.ActiveIdIsJustActivated) + if (is_readonly && !g.ActiveIdIsJustActivated) { // When read-only we always use the live data passed to the function const char* buf_end = NULL; @@ -3348,7 +3351,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Process text input (before we check for Return because using some IME will effectively send a Return?) // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. bool ignore_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper); - if (!ignore_inputs && is_editable && !user_nav_input_start) + if (!ignore_inputs && !is_readonly && !user_nav_input_start) for (int n = 0; n < io.InputQueueCharacters.Size; n++) { // Insert character if they pass filtering @@ -3362,10 +3365,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } } + // Process other shortcuts/key-presses bool cancel_edit = false; if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id) { - // Handle key-presses IM_ASSERT(state != NULL); const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_osx = io.ConfigMacOSXBehaviors; @@ -3376,11 +3379,11 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper; const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper; - const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || state->HasSelection()); + const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && !is_readonly && !is_password && (!is_multiline || state->HasSelection()); const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection()); - const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable; - const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && is_editable && is_undoable); - const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && is_editable && is_undoable; + const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_readonly; + const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && !is_readonly && is_undoable); + const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && !is_readonly && is_undoable; if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } @@ -3388,8 +3391,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) + else if (IsKeyPressedMap(ImGuiKey_Delete) && !is_readonly) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Backspace) && !is_readonly) { if (!state->HasSelection()) { @@ -3407,14 +3410,14 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { enter_pressed = clear_active_id = true; } - else if (is_editable) + else if (!is_readonly) { unsigned int c = '\n'; // Insert new line if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) state->OnKeyPressed((int)c); } } - else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) + else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !is_readonly) { unsigned int c = '\t'; // Insert TAB if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) @@ -3441,9 +3444,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; - state->TempBuffer.resize((ie-ib) * 4 + 1); - ImTextStrToUtf8(state->TempBuffer.Data, state->TempBuffer.Size, state->TextW.Data+ib, state->TextW.Data+ie); - SetClipboardText(state->TempBuffer.Data); + state->TempBufferA.resize((ie-ib) * 4 + 1); + ImTextStrToUtf8(state->TempBufferA.Data, state->TempBufferA.Size, state->TextW.Data+ib, state->TextW.Data+ie); + SetClipboardText(state->TempBufferA.Data); } if (is_cut) { @@ -3482,6 +3485,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } } + // Process callbacks and apply result back to user's buffer. if (g.ActiveId == id) { IM_ASSERT(state != NULL); @@ -3490,10 +3494,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (cancel_edit) { // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents. - if (is_editable && strcmp(buf, state->InitialText.Data) != 0) + if (!is_readonly && strcmp(buf, state->InitialTextA.Data) != 0) { - apply_new_text = state->InitialText.Data; - apply_new_text_length = state->InitialText.Size - 1; + apply_new_text = state->InitialTextA.Data; + apply_new_text_length = state->InitialTextA.Size - 1; } } @@ -3506,10 +3510,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. - if (is_editable) + if (!is_readonly) { - state->TempBuffer.resize(state->TextW.Size * 4 + 1); - ImTextStrToUtf8(state->TempBuffer.Data, state->TempBuffer.Size, state->TextW.Data, NULL); + state->TempBufferA.resize(state->TextW.Size * 4 + 1); + ImTextStrToUtf8(state->TempBufferA.Data, state->TempBufferA.Size, state->TextW.Data, NULL); } // User callback @@ -3547,7 +3551,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 callback_data.UserData = callback_user_data; callback_data.EventKey = event_key; - callback_data.Buf = state->TempBuffer.Data; + callback_data.Buf = state->TempBufferA.Data; callback_data.BufTextLen = state->CurLenA; callback_data.BufSize = state->BufCapacityA; callback_data.BufDirty = false; @@ -3562,7 +3566,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 callback(&callback_data); // Read back what user may have modified - IM_ASSERT(callback_data.Buf == state->TempBuffer.Data); // Invalid to modify those fields + IM_ASSERT(callback_data.Buf == state->TempBufferA.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == state->BufCapacityA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } @@ -3581,9 +3585,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // Will copy result string if modified - if (is_editable && strcmp(state->TempBuffer.Data, buf) != 0) + if (!is_readonly && strcmp(state->TempBufferA.Data, buf) != 0) { - apply_new_text = state->TempBuffer.Data; + apply_new_text = state->TempBufferA.Data; apply_new_text_length = state->CurLenA; } } @@ -3629,7 +3633,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const int buf_display_max_length = 2 * 1024 * 1024; // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. - const char* buf_display = (state != NULL && is_editable) ? state->TempBuffer.Data : buf; + const char* buf_display = (state != NULL && !is_readonly) ? state->TempBufferA.Data : buf; + IM_ASSERT(buf_display); buf = NULL; // Render @@ -3640,20 +3645,18 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size - ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; - ImVec2 text_size(0.f, 0.f); + ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.0f, 0.0f); if (g.ActiveId == id || user_scroll_active) { - // Animate cursor - IM_ASSERT(state != NULL); - state->CursorAnim += io.DeltaTime; - + // Render text (with cursor and selection) // This is going to be messy. We need to: // - Display the text (this alone can be more easily clipped) // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. + IM_ASSERT(state != NULL); const ImWchar* text_begin = state->TextW.Data; ImVec2 cursor_offset, select_start_offset; @@ -3728,14 +3731,14 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 scroll_y = cursor_offset.y - size.y; draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; - render_pos.y = draw_window->DC.CursorPos.y; + draw_pos.y = draw_window->DC.CursorPos.y; } } + const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f); state->CursorFollow = false; - const ImVec2 render_scroll = ImVec2(state->ScrollX, 0.0f); // Draw selection - if (state->Stb.select_start != state->Stb.select_end) + if (state->HasSelection()) { const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end); @@ -3743,7 +3746,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); - ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; + ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll; for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) { if (rect_pos.y > clip_rect.w + g.FontSize) @@ -3765,7 +3768,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (rect.Overlaps(clip_rect)) draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); } - rect_pos.x = render_pos.x - render_scroll.x; + rect_pos.x = draw_pos.x - draw_scroll.x; rect_pos.y += g.FontSize; } } @@ -3773,29 +3776,30 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. const int buf_display_len = state->CurLenA; if (is_multiline || buf_display_len < buf_display_max_length) - draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + buf_display_len, 0.0f, is_multiline ? NULL : &clip_rect); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + buf_display_len, 0.0f, is_multiline ? NULL : &clip_rect); // Draw blinking cursor - bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (g.InputTextState.CursorAnim <= 0.0f) || ImFmod(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; - ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_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); + 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 = 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); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); // 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.) - if (is_editable) - g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); + if (!is_readonly) + g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); } else { - // Render text only + // Render text only (no selection, no cursor) const char* buf_end = NULL; if (is_multiline) text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width else buf_end = buf_display + strlen(buf_display); if (is_multiline || (buf_end - buf_display) < buf_display_max_length) - draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); } if (is_multiline) @@ -3810,7 +3814,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Log as text if (g.LogEnabled && !is_password) - LogRenderedText(&render_pos, buf_display, NULL); + LogRenderedText(&draw_pos, buf_display, NULL); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); From 332f8f2462e8a3d0ab1390ecdfcaea9dd7c02838 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 21 Feb 2019 17:33:57 +0100 Subject: [PATCH 083/566] Internal: InputText: Made clipboard copy/cut use its own temporary buffer (like paste) so we can guarantee that TempBuffer if not altered and can be preserved. Renamed TempBufferA to TextA to celebrate this. --- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 28 +++++++++++++++------------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 2f39967a..5a80fc6e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -561,10 +561,10 @@ struct IMGUI_API ImGuiMenuColumns struct IMGUI_API ImGuiInputTextState { ImGuiID ID; // widget id owning the text state + int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. ImVector TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. + ImVector TextA; // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity. ImVector InitialTextA; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) - ImVector TempBufferA; // temporary buffer for callbacks and other operations. size=capacity. - int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. int BufCapacityA; // end-user buffer capacity float ScrollX; // horizontal scrolling/offset ImStb::STB_TexteditState Stb; // state for stb_textedit.h @@ -578,7 +578,7 @@ struct IMGUI_API ImGuiInputTextState void* UserCallbackData; ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } - void ClearFreeMemory() { TextW.clear(); InitialTextA.clear(); TempBufferA.clear(); } + void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); } void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } bool HasSelection() const { return Stb.select_start != Stb.select_end; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7673491b..87ce703d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3045,10 +3045,10 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons ImGuiContext& g = *GImGui; ImGuiInputTextState* edit_state = &g.InputTextState; IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); - IM_ASSERT(Buf == edit_state->TempBufferA.Data); + IM_ASSERT(Buf == edit_state->TextA.Data); int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; - edit_state->TempBufferA.reserve(new_buf_size + 1); - Buf = edit_state->TempBufferA.Data; + edit_state->TextA.reserve(new_buf_size + 1); + Buf = edit_state->TextA.Data; BufSize = edit_state->BufCapacityA = new_buf_size; } @@ -3444,9 +3444,11 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 { const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; - state->TempBufferA.resize((ie-ib) * 4 + 1); - ImTextStrToUtf8(state->TempBufferA.Data, state->TempBufferA.Size, state->TextW.Data+ib, state->TextW.Data+ie); - SetClipboardText(state->TempBufferA.Data); + const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1; + char* clipboard_data = (char*)MemAlloc(clipboard_data_len * sizeof(char)); + ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie); + SetClipboardText(clipboard_data); + MemFree(clipboard_data); } if (is_cut) { @@ -3512,8 +3514,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. if (!is_readonly) { - state->TempBufferA.resize(state->TextW.Size * 4 + 1); - ImTextStrToUtf8(state->TempBufferA.Data, state->TempBufferA.Size, state->TextW.Data, NULL); + state->TextA.resize(state->TextW.Size * 4 + 1); + ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL); } // User callback @@ -3551,7 +3553,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 callback_data.UserData = callback_user_data; callback_data.EventKey = event_key; - callback_data.Buf = state->TempBufferA.Data; + callback_data.Buf = state->TextA.Data; callback_data.BufTextLen = state->CurLenA; callback_data.BufSize = state->BufCapacityA; callback_data.BufDirty = false; @@ -3566,7 +3568,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 callback(&callback_data); // Read back what user may have modified - IM_ASSERT(callback_data.Buf == state->TempBufferA.Data); // Invalid to modify those fields + IM_ASSERT(callback_data.Buf == state->TextA.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == state->BufCapacityA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } @@ -3585,9 +3587,9 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // Will copy result string if modified - if (!is_readonly && strcmp(state->TempBufferA.Data, buf) != 0) + if (!is_readonly && strcmp(state->TextA.Data, buf) != 0) { - apply_new_text = state->TempBufferA.Data; + apply_new_text = state->TextA.Data; apply_new_text_length = state->CurLenA; } } @@ -3633,7 +3635,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const int buf_display_max_length = 2 * 1024 * 1024; // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. - const char* buf_display = (state != NULL && !is_readonly) ? state->TempBufferA.Data : buf; + const char* buf_display = (state != NULL && !is_readonly) ? state->TextA.Data : buf; IM_ASSERT(buf_display); buf = NULL; From be593f2c163de500aad6a2b3683402c27e7f4259 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 21 Feb 2019 19:45:28 +0100 Subject: [PATCH 084/566] Internal: InputText: refactor the flow to easily decorrelate rendering of selection vs cursor, which would allow us to render selection on inactive items, and generally makes the code clearer. + Some renaming. --- imgui_widgets.cpp | 80 ++++++++++++++++++++++++++++------------------- 1 file changed, 48 insertions(+), 32 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 87ce703d..a6c7e34e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3143,6 +3143,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; + const bool RENDER_SELECTION_WHEN_INACTIVE = true; const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0; const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; @@ -3220,8 +3221,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y); bool clear_active_id = false; - bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline); + if (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start) { if (g.ActiveId != id) @@ -3649,7 +3650,12 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.0f, 0.0f); - if (g.ActiveId == id || user_scroll_active) + + // We currently only render selection when the widget is active or while scrolling. + // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. + const bool render_cursor = (g.ActiveId == id) || user_scroll_active; + const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); + if (render_cursor || render_selection) { // Render text (with cursor and selection) // This is going to be messy. We need to: @@ -3663,16 +3669,20 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 ImVec2 cursor_offset, select_start_offset; { - // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. - const ImWchar* searches_input_ptr[2]; - searches_input_ptr[0] = text_begin + state->Stb.cursor; - searches_input_ptr[1] = NULL; - int searches_remaining = 1; - int searches_result_line_number[2] = { -1, -999 }; - if (state->Stb.select_start != state->Stb.select_end) + // Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions. + const ImWchar* searches_input_ptr[2] = { NULL, NULL }; + int searches_result_line_no[2] = { -1000, -1000 }; + int searches_remaining = 0; + if (render_cursor) + { + searches_input_ptr[0] = text_begin + state->Stb.cursor; + searches_result_line_no[0] = -1; + searches_remaining++; + } + if (render_selection) { searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); - searches_result_line_number[1] = -1; + searches_result_line_no[1] = -1; searches_remaining++; } @@ -3685,20 +3695,22 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (*s == '\n') { line_count++; - if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } - if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; } } line_count++; - if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; - if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; + if (searches_result_line_no[0] == -1) + searches_result_line_no[0] = line_count; + if (searches_result_line_no[1] == -1) + searches_result_line_no[1] = line_count; // Calculate 2d position by finding the beginning of the line and measuring distance cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; - cursor_offset.y = searches_result_line_number[0] * g.FontSize; - if (searches_result_line_number[1] >= 0) + cursor_offset.y = searches_result_line_no[0] * g.FontSize; + if (searches_result_line_no[1] >= 0) { select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; - select_start_offset.y = searches_result_line_number[1] * g.FontSize; + select_start_offset.y = searches_result_line_no[1] * g.FontSize; } // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) @@ -3707,7 +3719,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // Scroll - if (state->CursorFollow) + if (render_cursor && state->CursorFollow) { // Horizontal scroll in chunks of quarter width if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) @@ -3735,19 +3747,20 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 draw_window->Scroll.y = scroll_y; draw_pos.y = draw_window->DC.CursorPos.y; } + + state->CursorFollow = false; } - const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f); - state->CursorFollow = false; // Draw selection - if (state->HasSelection()) + const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f); + if (render_selection) { const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end); + ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; - ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll; for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) { @@ -3781,16 +3794,19 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + buf_display_len, 0.0f, is_multiline ? NULL : &clip_rect); // Draw blinking cursor - 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 = 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); - if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) - draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); - - // 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.) - if (!is_readonly) - g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + if (render_cursor) + { + 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 = 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); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + + // 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.) + if (!is_readonly) + g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); + } } else { From f988618ebe9cfb216268d659e6b250fc377647c6 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 21 Feb 2019 23:00:47 +0100 Subject: [PATCH 085/566] Internal: InputText: Tweaks (including a large indentation change, compare ignoring space) to make next commit more digestible. --- imgui_widgets.cpp | 108 +++++++++++++++++++++++----------------------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a6c7e34e..cd059cc3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3223,50 +3223,51 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 bool clear_active_id = false; bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline); - if (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start) + const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start); + if (init_make_active && g.ActiveId != id) { - if (g.ActiveId != id) - { - // Access state even if we don't own it yet. - state = &g.InputTextState; - - // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) - // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) - const int buf_len = (int)strlen(buf); - state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. - memcpy(state->InitialTextA.Data, buf, buf_len + 1); + // Access state even if we don't own it yet. + state = &g.InputTextState; + state->CursorAnimReset(); - // Start edition - const int prev_len_w = state->CurLenW; - const char* buf_end = NULL; - state->TextW.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string. - state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end); - state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. - state->CursorAnimReset(); + // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) + // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int buf_len = (int)strlen(buf); + state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. + memcpy(state->InitialTextA.Data, buf, buf_len + 1); - // Preserve cursor position and undo/redo stack if we come back to same widget - // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). - const bool recycle_state = (state->ID == id) && (prev_len_w == state->CurLenW); - if (recycle_state) - { - // Recycle existing cursor/selection/undo stack but clamp position - // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. - state->CursorClamp(); - } - else - { - state->ID = id; - state->ScrollX = 0.0f; - stb_textedit_initialize_state(&state->Stb, !is_multiline); - if (!is_multiline && focus_requested_by_code) - select_all = true; - } - if (flags & ImGuiInputTextFlags_AlwaysInsertMode) - state->Stb.insert_mode = 1; - if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) + // Start edition + const int prev_len_w = state->CurLenW; + const char* buf_end = NULL; + state->TextW.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string. + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. + + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). + const bool recycle_state = (state->ID == id) && (prev_len_w == state->CurLenW); + if (recycle_state) + { + // Recycle existing cursor/selection/undo stack but clamp position + // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. + state->CursorClamp(); + } + else + { + state->ID = id; + state->ScrollX = 0.0f; + stb_textedit_initialize_state(&state->Stb, !is_multiline); + if (!is_multiline && focus_requested_by_code) select_all = true; } + if (flags & ImGuiInputTextFlags_AlwaysInsertMode) + state->Stb.insert_mode = 1; + if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) + select_all = true; + } + if (init_make_active) + { IM_ASSERT(state && state->ID == id); SetActiveID(id, window); SetFocusID(id, window); @@ -3275,11 +3276,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory)) g.ActiveIdAllowNavDirFlags = ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down)); } - else if (io.MouseClicked[0]) - { - // Release focus when we click outside + + // Release focus when we click outside + if (!init_make_active && io.MouseClicked[0]) clear_active_id = true; - } // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped) if (g.ActiveId == id && state == NULL) @@ -3630,17 +3630,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (clear_active_id && g.ActiveId == id) ClearActiveID(); - // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line - // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. - // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. - const int buf_display_max_length = 2 * 1024 * 1024; - - // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. - const char* buf_display = (state != NULL && !is_readonly) ? state->TextA.Data : buf; - IM_ASSERT(buf_display); - buf = NULL; - - // Render + // Render frame if (!is_multiline) { RenderNavHighlight(frame_bb, id); @@ -3651,7 +3641,17 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.0f, 0.0f); - // We currently only render selection when the widget is active or while scrolling. + // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line + // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. + // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. + const int buf_display_max_length = 2 * 1024 * 1024; + + // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. + const char* buf_display = (state != NULL && !is_readonly) ? state->TextA.Data : buf; + IM_ASSERT(buf_display); + buf = NULL; + + // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. const bool render_cursor = (g.ActiveId == id) || user_scroll_active; const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); From 0f83145aa870a13a416a04a715a1e98bf4f8bbfb Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 22 Feb 2019 12:24:27 +0100 Subject: [PATCH 086/566] TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) Added ImPool::Contains() helper. --- docs/CHANGELOG.txt | 1 + imgui_internal.h | 23 +++++++++++++++++------ imgui_widgets.cpp | 41 ++++++++++++++++++++++++++++++----------- 3 files changed, 48 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3634bf2c..31305f18 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,7 @@ Other Changes: meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) - InputText: Fixed an edge case crash that would happen if another widget sharing the same ID is being swapped with an InputText that has yet to be activated. +- TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) diff --git a/imgui_internal.h b/imgui_internal.h index 5a80fc6e..cc355e95 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -275,7 +275,8 @@ struct IMGUI_API ImPool T* GetByIndex(ImPoolIdx n) { return &Data[n]; } ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Data.Data && p < Data.Data + Data.Size); return (ImPoolIdx)(p - Data.Data); } T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Data[*p_idx]; *p_idx = FreeIdx; return Add(); } - void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Data[idx].~T(); } Map.Clear(); Data.clear(); FreeIdx = 0; } + bool Contains(const T* p) const { return (p >= Data.Data && p < Data.Data + Data.Size); } + void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Data[idx].~T(); } Map.Clear(); Data.clear(); FreeIdx = 0; } T* Add() { int idx = FreeIdx; if (idx == Data.Size) { Data.resize(Data.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Data[idx]; } IM_PLACEMENT_NEW(&Data[idx]) T(); return &Data[idx]; } void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); } void Remove(ImGuiID key, ImPoolIdx idx) { Data[idx].~T(); *(int*)&Data[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); } @@ -749,8 +750,17 @@ struct ImGuiNextWindowData struct ImGuiTabBarSortItem { - int Index; - float Width; + int Index; + float Width; +}; + +struct ImGuiTabBarRef +{ + ImGuiTabBar* Ptr; // Either field can be set, not both. Dock node tab bars are loose while BeginTabBar() ones are in a pool. + int IndexInMainPool; + + ImGuiTabBarRef(ImGuiTabBar* ptr) { Ptr = ptr; IndexInMainPool = -1; } + ImGuiTabBarRef(int index_in_main_pool) { Ptr = NULL; IndexInMainPool = index_in_main_pool; } }; //----------------------------------------------------------------------------- @@ -883,8 +893,9 @@ struct ImGuiContext unsigned char DragDropPayloadBufLocal[8]; // Local buffer for small payloads // Tab bars - ImPool TabBars; - ImVector CurrentTabBar; + ImPool TabBars; + ImGuiTabBar* CurrentTabBar; + ImVector CurrentTabBarStack; ImVector TabSortByWidthBuffer; // Widget state @@ -1246,7 +1257,7 @@ struct ImGuiItemHoveredDataBackup enum ImGuiTabBarFlagsPrivate_ { - ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node + ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] ImGuiTabBarFlags_IsFocused = 1 << 21, ImGuiTabBarFlags_SaveSettings = 1 << 22 // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cd059cc3..aaec4cb3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5905,6 +5905,20 @@ static int IMGUI_CDECL TabBarSortItemComparer(const void* lhs, const void* rhs) return (b->Index - a->Index); } +static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiTabBarRef& ref) +{ + ImGuiContext& g = *GImGui; + return ref.Ptr ? ref.Ptr : g.TabBars.GetByIndex(ref.IndexInMainPool); +} + +static ImGuiTabBarRef GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) +{ + ImGuiContext& g = *GImGui; + if (g.TabBars.Contains(tab_bar)) + return ImGuiTabBarRef(g.TabBars.GetIndex(tab_bar)); + return ImGuiTabBarRef(tab_bar); +} + bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) { ImGuiContext& g = *GImGui; @@ -5929,7 +5943,10 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG if ((flags & ImGuiTabBarFlags_DockNode) == 0) window->IDStack.push_back(tab_bar->ID); - g.CurrentTabBar.push_back(tab_bar); + // Add to stack + g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar)); + g.CurrentTabBar = tab_bar; + if (tab_bar->CurrFrameVisible == g.FrameCount) { //IMGUI_DEBUG_LOG("BeginTabBarEx already called this frame\n", g.FrameCount); @@ -5975,8 +5992,8 @@ void ImGui::EndTabBar() if (window->SkipItems) return; - IM_ASSERT(!g.CurrentTabBar.empty()); // Mismatched BeginTabBar/EndTabBar - ImGuiTabBar* tab_bar = g.CurrentTabBar.back(); + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT(tab_bar != NULL && "Mismatched BeginTabBar()/EndTabBar()!"); if (tab_bar->WantLayout) TabBarLayout(tab_bar); @@ -5989,7 +6006,9 @@ void ImGui::EndTabBar() if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) PopID(); - g.CurrentTabBar.pop_back(); + + g.CurrentTabBarStack.pop_back(); + g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back()); } // This is called only once a frame before by the first call to ItemTab() @@ -6356,8 +6375,8 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f if (g.CurrentWindow->SkipItems) return false; - IM_ASSERT(g.CurrentTabBar.Size > 0 && "Needs to be called between BeginTabBar() and EndTabBar()!"); - ImGuiTabBar* tab_bar = g.CurrentTabBar.back(); + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT(tab_bar && "Needs to be called between BeginTabBar() and EndTabBar()!"); bool ret = TabItemEx(tab_bar, label, p_open, flags); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) { @@ -6373,9 +6392,9 @@ void ImGui::EndTabItem() if (g.CurrentWindow->SkipItems) return; - IM_ASSERT(g.CurrentTabBar.Size > 0 && "Needs to be called between BeginTabBar() and EndTabBar()!"); - ImGuiTabBar* tab_bar = g.CurrentTabBar.back(); - IM_ASSERT(tab_bar->LastTabItemIdx >= 0 && "Needs to be called between BeginTabItem() and EndTabItem()"); + ImGuiTabBar* tab_bar = g.CurrentTabBar; + IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!"); + IM_ASSERT(tab_bar->LastTabItemIdx >= 0); ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) g.CurrentWindow->IDStack.pop_back(); @@ -6575,10 +6594,10 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, void ImGui::SetTabItemClosed(const char* label) { ImGuiContext& g = *GImGui; - bool is_within_manual_tab_bar = (g.CurrentTabBar.Size > 0) && !(g.CurrentTabBar.back()->Flags & ImGuiTabBarFlags_DockNode); + bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode); if (is_within_manual_tab_bar) { - ImGuiTabBar* tab_bar = g.CurrentTabBar.back(); + ImGuiTabBar* tab_bar = g.CurrentTabBar; IM_ASSERT(tab_bar->WantLayout); // Needs to be called AFTER BeginTabBar() and BEFORE the first call to BeginTabItem() ImGuiID tab_id = TabBarCalcTabID(tab_bar, label); TabBarRemoveTab(tab_bar, tab_id); From 9da48c16c5eeb8ea98e89951c83fab0f9d2b037b Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 22 Feb 2019 12:27:41 +0100 Subject: [PATCH 087/566] TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 31305f18..73a59691 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ Other Changes: - InputText: Fixed an edge case crash that would happen if another widget sharing the same ID is being swapped with an InputText that has yet to be activated. - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) +- TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to + hard crashes any more, facilitating integration with scripting languages. (#1651) - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index aaec4cb3..f49fa46d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5993,7 +5993,11 @@ void ImGui::EndTabBar() return; ImGuiTabBar* tab_bar = g.CurrentTabBar; - IM_ASSERT(tab_bar != NULL && "Mismatched BeginTabBar()/EndTabBar()!"); + if (tab_bar == NULL) + { + IM_ASSERT(tab_bar != NULL && "Mismatched BeginTabBar()/EndTabBar()!"); + return; // FIXME-ERRORHANDLING + } if (tab_bar->WantLayout) TabBarLayout(tab_bar); @@ -6376,7 +6380,11 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f return false; ImGuiTabBar* tab_bar = g.CurrentTabBar; - IM_ASSERT(tab_bar && "Needs to be called between BeginTabBar() and EndTabBar()!"); + if (tab_bar == NULL) + { + IM_ASSERT(tab_bar && "Needs to be called between BeginTabBar() and EndTabBar()!"); + return false; // FIXME-ERRORHANDLING + } bool ret = TabItemEx(tab_bar, label, p_open, flags); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) { @@ -6393,7 +6401,11 @@ void ImGui::EndTabItem() return; ImGuiTabBar* tab_bar = g.CurrentTabBar; - IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!"); + if (tab_bar == NULL) + { + IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!"); + return; + } IM_ASSERT(tab_bar->LastTabItemIdx >= 0); ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) From 3eba84005372734297700212cbf31c8b400bef3d Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 23 Feb 2019 14:49:36 +0100 Subject: [PATCH 088/566] Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigation to the menu layer. (follow and extend on e.g #369, #370) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 73a59691..7c415766 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,7 @@ HOW TO UPDATE? Other Changes: +- Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigation to the menu layer. - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) diff --git a/imgui.cpp b/imgui.cpp index ddcd10c2..ce7494d9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7591,9 +7591,12 @@ static void ImGui::NavUpdate() NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_); NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ ); NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ ); - if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; - if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; - if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; + if (g.IO.KeyCtrl) + g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; + if (g.IO.KeyShift) + g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; + if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu. + g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; #undef NAV_MAP_KEY } memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration)); From 2cd7de56666531d729e4dbe06af3e3c0a2e5aaf9 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 23 Feb 2019 15:24:01 +0100 Subject: [PATCH 089/566] Internal: Log/Capture: Rework to add an internal LogToBuffer() function which is useful for writing automated tests. Clarified logging state by adding an enum. --- imgui.cpp | 68 +++++++++++++++++++++++++++++++++--------------- imgui_internal.h | 16 +++++++++++- 2 files changed, 62 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ce7494d9..22696b17 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3615,7 +3615,7 @@ void ImGui::Shutdown(ImGuiContext* context) fclose(g.LogFile); g.LogFile = NULL; } - g.LogClipboard.clear(); + g.LogBuffer.clear(); g.Initialized = false; } @@ -8786,7 +8786,7 @@ void ImGui::LogText(const char* fmt, ...) if (g.LogFile) vfprintf(g.LogFile, fmt, args); else - g.LogClipboard.appendfv(fmt, args); + g.LogBuffer.appendfv(fmt, args); va_end(args); } @@ -8830,7 +8830,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* } } -// Start logging ImGui output to TTY +// Start logging/capturing text output to TTY void ImGui::LogToTTY(int max_depth) { ImGuiContext& g = *GImGui; @@ -8841,12 +8841,13 @@ void ImGui::LogToTTY(int max_depth) IM_ASSERT(g.LogFile == NULL); g.LogFile = stdout; g.LogEnabled = true; + g.LogType = ImGuiLogType_TTY; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } -// Start logging ImGui output to given file +// Start logging/capturing text output to given file void ImGui::LogToFile(int max_depth, const char* filename) { ImGuiContext& g = *GImGui; @@ -8855,26 +8856,25 @@ void ImGui::LogToFile(int max_depth, const char* filename) ImGuiWindow* window = g.CurrentWindow; if (!filename) - { filename = g.IO.LogFilename; - if (!filename) - return; - } + if (!filename || !filename[0]) + return; IM_ASSERT(g.LogFile == NULL); - g.LogFile = ImFileOpen(filename, "ab"); + g.LogFile = ImFileOpen(filename, "ab"); // FIXME: Why not logging in text mode? Then we don't need to bother the user with IM_NEWLINE.. if (!g.LogFile) { IM_ASSERT(0); return; } g.LogEnabled = true; + g.LogType = ImGuiLogType_File; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } -// Start logging ImGui output to clipboard +// Start logging/capturing text output to clipboard void ImGui::LogToClipboard(int max_depth) { ImGuiContext& g = *GImGui; @@ -8883,8 +8883,27 @@ void ImGui::LogToClipboard(int max_depth) ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.LogFile == NULL); + IM_ASSERT(g.LogBuffer.empty()); + g.LogEnabled = true; + g.LogType = ImGuiLogType_Clipboard; g.LogFile = NULL; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +void ImGui::LogToBuffer(int max_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = g.CurrentWindow; + + IM_ASSERT(g.LogFile == NULL); + IM_ASSERT(g.LogBuffer.empty()); g.LogEnabled = true; + g.LogType = ImGuiLogType_Clipboard; + g.LogFile = NULL; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; @@ -8897,23 +8916,30 @@ void ImGui::LogFinish() return; LogText(IM_NEWLINE); - if (g.LogFile != NULL) - { - if (g.LogFile == stdout) - fflush(g.LogFile); - else - fclose(g.LogFile); - g.LogFile = NULL; - } - if (g.LogClipboard.size() > 1) + switch (g.LogType) { - SetClipboardText(g.LogClipboard.begin()); - g.LogClipboard.clear(); + case ImGuiLogType_TTY: + fflush(g.LogFile); + break; + case ImGuiLogType_File: + fclose(g.LogFile); + break; + case ImGuiLogType_Buffer: + break; + case ImGuiLogType_Clipboard: + if (!g.LogBuffer.empty()) + SetClipboardText(g.LogBuffer.begin()); + break; } + g.LogEnabled = false; + g.LogType = ImGuiLogType_None; + g.LogFile = NULL; + g.LogBuffer.clear(); } // Helper to display logging buttons +// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) void ImGui::LogButtons() { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index cc355e95..c79aeabc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -384,6 +384,15 @@ enum ImGuiLayoutType_ ImGuiLayoutType_Vertical = 1 }; +enum ImGuiLogType +{ + ImGuiLogType_None = 0, + ImGuiLogType_TTY, + ImGuiLogType_File, + ImGuiLogType_Buffer, + ImGuiLogType_Clipboard +}; + // X/Y enums are fixed to 0/1 so they may be used to index ImVec2 enum ImGuiAxis { @@ -928,8 +937,9 @@ struct ImGuiContext // Logging bool LogEnabled; + ImGuiLogType LogType; FILE* LogFile; // If != NULL log to stdout/ file - ImGuiTextBuffer LogClipboard; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. int LogStartDepth; int LogAutoExpandMaxDepth; @@ -1041,6 +1051,7 @@ struct ImGuiContext SettingsDirtyTimer = 0.0f; LogEnabled = false; + LogType = ImGuiLogType_None; LogFile = NULL; LogStartDepth = 0; LogAutoExpandMaxDepth = 2; @@ -1396,6 +1407,9 @@ namespace ImGui IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); + // Logging/Capture + IMGUI_API void LogToBuffer(int max_depth = -1); // Start logging to internal buffer + // Popups, Modals, Tooltips IMGUI_API void OpenPopupEx(ImGuiID id); IMGUI_API void ClosePopupToLevel(int remaining, bool apply_focus_to_window_under); From cd67d4d3c18f1f5c0b94a6a09ed35b748e5a2cc4 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 23 Feb 2019 15:39:18 +0100 Subject: [PATCH 090/566] Log/Capture: Fixed LogXXX functions 'auto_open_depth' parameter being treated as an absolute tree depth instead of a relative one. Fixed CollapsingHeader trailing ascii representation being "#" instead of "##". Minor tidying up the of code. --- docs/CHANGELOG.txt | 3 +++ docs/TODO.txt | 5 +++-- imgui.cpp | 42 +++++++++++++++++++----------------------- imgui.h | 6 +++--- imgui_internal.h | 13 +++++++------ imgui_widgets.cpp | 4 ++-- 6 files changed, 37 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7c415766..eba02739 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,9 @@ Other Changes: - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) +- Log/Capture: Fixed LogXXX functions 'auto_open_depth' parameter being treated as an absolute + tree depth instead of a relative one. +- Log/Capture: Fixed CollapsingHeader trailing ascii representation being "#" instead of "##". - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) diff --git a/docs/TODO.txt b/docs/TODO.txt index 01b54716..d0fa9755 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -217,11 +217,12 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - style: gradients fill (#1223) ~ 2 bg colors for each fill? tricky with rounded shapes and using textures for corners. - style editor: color child window height expressed in multiple of line height. - - log: LogButtons() options for specifying depth and/or hiding depth slider - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. - + - log: obsolete LogButtons() all together. + - log: LogButtons() options for specifying depth and/or hiding depth slider + - filters: set a current filter that tree node can automatically query to hide themselves - filters: handle wild-cards (with implicit leading/trailing *), reg-exprs - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb) diff --git a/imgui.cpp b/imgui.cpp index 22696b17..d6fbc1ce 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8805,9 +8805,9 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* window->DC.LogLinePosY = ref_pos->y; const char* text_remaining = text; - if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth - g.LogStartDepth = window->DC.TreeDepth; - const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); + if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth + g.LogDepthRef = window->DC.TreeDepth; + const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. @@ -8831,7 +8831,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* } // Start logging/capturing text output to TTY -void ImGui::LogToTTY(int max_depth) +void ImGui::LogToTTY(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) @@ -8842,13 +8842,12 @@ void ImGui::LogToTTY(int max_depth) g.LogFile = stdout; g.LogEnabled = true; g.LogType = ImGuiLogType_TTY; - g.LogStartDepth = window->DC.TreeDepth; - if (max_depth >= 0) - g.LogAutoExpandMaxDepth = max_depth; + g.LogDepthRef = window->DC.TreeDepth; + g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); } // Start logging/capturing text output to given file -void ImGui::LogToFile(int max_depth, const char* filename) +void ImGui::LogToFile(int auto_open_depth, const char* filename) { ImGuiContext& g = *GImGui; if (g.LogEnabled) @@ -8869,13 +8868,12 @@ void ImGui::LogToFile(int max_depth, const char* filename) } g.LogEnabled = true; g.LogType = ImGuiLogType_File; - g.LogStartDepth = window->DC.TreeDepth; - if (max_depth >= 0) - g.LogAutoExpandMaxDepth = max_depth; + g.LogDepthRef = window->DC.TreeDepth; + g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); } // Start logging/capturing text output to clipboard -void ImGui::LogToClipboard(int max_depth) +void ImGui::LogToClipboard(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) @@ -8887,12 +8885,11 @@ void ImGui::LogToClipboard(int max_depth) g.LogEnabled = true; g.LogType = ImGuiLogType_Clipboard; g.LogFile = NULL; - g.LogStartDepth = window->DC.TreeDepth; - if (max_depth >= 0) - g.LogAutoExpandMaxDepth = max_depth; + g.LogDepthRef = window->DC.TreeDepth; + g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); } -void ImGui::LogToBuffer(int max_depth) +void ImGui::LogToBuffer(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) @@ -8904,9 +8901,8 @@ void ImGui::LogToBuffer(int max_depth) g.LogEnabled = true; g.LogType = ImGuiLogType_Clipboard; g.LogFile = NULL; - g.LogStartDepth = window->DC.TreeDepth; - if (max_depth >= 0) - g.LogAutoExpandMaxDepth = max_depth; + g.LogDepthRef = window->DC.TreeDepth; + g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); } void ImGui::LogFinish() @@ -8950,18 +8946,18 @@ void ImGui::LogButtons() const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); PushItemWidth(80.0f); PushAllowKeyboardFocus(false); - SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); + SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); PopAllowKeyboardFocus(); PopItemWidth(); PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) - LogToTTY(g.LogAutoExpandMaxDepth); + LogToTTY(); if (log_to_file) - LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); + LogToFile(); if (log_to_clipboard) - LogToClipboard(g.LogAutoExpandMaxDepth); + LogToClipboard(); } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index e109f3a4..dd1e67dc 100644 --- a/imgui.h +++ b/imgui.h @@ -572,9 +572,9 @@ namespace ImGui // Logging/Capture // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. - IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty (stdout) - IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file - IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard + IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout) + IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard IMGUI_API void LogFinish(); // stop logging (close file, etc.) IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) diff --git a/imgui_internal.h b/imgui_internal.h index c79aeabc..96827b70 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -939,9 +939,10 @@ struct ImGuiContext bool LogEnabled; ImGuiLogType LogType; FILE* LogFile; // If != NULL log to stdout/ file - ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. - int LogStartDepth; - int LogAutoExpandMaxDepth; + ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + int LogDepthRef; + int LogDepthToExpand; + int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. // Misc float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds. @@ -1053,8 +1054,8 @@ struct ImGuiContext LogEnabled = false; LogType = ImGuiLogType_None; LogFile = NULL; - LogStartDepth = 0; - LogAutoExpandMaxDepth = 2; + LogDepthRef = 0; + LogDepthToExpand = LogDepthToExpandDefault = 2; memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); FramerateSecPerFrameIdx = 0; @@ -1408,7 +1409,7 @@ namespace ImGui IMGUI_API void PopItemFlag(); // Logging/Capture - IMGUI_API void LogToBuffer(int max_depth = -1); // Start logging to internal buffer + IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging to internal buffer // Popups, Modals, Tooltips IMGUI_API void OpenPopupEx(ImGuiID id); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f49fa46d..26eb5c24 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4795,7 +4795,7 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). // NB- If we are above max depth we still allow manually opened nodes to be logged. - if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand) is_open = true; return is_open; @@ -4922,7 +4922,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const char log_suffix[] = "##"; LogRenderedText(&text_pos, log_prefix, log_prefix+3); RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); - LogRenderedText(&text_pos, log_suffix+1, log_suffix+3); + LogRenderedText(&text_pos, log_suffix, log_suffix+2); } else { From 9558e327d2c68c27b7aac4384c892ef4f316a5c1 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 23 Feb 2019 16:22:55 +0100 Subject: [PATCH 091/566] Log/Capture: Fixed extraneous leading carriage return. Fixed an issue when empty string on a new line would not emit a carriage return. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 90 ++++++++++++++++++++++++---------------------- imgui_internal.h | 10 +++--- 3 files changed, 55 insertions(+), 47 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index eba02739..9ef37fab 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,8 @@ Other Changes: - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) +- Log/Capture: Fixed extraneous leading carriage return. +- Log/Capture: Fixed an issue when empty string on a new line would not emit a carriage return. - Log/Capture: Fixed LogXXX functions 'auto_open_depth' parameter being treated as an absolute tree depth instead of a relative one. - Log/Capture: Fixed CollapsingHeader trailing ascii representation being "#" instead of "##". diff --git a/imgui.cpp b/imgui.cpp index d6fbc1ce..830e14a7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5325,7 +5325,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; window->DC.MenuBarAppending = false; - window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; window->DC.ChildWindows.resize(0); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; @@ -6550,7 +6549,6 @@ void ImGui::BeginGroup() group_data.BackupGroupOffset = window->DC.GroupOffset; group_data.BackupCurrentLineSize = window->DC.CurrentLineSize; group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; - group_data.BackupLogLinePosY = window->DC.LogLinePosY; group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; group_data.AdvanceCursor = true; @@ -6559,14 +6557,15 @@ void ImGui::BeginGroup() window->DC.Indent = window->DC.GroupOffset; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); - window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return + if (g.LogEnabled) + g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return } void ImGui::EndGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls + IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); @@ -6579,7 +6578,8 @@ void ImGui::EndGroup() window->DC.GroupOffset = group_data.BackupGroupOffset; window->DC.CurrentLineSize = group_data.BackupCurrentLineSize; window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; - window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return + if (g.LogEnabled) + g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return if (group_data.AdvanceCursor) { @@ -8800,9 +8800,11 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* if (!text_end) text_end = FindRenderedTextEnd(text, text_end); - const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1); + const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1); if (ref_pos) - window->DC.LogLinePosY = ref_pos->y; + g.LogLinePosY = ref_pos->y; + if (log_new_line) + g.LogLineFirstItem = true; const char* text_remaining = text; if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth @@ -8811,6 +8813,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. + // We don't add a trailing \n to allow a subsequent item on the same line to be captured. const char* line_start = text_remaining; const char* line_end = ImStreolRange(line_start, text_end); const bool is_first_line = (line_start == text); @@ -8819,9 +8822,18 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* { const int char_count = (int)(line_end - line_start); if (log_new_line || !is_first_line) - LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, line_start); - else + LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start); + else if (g.LogLineFirstItem) + LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start); + else LogText(" %.*s", char_count, line_start); + g.LogLineFirstItem = false; + } + else if (log_new_line) + { + // An empty "" string at a different Y position should output a carriage return. + LogText(IM_NEWLINE); + break; } if (is_last_line) @@ -8830,20 +8842,29 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* } } -// Start logging/capturing text output to TTY -void ImGui::LogToTTY(int auto_open_depth) +// Start logging/capturing text output +void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth) { ImGuiContext& g = *GImGui; - if (g.LogEnabled) - return; ImGuiWindow* window = g.CurrentWindow; - + IM_ASSERT(g.LogEnabled == false); IM_ASSERT(g.LogFile == NULL); - g.LogFile = stdout; + IM_ASSERT(g.LogBuffer.empty()); g.LogEnabled = true; - g.LogType = ImGuiLogType_TTY; + g.LogType = type; g.LogDepthRef = window->DC.TreeDepth; g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); + g.LogLinePosY = FLT_MAX; + g.LogLineFirstItem = true; +} + +void ImGui::LogToTTY(int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogType_TTY, auto_open_depth); + g.LogFile = stdout; } // Start logging/capturing text output to given file @@ -8852,24 +8873,23 @@ void ImGui::LogToFile(int auto_open_depth, const char* filename) ImGuiContext& g = *GImGui; if (g.LogEnabled) return; - ImGuiWindow* window = g.CurrentWindow; + // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still + // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. + // By opening the file in binary mode "ab" we have consistent output everywhere. if (!filename) filename = g.IO.LogFilename; if (!filename || !filename[0]) return; - - IM_ASSERT(g.LogFile == NULL); - g.LogFile = ImFileOpen(filename, "ab"); // FIXME: Why not logging in text mode? Then we don't need to bother the user with IM_NEWLINE.. - if (!g.LogFile) + FILE* f = ImFileOpen(filename, "ab"); + if (f == NULL) { IM_ASSERT(0); return; } - g.LogEnabled = true; - g.LogType = ImGuiLogType_File; - g.LogDepthRef = window->DC.TreeDepth; - g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); + + LogBegin(ImGuiLogType_File, auto_open_depth); + g.LogFile = f; } // Start logging/capturing text output to clipboard @@ -8878,15 +8898,7 @@ void ImGui::LogToClipboard(int auto_open_depth) ImGuiContext& g = *GImGui; if (g.LogEnabled) return; - ImGuiWindow* window = g.CurrentWindow; - - IM_ASSERT(g.LogFile == NULL); - IM_ASSERT(g.LogBuffer.empty()); - g.LogEnabled = true; - g.LogType = ImGuiLogType_Clipboard; - g.LogFile = NULL; - g.LogDepthRef = window->DC.TreeDepth; - g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); + LogBegin(ImGuiLogType_Clipboard, auto_open_depth); } void ImGui::LogToBuffer(int auto_open_depth) @@ -8894,15 +8906,7 @@ void ImGui::LogToBuffer(int auto_open_depth) ImGuiContext& g = *GImGui; if (g.LogEnabled) return; - ImGuiWindow* window = g.CurrentWindow; - - IM_ASSERT(g.LogFile == NULL); - IM_ASSERT(g.LogBuffer.empty()); - g.LogEnabled = true; - g.LogType = ImGuiLogType_Clipboard; - g.LogFile = NULL; - g.LogDepthRef = window->DC.TreeDepth; - g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); + LogBegin(ImGuiLogType_Buffer, auto_open_depth); } void ImGui::LogFinish() diff --git a/imgui_internal.h b/imgui_internal.h index 96827b70..fa172834 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -547,7 +547,6 @@ struct ImGuiGroupData ImVec1 BackupGroupOffset; ImVec2 BackupCurrentLineSize; float BackupCurrentLineTextBaseOffset; - float BackupLogLinePosY; ImGuiID BackupActiveIdIsAlive; bool BackupActiveIdPreviousFrameIsAlive; bool AdvanceCursor; @@ -940,6 +939,8 @@ struct ImGuiContext ImGuiLogType LogType; FILE* LogFile; // If != NULL log to stdout/ file ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + float LogLinePosY; + bool LogLineFirstItem; int LogDepthRef; int LogDepthToExpand; int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. @@ -1054,6 +1055,8 @@ struct ImGuiContext LogEnabled = false; LogType = ImGuiLogType_None; LogFile = NULL; + LogLinePosY = FLT_MAX; + LogLineFirstItem = false; LogDepthRef = 0; LogDepthToExpand = LogDepthToExpandDefault = 2; @@ -1081,7 +1084,6 @@ struct IMGUI_API ImGuiWindowTempData float CurrentLineTextBaseOffset; ImVec2 PrevLineSize; float PrevLineTextBaseOffset; - float LogLinePosY; int TreeDepth; ImU32 TreeDepthMayJumpToParentOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31 ImGuiID LastItemId; @@ -1121,7 +1123,6 @@ struct IMGUI_API ImGuiWindowTempData CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); CurrentLineSize = PrevLineSize = ImVec2(0.0f, 0.0f); CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; - LogLinePosY = -1.0f; TreeDepth = 0; TreeDepthMayJumpToParentOnPop = 0x00; LastItemId = 0; @@ -1409,7 +1410,8 @@ namespace ImGui IMGUI_API void PopItemFlag(); // Logging/Capture - IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging to internal buffer + IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. + IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer // Popups, Modals, Tooltips IMGUI_API void OpenPopupEx(ImGuiID id); From 6cbf4b81210204736a844a9519b0fde72df35cad Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 23 Feb 2019 17:00:59 +0100 Subject: [PATCH 092/566] Fixed uninitialized variable (leading to asserts in the docking branch). (#2376, #2371) --- imgui_internal.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui_internal.h b/imgui_internal.h index fa172834..a76c386a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1037,6 +1037,8 @@ struct ImGuiContext DragDropAcceptFrameCount = -1; memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal)); + CurrentTabBar = NULL; + ScalarAsInputTextId = 0; ColorEditOptions = ImGuiColorEditFlags__OptionsDefault; DragCurrentAccumDirty = false; From 6f80179a1d45753e7065ea7f79360e8e30e5d115 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 23 Feb 2019 17:04:54 +0100 Subject: [PATCH 093/566] InputText: Fixed deactivated but-last-active InputText instance holding on displaying the last active version of the text and not reflecting change in the source. Fix/amend 2e9a175. [+test] --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 26eb5c24..8ad51a28 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3647,7 +3647,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const int buf_display_max_length = 2 * 1024 * 1024; // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. - const char* buf_display = (state != NULL && !is_readonly) ? state->TextA.Data : buf; + const char* buf_display = (g.ActiveId == id && state && !is_readonly) ? state->TextA.Data : buf; IM_ASSERT(buf_display); buf = NULL; From c3ea1748dc124ca4a209d54219d9b55b7817244e Mon Sep 17 00:00:00 2001 From: Elias Daler Date: Sun, 24 Feb 2019 20:35:52 +0300 Subject: [PATCH 094/566] Fix -Wconversion warning (#2379) The warning was caused by implicit conversion from pointer type which NULL has to non-pointer type, e.g. if ImTextureID is long int --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 37e8ff51..25ce75fe 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -407,7 +407,7 @@ ImDrawList* ImDrawList::CloneOutput() const // Using macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug builds #define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : _Data->ClipRectFullscreen) -#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL) +#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : (ImTextureID)NULL) void ImDrawList::AddDrawCmd() { From 5d7bd2309b19e451710f4a906ad99cb4d7fe02e5 Mon Sep 17 00:00:00 2001 From: David Wingrove Date: Sun, 24 Feb 2019 17:19:36 -0500 Subject: [PATCH 095/566] Fixes warning caused by a missing switch/case. (#2382, #2381) --- imgui.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 830e14a7..80fb3e33 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8930,6 +8930,9 @@ void ImGui::LogFinish() if (!g.LogBuffer.empty()) SetClipboardText(g.LogBuffer.begin()); break; + case ImGuiLogType_None: + IM_ASSERT(0); + break; } g.LogEnabled = false; From 439f72694596620257611a8ae46d5d4b2ab1174e Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 24 Feb 2019 23:31:00 +0100 Subject: [PATCH 096/566] InputText; Disabled rendering selection when inactive (it kinda work but I'm not sure this is desirable especially for single-line input, was not intended to be active). --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8ad51a28..7ff3d100 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3143,7 +3143,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; - const bool RENDER_SELECTION_WHEN_INACTIVE = true; + const bool RENDER_SELECTION_WHEN_INACTIVE = false; const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0; const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; From b7b82520b4d8223d5d676f6bff05b34f7f58bf1f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Feb 2019 12:22:58 +0100 Subject: [PATCH 097/566] Internal: InputText: Minor changes (intended to have side-effect but clarify next commit, however there is rarely such a thing as zero side effect in InputText land!) --- imgui_internal.h | 4 ++++ imgui_widgets.cpp | 41 +++++++++++++++++++++-------------------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index a76c386a..84420b99 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -104,6 +104,8 @@ namespace ImStb #define STB_TEXTEDIT_STRING ImGuiInputTextState #define STB_TEXTEDIT_CHARTYPE ImWchar #define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f +#define STB_TEXTEDIT_UNDOSTATECOUNT 99 +#define STB_TEXTEDIT_UNDOCHARCOUNT 999 #include "imstb_textedit.h" } // namespace ImStb @@ -593,6 +595,8 @@ struct IMGUI_API ImGuiInputTextState bool HasSelection() const { return Stb.select_start != Stb.select_end; } void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } + int GetUndoAvailCount() const { return Stb.undostate.undo_point; } + int GetRedoAvailCount() const { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; } void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7ff3d100..d1ecb088 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3277,32 +3277,33 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 g.ActiveIdAllowNavDirFlags = ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down)); } + // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function) + if (g.ActiveId == id && state == NULL) + ClearActiveID(); + // Release focus when we click outside if (!init_make_active && io.MouseClicked[0]) clear_active_id = true; - // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped) - if (g.ActiveId == id && state == NULL) - ClearActiveID(); - bool value_changed = false; bool enter_pressed = false; int backup_current_text_length = 0; + // When read-only we always use the live data passed to the function + if (g.ActiveId == id && is_readonly && !g.ActiveIdIsJustActivated) + { + IM_ASSERT(state != NULL); + const char* buf_end = NULL; + state->TextW.resize(buf_size + 1); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); + state->CursorClamp(); + } + // Process mouse inputs and character inputs if (g.ActiveId == id) { IM_ASSERT(state != NULL); - if (is_readonly && !g.ActiveIdIsJustActivated) - { - // When read-only we always use the live data passed to the function - const char* buf_end = NULL; - state->TextW.resize(buf_size+1); - state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); - state->CurLenA = (int)(buf_end - buf); - state->CursorClamp(); - } - backup_current_text_length = state->CurLenA; state->BufCapacityA = buf_size; state->UserFlags = flags; @@ -3653,7 +3654,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. - const bool render_cursor = (g.ActiveId == id) || user_scroll_active; + const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active); const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); if (render_cursor || render_selection) { @@ -3811,13 +3812,13 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 else { // Render text only (no selection, no cursor) - const char* buf_end = NULL; + const char* buf_display_end = NULL; if (is_multiline) - text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width + text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width else - buf_end = buf_display + strlen(buf_display); - if (is_multiline || (buf_end - buf_display) < buf_display_max_length) - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); + buf_display_end = buf_display + strlen(buf_display); + if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); } if (is_multiline) From cf3cb7cf7ee01a066a20c3e47189b336c48fb776 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Feb 2019 12:50:44 +0100 Subject: [PATCH 098/566] InputText: Fixed various display corruption related to swapping the underlying buffer while a input widget is active (both for writable and read-only paths). Often they would manifest when manipulating the scrollbar of a multi-line input text. --- docs/CHANGELOG.txt | 3 +++ imgui_internal.h | 3 ++- imgui_widgets.cpp | 54 ++++++++++++++++++++++++++-------------------- 3 files changed, 36 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9ef37fab..2511e4c0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ Other Changes: meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) - InputText: Fixed an edge case crash that would happen if another widget sharing the same ID is being swapped with an InputText that has yet to be activated. +- InputText: Fixed various display corruption related to swapping the underlying buffer while + a input widget is active (both for writable and read-only paths). Often they would manifest + when manipulating the scrollbar of a multi-line input text. - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) diff --git a/imgui_internal.h b/imgui_internal.h index 84420b99..40e10748 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -572,10 +572,11 @@ struct IMGUI_API ImGuiMenuColumns struct IMGUI_API ImGuiInputTextState { ImGuiID ID; // widget id owning the text state - int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. + int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 len is valid even if TextA is not. ImVector TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. ImVector TextA; // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity. ImVector InitialTextA; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) + bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument) int BufCapacityA; // end-user buffer capacity float ScrollX; // horizontal scrolling/offset ImStb::STB_TexteditState Stb; // state for stb_textedit.h diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d1ecb088..946a5dbe 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3224,7 +3224,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline); const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start); - if (init_make_active && g.ActiveId != id) + const bool init_state = (init_make_active || user_scroll_active); + if (init_state && g.ActiveId != id) { // Access state even if we don't own it yet. state = &g.InputTextState; @@ -3237,15 +3238,16 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 memcpy(state->InitialTextA.Data, buf, buf_len + 1); // Start edition - const int prev_len_w = state->CurLenW; const char* buf_end = NULL; state->TextW.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string. + state->TextA.resize(0); + state->TextAIsValid = false; // TextA is not valid yet (we will display buf until then) state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end); state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. // Preserve cursor position and undo/redo stack if we come back to same widget - // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). - const bool recycle_state = (state->ID == id) && (prev_len_w == state->CurLenW); + // FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed. + const bool recycle_state = (state->ID == id); if (recycle_state) { // Recycle existing cursor/selection/undo stack but clamp position @@ -3266,7 +3268,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 select_all = true; } - if (init_make_active) + if (g.ActiveId != id && init_make_active) { IM_ASSERT(state && state->ID == id); SetActiveID(id, window); @@ -3282,7 +3284,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 ClearActiveID(); // Release focus when we click outside - if (!init_make_active && io.MouseClicked[0]) + if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) clear_active_id = true; bool value_changed = false; @@ -3290,14 +3292,19 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 int backup_current_text_length = 0; // When read-only we always use the live data passed to the function - if (g.ActiveId == id && is_readonly && !g.ActiveIdIsJustActivated) + // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :( + if (is_readonly && state != NULL) { - IM_ASSERT(state != NULL); - const char* buf_end = NULL; - state->TextW.resize(buf_size + 1); - state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); - state->CurLenA = (int)(buf_end - buf); - state->CursorClamp(); + const bool will_render_cursor = (g.ActiveId == id) || (state && user_scroll_active); + const bool will_render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || will_render_cursor); + if (will_render_cursor || will_render_selection) + { + const char* buf_end = NULL; + state->TextW.resize(buf_size + 1); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); + state->CursorClamp(); + } } // Process mouse inputs and character inputs @@ -3516,6 +3523,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. if (!is_readonly) { + state->TextAIsValid = true; state->TextA.resize(state->TextW.Size * 4 + 1); ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL); } @@ -3646,11 +3654,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. const int buf_display_max_length = 2 * 1024 * 1024; - - // Select which buffer we are going to display. We set buf to NULL to prevent accidental usage from now on. - const char* buf_display = (g.ActiveId == id && state && !is_readonly) ? state->TextA.Data : buf; - IM_ASSERT(buf_display); - buf = NULL; + const char* buf_display = NULL; + const char* buf_display_end = NULL; // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. @@ -3790,9 +3795,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. - const int buf_display_len = state->CurLenA; - if (is_multiline || buf_display_len < buf_display_max_length) - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + buf_display_len, 0.0f, is_multiline ? NULL : &clip_rect); + buf_display = (!is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; + buf_display_end = buf_display + state->CurLenA; + if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); // Draw blinking cursor if (render_cursor) @@ -3812,9 +3818,11 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 else { // Render text only (no selection, no cursor) - const char* buf_display_end = NULL; + buf_display = (g.ActiveId == id && !is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; if (is_multiline) text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width + else if (g.ActiveId == id) + buf_display_end = buf_display + state->CurLenA; else buf_display_end = buf_display + strlen(buf_display); if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) @@ -3833,7 +3841,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Log as text if (g.LogEnabled && !is_password) - LogRenderedText(&draw_pos, buf_display, NULL); + LogRenderedText(&draw_pos, buf_display, buf_display_end); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); From 104294c7e44ecad5093cd03fa56c5a7d1076834a Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Feb 2019 15:33:50 +0100 Subject: [PATCH 099/566] Moved Logging/Capturing section above Docking to facilitate master<>docking merges. --- imgui.cpp | 402 +++++++++++++++++++++++++++--------------------------- 1 file changed, 202 insertions(+), 200 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2b1d4a98..12aba981 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -73,8 +73,8 @@ CODE // [SECTION] KEYBOARD/GAMEPAD NAVIGATION // [SECTION] COLUMNS // [SECTION] DRAG AND DROP -// [SECTION] DOCKING // [SECTION] LOGGING/CAPTURING +// [SECTION] DOCKING // [SECTION] SETTINGS // [SECTION] PLATFORM DEPENDENT HELPERS // [SECTION] METRICS/DEBUG WINDOW @@ -10100,6 +10100,207 @@ void ImGui::EndDragDropTarget() g.DragDropWithinSourceOrTarget = false; } +//----------------------------------------------------------------------------- +// [SECTION] LOGGING/CAPTURING +//----------------------------------------------------------------------------- +// All text output from the interface can be captured into tty/file/clipboard. +// By default, tree nodes are automatically opened during logging. +//----------------------------------------------------------------------------- + +// Pass text data straight to log (without being displayed) +void ImGui::LogText(const char* fmt, ...) +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + va_list args; + va_start(args, fmt); + if (g.LogFile) + vfprintf(g.LogFile, fmt, args); + else + g.LogBuffer.appendfv(fmt, args); + va_end(args); +} + +// Internal version that takes a position to decide on newline placement and pad items according to their depth. +// We split text into individual lines to add current tree level padding +void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (!text_end) + text_end = FindRenderedTextEnd(text, text_end); + + const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1); + if (ref_pos) + g.LogLinePosY = ref_pos->y; + if (log_new_line) + g.LogLineFirstItem = true; + + const char* text_remaining = text; + if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth + g.LogDepthRef = window->DC.TreeDepth; + const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); + for (;;) + { + // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. + // We don't add a trailing \n to allow a subsequent item on the same line to be captured. + const char* line_start = text_remaining; + const char* line_end = ImStreolRange(line_start, text_end); + const bool is_first_line = (line_start == text); + const bool is_last_line = (line_end == text_end); + if (!is_last_line || (line_start != line_end)) + { + const int char_count = (int)(line_end - line_start); + if (log_new_line || !is_first_line) + LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start); + else if (g.LogLineFirstItem) + LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start); + else + LogText(" %.*s", char_count, line_start); + g.LogLineFirstItem = false; + } + else if (log_new_line) + { + // An empty "" string at a different Y position should output a carriage return. + LogText(IM_NEWLINE); + break; + } + + if (is_last_line) + break; + text_remaining = line_end + 1; + } +} + +// Start logging/capturing text output +void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(g.LogEnabled == false); + IM_ASSERT(g.LogFile == NULL); + IM_ASSERT(g.LogBuffer.empty()); + g.LogEnabled = true; + g.LogType = type; + g.LogDepthRef = window->DC.TreeDepth; + g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); + g.LogLinePosY = FLT_MAX; + g.LogLineFirstItem = true; +} + +void ImGui::LogToTTY(int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogType_TTY, auto_open_depth); + g.LogFile = stdout; +} + +// Start logging/capturing text output to given file +void ImGui::LogToFile(int auto_open_depth, const char* filename) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + + // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still + // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. + // By opening the file in binary mode "ab" we have consistent output everywhere. + if (!filename) + filename = g.IO.LogFilename; + if (!filename || !filename[0]) + return; + FILE* f = ImFileOpen(filename, "ab"); + if (f == NULL) + { + IM_ASSERT(0); + return; + } + + LogBegin(ImGuiLogType_File, auto_open_depth); + g.LogFile = f; +} + +// Start logging/capturing text output to clipboard +void ImGui::LogToClipboard(int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogType_Clipboard, auto_open_depth); +} + +void ImGui::LogToBuffer(int auto_open_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + LogBegin(ImGuiLogType_Buffer, auto_open_depth); +} + +void ImGui::LogFinish() +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + LogText(IM_NEWLINE); + switch (g.LogType) + { + case ImGuiLogType_TTY: + fflush(g.LogFile); + break; + case ImGuiLogType_File: + fclose(g.LogFile); + break; + case ImGuiLogType_Buffer: + break; + case ImGuiLogType_Clipboard: + if (!g.LogBuffer.empty()) + SetClipboardText(g.LogBuffer.begin()); + break; + case ImGuiLogType_None: + IM_ASSERT(0); + break; + } + + g.LogEnabled = false; + g.LogType = ImGuiLogType_None; + g.LogFile = NULL; + g.LogBuffer.clear(); +} + +// Helper to display logging buttons +// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) +void ImGui::LogButtons() +{ + ImGuiContext& g = *GImGui; + + PushID("LogButtons"); + const bool log_to_tty = Button("Log To TTY"); SameLine(); + const bool log_to_file = Button("Log To File"); SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); + PushItemWidth(80.0f); + PushAllowKeyboardFocus(false); + SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); + PopAllowKeyboardFocus(); + PopItemWidth(); + PopID(); + + // Start logging at the end of the function so that the buttons don't appear in the log + if (log_to_tty) + LogToTTY(); + if (log_to_file) + LogToFile(); + if (log_to_clipboard) + LogToClipboard(); +} + + //----------------------------------------------------------------------------- // [SECTION] DOCKING //----------------------------------------------------------------------------- @@ -13194,205 +13395,6 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings buf->appendf("\n"); } -//----------------------------------------------------------------------------- -// [SECTION] LOGGING/CAPTURING -//----------------------------------------------------------------------------- -// All text output from the interface can be captured into tty/file/clipboard. -// By default, tree nodes are automatically opened during logging. -//----------------------------------------------------------------------------- - -// Pass text data straight to log (without being displayed) -void ImGui::LogText(const char* fmt, ...) -{ - ImGuiContext& g = *GImGui; - if (!g.LogEnabled) - return; - - va_list args; - va_start(args, fmt); - if (g.LogFile) - vfprintf(g.LogFile, fmt, args); - else - g.LogBuffer.appendfv(fmt, args); - va_end(args); -} - -// Internal version that takes a position to decide on newline placement and pad items according to their depth. -// We split text into individual lines to add current tree level padding -void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - - if (!text_end) - text_end = FindRenderedTextEnd(text, text_end); - - const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1); - if (ref_pos) - g.LogLinePosY = ref_pos->y; - if (log_new_line) - g.LogLineFirstItem = true; - - const char* text_remaining = text; - if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth - g.LogDepthRef = window->DC.TreeDepth; - const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); - for (;;) - { - // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. - // We don't add a trailing \n to allow a subsequent item on the same line to be captured. - const char* line_start = text_remaining; - const char* line_end = ImStreolRange(line_start, text_end); - const bool is_first_line = (line_start == text); - const bool is_last_line = (line_end == text_end); - if (!is_last_line || (line_start != line_end)) - { - const int char_count = (int)(line_end - line_start); - if (log_new_line || !is_first_line) - LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start); - else if (g.LogLineFirstItem) - LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start); - else - LogText(" %.*s", char_count, line_start); - g.LogLineFirstItem = false; - } - else if (log_new_line) - { - // An empty "" string at a different Y position should output a carriage return. - LogText(IM_NEWLINE); - break; - } - - if (is_last_line) - break; - text_remaining = line_end + 1; - } -} - -// Start logging/capturing text output -void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(g.LogEnabled == false); - IM_ASSERT(g.LogFile == NULL); - IM_ASSERT(g.LogBuffer.empty()); - g.LogEnabled = true; - g.LogType = type; - g.LogDepthRef = window->DC.TreeDepth; - g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); - g.LogLinePosY = FLT_MAX; - g.LogLineFirstItem = true; -} - -void ImGui::LogToTTY(int auto_open_depth) -{ - ImGuiContext& g = *GImGui; - if (g.LogEnabled) - return; - LogBegin(ImGuiLogType_TTY, auto_open_depth); - g.LogFile = stdout; -} - -// Start logging/capturing text output to given file -void ImGui::LogToFile(int auto_open_depth, const char* filename) -{ - ImGuiContext& g = *GImGui; - if (g.LogEnabled) - return; - - // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still - // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. - // By opening the file in binary mode "ab" we have consistent output everywhere. - if (!filename) - filename = g.IO.LogFilename; - if (!filename || !filename[0]) - return; - FILE* f = ImFileOpen(filename, "ab"); - if (f == NULL) - { - IM_ASSERT(0); - return; - } - - LogBegin(ImGuiLogType_File, auto_open_depth); - g.LogFile = f; -} - -// Start logging/capturing text output to clipboard -void ImGui::LogToClipboard(int auto_open_depth) -{ - ImGuiContext& g = *GImGui; - if (g.LogEnabled) - return; - LogBegin(ImGuiLogType_Clipboard, auto_open_depth); -} - -void ImGui::LogToBuffer(int auto_open_depth) -{ - ImGuiContext& g = *GImGui; - if (g.LogEnabled) - return; - LogBegin(ImGuiLogType_Buffer, auto_open_depth); -} - -void ImGui::LogFinish() -{ - ImGuiContext& g = *GImGui; - if (!g.LogEnabled) - return; - - LogText(IM_NEWLINE); - switch (g.LogType) - { - case ImGuiLogType_TTY: - fflush(g.LogFile); - break; - case ImGuiLogType_File: - fclose(g.LogFile); - break; - case ImGuiLogType_Buffer: - break; - case ImGuiLogType_Clipboard: - if (!g.LogBuffer.empty()) - SetClipboardText(g.LogBuffer.begin()); - break; - case ImGuiLogType_None: - IM_ASSERT(0); - break; - } - - g.LogEnabled = false; - g.LogType = ImGuiLogType_None; - g.LogFile = NULL; - g.LogBuffer.clear(); -} - -// Helper to display logging buttons -// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) -void ImGui::LogButtons() -{ - ImGuiContext& g = *GImGui; - - PushID("LogButtons"); - const bool log_to_tty = Button("Log To TTY"); SameLine(); - const bool log_to_file = Button("Log To File"); SameLine(); - const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); - PushItemWidth(80.0f); - PushAllowKeyboardFocus(false); - SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); - PopAllowKeyboardFocus(); - PopItemWidth(); - PopID(); - - // Start logging at the end of the function so that the buttons don't appear in the log - if (log_to_tty) - LogToTTY(); - if (log_to_file) - LogToFile(); - if (log_to_clipboard) - LogToClipboard(); -} //----------------------------------------------------------------------------- // [SECTION] SETTINGS From 4eecf80a4b253f359b9879e6538e41b4edeae1de Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Feb 2019 15:34:47 +0100 Subject: [PATCH 100/566] Moved Settings section above Docking to facilitate master<>docking merges. --- imgui.cpp | 497 +++++++++++++++++++++++++++--------------------------- 1 file changed, 249 insertions(+), 248 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 12aba981..0558043f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -74,8 +74,8 @@ CODE // [SECTION] COLUMNS // [SECTION] DRAG AND DROP // [SECTION] LOGGING/CAPTURING -// [SECTION] DOCKING // [SECTION] SETTINGS +// [SECTION] DOCKING // [SECTION] PLATFORM DEPENDENT HELPERS // [SECTION] METRICS/DEBUG WINDOW @@ -10301,6 +10301,254 @@ void ImGui::LogButtons() } +//----------------------------------------------------------------------------- +// [SECTION] SETTINGS +//----------------------------------------------------------------------------- + +void ImGui::MarkIniSettingsDirty() +{ + ImGuiContext& g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +void ImGui::MarkIniSettingsDirty(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) +{ + ImGuiContext& g = *GImGui; + g.SettingsWindows.push_back(ImGuiWindowSettings()); + ImGuiWindowSettings* settings = &g.SettingsWindows.back(); + settings->Name = ImStrdup(name); + settings->ID = ImHashStr(name, 0); + return settings; +} + +ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + for (int i = 0; i != g.SettingsWindows.Size; i++) + if (g.SettingsWindows[i].ID == id) + return &g.SettingsWindows[i]; + return NULL; +} + +ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) +{ + if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name, 0))) + return settings; + return CreateNewWindowSettings(name); +} + +void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) +{ + size_t file_data_size = 0; + char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); + if (!file_data) + return; + LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); + ImGui::MemFree(file_data); +} + +ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) +{ + ImGuiContext& g = *GImGui; + const ImGuiID type_hash = ImHashStr(type_name, 0); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].TypeHash == type_hash) + return &g.SettingsHandlers[handler_n]; + return NULL; +} + +// Zero-tolerance, no error reporting, cheap .ini parsing +void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); + IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); + + // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). + // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. + if (ini_size == 0) + ini_size = strlen(ini_data); + char* buf = (char*)ImGui::MemAlloc(ini_size + 1); + char* buf_end = buf + ini_size; + memcpy(buf, ini_data, ini_size); + buf[ini_size] = 0; + + void* entry_data = NULL; + ImGuiSettingsHandler* entry_handler = NULL; + + char* line_end = NULL; + for (char* line = buf; line < buf_end; line = line_end + 1) + { + // Skip new lines markers, then find end of the line + while (*line == '\n' || *line == '\r') + line++; + line_end = line; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + line_end[0] = 0; + if (line[0] == ';') + continue; + if (line[0] == '[' && line_end > line && line_end[-1] == ']') + { + // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. + line_end[-1] = 0; + const char* name_end = line_end - 1; + const char* type_start = line + 1; + char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); + const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; + if (!type_end || !name_start) + { + name_start = type_start; // Import legacy entries that have no type + type_start = "Window"; + } + else + { + *type_end = 0; // Overwrite first ']' + name_start++; // Skip second '[' + } + entry_handler = FindSettingsHandler(type_start); + entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; + } + else if (entry_handler != NULL && entry_data != NULL) + { + // Let type handler parse the line + entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); + } + } + ImGui::MemFree(buf); + g.SettingsLoaded = true; + DockContextOnLoadSettings(&g); +} + +void ImGui::SaveIniSettingsToDisk(const char* ini_filename) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + if (!ini_filename) + return; + + size_t ini_data_size = 0; + const char* ini_data = SaveIniSettingsToMemory(&ini_data_size); + FILE* f = ImFileOpen(ini_filename, "wt"); + if (!f) + return; + fwrite(ini_data, sizeof(char), ini_data_size, f); + fclose(f); +} + +// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer +const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + g.SettingsIniData.Buf.resize(0); + g.SettingsIniData.Buf.push_back(0); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + { + ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n]; + handler->WriteAllFn(&g, handler, &g.SettingsIniData); + } + if (out_size) + *out_size = (size_t)g.SettingsIniData.size(); + return g.SettingsIniData.c_str(); +} + +static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +{ + ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name, 0)); + if (!settings) + settings = ImGui::CreateNewWindowSettings(name); + return (void*)settings; +} + +static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +{ + ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; + float x, y; + int i; + ImU32 u1; + if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) { settings->Pos = ImVec2(x, y); } + else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) { settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize); } + else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; } + else if (sscanf(line, "ViewportPos=%f,%f", &x, &y) == 2) { settings->ViewportPos = ImVec2(x, y); } + else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } + else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; } + else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; } + else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; } +} + +static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +{ + // Gather data from windows that were active during this session + // (if a window wasn't opened in this session we preserve its settings) + ImGuiContext& g = *imgui_ctx; + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + + ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID); + if (!settings) + { + settings = ImGui::CreateNewWindowSettings(window->Name); + window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); + } + IM_ASSERT(settings->ID == window->ID); + settings->Pos = window->Pos - window->ViewportPos; + settings->Size = window->SizeFull; + settings->ViewportId = window->ViewportId; + settings->ViewportPos = window->ViewportPos; + IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId); + settings->DockId = window->DockId; + settings->ClassId = window->WindowClass.ClassId; + settings->DockOrder = window->DockOrder; + settings->Collapsed = window->Collapsed; + } + + // Write to text buffer + buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve + for (int i = 0; i != g.SettingsWindows.Size; i++) + { + const ImGuiWindowSettings* settings = &g.SettingsWindows[i]; + const char* name = settings->Name; + if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + name = p; + buf->appendf("[%s][%s]\n", handler->TypeName, name); + if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID) + { + buf->appendf("ViewportPos=%d,%d\n", (int)settings->ViewportPos.x, (int)settings->ViewportPos.y); + buf->appendf("ViewportId=0x%08X\n", settings->ViewportId); + } + if (settings->Pos.x != 0.0f || settings->Pos.y != 0.0f || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID) + buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); + if (settings->Size.x != 0.0f || settings->Size.y != 0.0f) + buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + buf->appendf("Collapsed=%d\n", settings->Collapsed); + if (settings->DockId != 0) + { + // Write DockId as 4 digits if possible. Automatic DockId are small numbers, but full explicit DockSpace() are full ImGuiID range. + if (settings->DockOrder == -1) + buf->appendf("DockId=0x%08X\n", settings->DockId); + else + buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder); + if (settings->ClassId != 0) + buf->appendf("ClassId=0x%08X\n", settings->ClassId); + } + buf->appendf("\n"); + } +} + + //----------------------------------------------------------------------------- // [SECTION] DOCKING //----------------------------------------------------------------------------- @@ -13396,253 +13644,6 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings } -//----------------------------------------------------------------------------- -// [SECTION] SETTINGS -//----------------------------------------------------------------------------- - -void ImGui::MarkIniSettingsDirty() -{ - ImGuiContext& g = *GImGui; - if (g.SettingsDirtyTimer <= 0.0f) - g.SettingsDirtyTimer = g.IO.IniSavingRate; -} - -void ImGui::MarkIniSettingsDirty(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) - if (g.SettingsDirtyTimer <= 0.0f) - g.SettingsDirtyTimer = g.IO.IniSavingRate; -} - -ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) -{ - ImGuiContext& g = *GImGui; - g.SettingsWindows.push_back(ImGuiWindowSettings()); - ImGuiWindowSettings* settings = &g.SettingsWindows.back(); - settings->Name = ImStrdup(name); - settings->ID = ImHashStr(name, 0); - return settings; -} - -ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) -{ - ImGuiContext& g = *GImGui; - for (int i = 0; i != g.SettingsWindows.Size; i++) - if (g.SettingsWindows[i].ID == id) - return &g.SettingsWindows[i]; - return NULL; -} - -ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) -{ - if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name, 0))) - return settings; - return CreateNewWindowSettings(name); -} - -void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) -{ - size_t file_data_size = 0; - char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); - if (!file_data) - return; - LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); - ImGui::MemFree(file_data); -} - -ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) -{ - ImGuiContext& g = *GImGui; - const ImGuiID type_hash = ImHashStr(type_name, 0); - for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) - if (g.SettingsHandlers[handler_n].TypeHash == type_hash) - return &g.SettingsHandlers[handler_n]; - return NULL; -} - -// Zero-tolerance, no error reporting, cheap .ini parsing -void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) -{ - ImGuiContext& g = *GImGui; - IM_ASSERT(g.Initialized); - IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); - - // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). - // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. - if (ini_size == 0) - ini_size = strlen(ini_data); - char* buf = (char*)ImGui::MemAlloc(ini_size + 1); - char* buf_end = buf + ini_size; - memcpy(buf, ini_data, ini_size); - buf[ini_size] = 0; - - void* entry_data = NULL; - ImGuiSettingsHandler* entry_handler = NULL; - - char* line_end = NULL; - for (char* line = buf; line < buf_end; line = line_end + 1) - { - // Skip new lines markers, then find end of the line - while (*line == '\n' || *line == '\r') - line++; - line_end = line; - while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') - line_end++; - line_end[0] = 0; - if (line[0] == ';') - continue; - if (line[0] == '[' && line_end > line && line_end[-1] == ']') - { - // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. - line_end[-1] = 0; - const char* name_end = line_end - 1; - const char* type_start = line + 1; - char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); - const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; - if (!type_end || !name_start) - { - name_start = type_start; // Import legacy entries that have no type - type_start = "Window"; - } - else - { - *type_end = 0; // Overwrite first ']' - name_start++; // Skip second '[' - } - entry_handler = FindSettingsHandler(type_start); - entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; - } - else if (entry_handler != NULL && entry_data != NULL) - { - // Let type handler parse the line - entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); - } - } - ImGui::MemFree(buf); - g.SettingsLoaded = true; - DockContextOnLoadSettings(&g); -} - -void ImGui::SaveIniSettingsToDisk(const char* ini_filename) -{ - ImGuiContext& g = *GImGui; - g.SettingsDirtyTimer = 0.0f; - if (!ini_filename) - return; - - size_t ini_data_size = 0; - const char* ini_data = SaveIniSettingsToMemory(&ini_data_size); - FILE* f = ImFileOpen(ini_filename, "wt"); - if (!f) - return; - fwrite(ini_data, sizeof(char), ini_data_size, f); - fclose(f); -} - -// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer -const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) -{ - ImGuiContext& g = *GImGui; - g.SettingsDirtyTimer = 0.0f; - g.SettingsIniData.Buf.resize(0); - g.SettingsIniData.Buf.push_back(0); - for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) - { - ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n]; - handler->WriteAllFn(&g, handler, &g.SettingsIniData); - } - if (out_size) - *out_size = (size_t)g.SettingsIniData.size(); - return g.SettingsIniData.c_str(); -} - -static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) -{ - ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name, 0)); - if (!settings) - settings = ImGui::CreateNewWindowSettings(name); - return (void*)settings; -} - -static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) -{ - ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; - float x, y; - int i; - ImU32 u1; - if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) { settings->Pos = ImVec2(x, y); } - else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) { settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize); } - else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; } - else if (sscanf(line, "ViewportPos=%f,%f", &x, &y) == 2) { settings->ViewportPos = ImVec2(x, y); } - else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } - else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; } - else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; } - else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; } -} - -static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) -{ - // Gather data from windows that were active during this session - // (if a window wasn't opened in this session we preserve its settings) - ImGuiContext& g = *imgui_ctx; - for (int i = 0; i != g.Windows.Size; i++) - { - ImGuiWindow* window = g.Windows[i]; - if (window->Flags & ImGuiWindowFlags_NoSavedSettings) - continue; - - ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID); - if (!settings) - { - settings = ImGui::CreateNewWindowSettings(window->Name); - window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); - } - IM_ASSERT(settings->ID == window->ID); - settings->Pos = window->Pos - window->ViewportPos; - settings->Size = window->SizeFull; - settings->ViewportId = window->ViewportId; - settings->ViewportPos = window->ViewportPos; - IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId); - settings->DockId = window->DockId; - settings->ClassId = window->WindowClass.ClassId; - settings->DockOrder = window->DockOrder; - settings->Collapsed = window->Collapsed; - } - - // Write to text buffer - buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve - for (int i = 0; i != g.SettingsWindows.Size; i++) - { - const ImGuiWindowSettings* settings = &g.SettingsWindows[i]; - const char* name = settings->Name; - if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() - name = p; - buf->appendf("[%s][%s]\n", handler->TypeName, name); - if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID) - { - buf->appendf("ViewportPos=%d,%d\n", (int)settings->ViewportPos.x, (int)settings->ViewportPos.y); - buf->appendf("ViewportId=0x%08X\n", settings->ViewportId); - } - if (settings->Pos.x != 0.0f || settings->Pos.y != 0.0f || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID) - buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); - if (settings->Size.x != 0.0f || settings->Size.y != 0.0f) - buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); - buf->appendf("Collapsed=%d\n", settings->Collapsed); - if (settings->DockId != 0) - { - // Write DockId as 4 digits if possible. Automatic DockId are small numbers, but full explicit DockSpace() are full ImGuiID range. - if (settings->DockOrder == -1) - buf->appendf("DockId=0x%08X\n", settings->DockId); - else - buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder); - if (settings->ClassId != 0) - buf->appendf("ClassId=0x%08X\n", settings->ClassId); - } - buf->appendf("\n"); - } -} - //----------------------------------------------------------------------------- // [SECTION] PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- From 5e3a1de4e6b328a18829b29b3ed265e41fd202bb Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 14:25:37 +0100 Subject: [PATCH 101/566] Plot: Fixed divide-by-zero in PlotLines() when passing a count of 1. (#2387) [@Lectem] --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2511e4c0..68850768 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,7 @@ Other Changes: - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) +- Plot: Fixed divide-by-zero in PlotLines() when passing a count of 1. (#2387) [@Lectem] - Log/Capture: Fixed extraneous leading carriage return. - Log/Capture: Fixed an issue when empty string on a new line would not emit a carriage return. - Log/Capture: Fixed LogXXX functions 'auto_open_depth' parameter being treated as an absolute diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 946a5dbe..4ed42ec3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5343,7 +5343,8 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); - if (values_count > 0) + const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1; + if (values_count >= 1)//values_count_min) { int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); From def723b6b6301b580450edce0ff7797c148379c3 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 14:34:11 +0100 Subject: [PATCH 102/566] Plot: Fixed error in 5e3a1de (#2387) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4ed42ec3..c9edc476 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5344,7 +5344,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1; - if (values_count >= 1)//values_count_min) + if (values_count >= values_count_min) { int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); From cef77098ab737c405a29cbdc2727677674e1d631 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 15:00:41 +0100 Subject: [PATCH 103/566] Update README.md --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index 7e041181..e9b53eb6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -145,7 +145,7 @@ Frameworks: - Ogre: [ogreimgui](https://bitbucket.org/LMCrashy/ogreimgui/src) - OpenFrameworks: [ofxImGui](https://github.com/jvcleave/ofxImGui) - OpenSceneGraph/OSG: [gist](https://gist.github.com/fulezi/d2442ca7626bf270226014501357042c) -- ORX: [#1843](https://github.com/ocornut/imgui/pull/1843) +- ORX: [ImGuiOrx](https://github.com/thegwydd/ImGuiOrx), [#1843](https://github.com/ocornut/imgui/pull/1843) - LÖVE+Lua: [love-imgui](https://github.com/slages/love-imgui) - Magnum: [ImGuiIntegration](https://doc.magnum.graphics/magnum/namespaceMagnum_1_1ImGuiIntegration.html) ([example](https://doc.magnum.graphics/magnum/examples-imgui.html)) - NanoRT: [syoyo/imgui](https://github.com/syoyo/imgui/tree/nanort) From 688035b5f40a5f2902e2f05f945cf75dc7b0cf6b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 15:06:11 +0100 Subject: [PATCH 104/566] Added px_render_imgui.h (#1935) --- docs/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/README.md b/docs/README.md index e9b53eb6..96d3e6d8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -146,6 +146,7 @@ Frameworks: - OpenFrameworks: [ofxImGui](https://github.com/jvcleave/ofxImGui) - OpenSceneGraph/OSG: [gist](https://gist.github.com/fulezi/d2442ca7626bf270226014501357042c) - ORX: [ImGuiOrx](https://github.com/thegwydd/ImGuiOrx), [#1843](https://github.com/ocornut/imgui/pull/1843) +- px_render: [px_render_imgui.h](https://github.com/pplux/px/blob/master/px_render_imgui.h), [#1935](https://github.com/ocornut/imgui/pull/1935) - LÖVE+Lua: [love-imgui](https://github.com/slages/love-imgui) - Magnum: [ImGuiIntegration](https://doc.magnum.graphics/magnum/namespaceMagnum_1_1ImGuiIntegration.html) ([example](https://doc.magnum.graphics/magnum/examples-imgui.html)) - NanoRT: [syoyo/imgui](https://github.com/syoyo/imgui/tree/nanort) From 8a2f6866a69b054995651d5edc7b87ac7b362634 Mon Sep 17 00:00:00 2001 From: haldean Date: Tue, 26 Feb 2019 10:19:06 -0800 Subject: [PATCH 105/566] add _Show prefix to color flags that control inputs, rename __InputsMask to __ShowMask This is anticipation of changing __InputsMask to control the format of input colors, and adding _InputRGB and _InputHSV to change how input colors are interpreted. --- imgui.h | 14 +++++++++----- imgui_demo.cpp | 16 ++++++++-------- imgui_widgets.cpp | 46 +++++++++++++++++++++++----------------------- 3 files changed, 40 insertions(+), 36 deletions(-) diff --git a/imgui.h b/imgui.h index dd1e67dc..13e5c2ed 100644 --- a/imgui.h +++ b/imgui.h @@ -1110,19 +1110,23 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). - ImGuiColorEditFlags_RGB = 1 << 20, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX. - ImGuiColorEditFlags_HSV = 1 << 21, // [Inputs] // " - ImGuiColorEditFlags_HEX = 1 << 22, // [Inputs] // " + ImGuiColorEditFlags_ShowRGB = 1 << 20, // [Show] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX. + ImGuiColorEditFlags_ShowHSV = 1 << 21, // [Show] // " + ImGuiColorEditFlags_ShowHEX = 1 << 22, // [Show] // " ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value. ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value. + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_ShowRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_ShowHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_ShowHEX, +#endif // [Internal] Masks - ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX, + ImGuiColorEditFlags__ShowMask = ImGuiColorEditFlags_ShowRGB|ImGuiColorEditFlags_ShowHSV|ImGuiColorEditFlags_ShowHEX, ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, - ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() + ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_ShowRGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() }; // Enumeration for GetMouseCursor() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 560224f1..4ec1561f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1045,7 +1045,7 @@ static void ShowDemoWindowWidgets() ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); ImGui::Text("Color widget HSV with Alpha:"); - ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_HSV | misc_flags); + ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_ShowHSV | misc_flags); ImGui::Text("Color widget with Float Display:"); ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); @@ -1127,7 +1127,7 @@ static void ShowDemoWindowWidgets() static bool side_preview = true; static bool ref_color = false; static ImVec4 ref_color_v(1.0f,0.0f,1.0f,0.5f); - static int inputs_mode = 2; + static int show_mode = 2; static int picker_mode = 0; ImGui::Checkbox("With Alpha", &alpha); ImGui::Checkbox("With Alpha Bar", &alpha_bar); @@ -1142,7 +1142,7 @@ static void ShowDemoWindowWidgets() ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags); } } - ImGui::Combo("Inputs Mode", &inputs_mode, "All Inputs\0No Inputs\0RGB Input\0HSV Input\0HEX Input\0"); + ImGui::Combo("Show Mode", &show_mode, "All\0None\0Show RGB\0Show HSV\0Show HEX\0"); ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0"); ImGui::SameLine(); ShowHelpMarker("User can right-click the picker to change mode."); ImGuiColorEditFlags flags = misc_flags; @@ -1151,16 +1151,16 @@ static void ShowDemoWindowWidgets() if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview; if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; - if (inputs_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; - if (inputs_mode == 2) flags |= ImGuiColorEditFlags_RGB; - if (inputs_mode == 3) flags |= ImGuiColorEditFlags_HSV; - if (inputs_mode == 4) flags |= ImGuiColorEditFlags_HEX; + if (show_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; + if (show_mode == 2) flags |= ImGuiColorEditFlags_ShowRGB; + if (show_mode == 3) flags |= ImGuiColorEditFlags_ShowHSV; + if (show_mode == 4) flags |= ImGuiColorEditFlags_ShowHEX; ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); ImGui::Text("Programmatically set defaults:"); ImGui::SameLine(); ShowHelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible."); if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) - ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_HSV | ImGuiColorEditFlags_PickerHueBar); + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_ShowHSV | ImGuiColorEditFlags_PickerHueBar); if (ImGui::Button("Default: Float + HDR + Hue Wheel")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c9edc476..a1741f6f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3898,20 +3898,20 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // If we're not showing any slider there's no point in doing any HSV conversions const ImGuiColorEditFlags flags_untouched = flags; if (flags & ImGuiColorEditFlags_NoInputs) - flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions; + flags = (flags & (~ImGuiColorEditFlags__ShowMask)) | ImGuiColorEditFlags_ShowRGB | ImGuiColorEditFlags_NoOptions; // Context menu: display and modify options (before defaults are applied) if (!(flags & ImGuiColorEditFlags_NoOptions)) ColorEditOptionsPopup(col, flags); // Read stored options - if (!(flags & ImGuiColorEditFlags__InputsMask)) - flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask); + if (!(flags & ImGuiColorEditFlags__ShowMask)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags__ShowMask); if (!(flags & ImGuiColorEditFlags__DataTypeMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask); if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask); - flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask)); + flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__ShowMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask)); const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; @@ -3919,14 +3919,14 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // Convert to the formats we need float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; - if (flags & ImGuiColorEditFlags_HSV) + if (flags & ImGuiColorEditFlags_ShowHSV) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; bool value_changed = false; bool value_changed_as_float = false; - if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + if ((flags & (ImGuiColorEditFlags_ShowRGB | ImGuiColorEditFlags_ShowHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); @@ -3946,7 +3946,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA }; - const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1; + const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_ShowHSV) ? 2 : 1; PushItemWidth(w_item_one); for (int n = 0; n < components; n++) @@ -3970,7 +3970,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag PopItemWidth(); PopItemWidth(); } - else if ((flags & ImGuiColorEditFlags_HEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + else if ((flags & ImGuiColorEditFlags_ShowHEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB Hexadecimal Input char buf[64]; @@ -4025,7 +4025,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag Spacing(); } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; - ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__ShowMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); PopItemWidth(); @@ -4045,7 +4045,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (!value_changed_as_float) for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; - if (flags & ImGuiColorEditFlags_HSV) + if (flags & ImGuiColorEditFlags_ShowHSV) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { @@ -4330,18 +4330,18 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; - if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0) - if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB)) + if (flags & ImGuiColorEditFlags_ShowRGB || (flags & ImGuiColorEditFlags__ShowMask) == 0) + if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_ShowRGB)) { // FIXME: Hackily differenciating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050) value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap); value_changed = true; } - if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0) - value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV); - if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0) - value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX); + if (flags & ImGuiColorEditFlags_ShowHSV || (flags & ImGuiColorEditFlags__ShowMask) == 0) + value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_ShowHSV); + if (flags & ImGuiColorEditFlags_ShowHEX || (flags & ImGuiColorEditFlags__ShowMask) == 0) + value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_ShowHEX); PopItemWidth(); } @@ -4539,13 +4539,13 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; - if ((flags & ImGuiColorEditFlags__InputsMask) == 0) - flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask; + if ((flags & ImGuiColorEditFlags__ShowMask) == 0) + flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__ShowMask; if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask; if ((flags & ImGuiColorEditFlags__PickerMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask; - IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__ShowMask))); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected g.ColorEditOptions = flags; @@ -4578,7 +4578,7 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) { - bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask); + bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__ShowMask); bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask); if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) return; @@ -4586,9 +4586,9 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) ImGuiColorEditFlags opts = g.ColorEditOptions; if (allow_opt_inputs) { - if (RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB; - if (RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV; - if (RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) != 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX; + if (RadioButton("RGB", (opts & ImGuiColorEditFlags_ShowRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__ShowMask) | ImGuiColorEditFlags_ShowRGB; + if (RadioButton("HSV", (opts & ImGuiColorEditFlags_ShowHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__ShowMask) | ImGuiColorEditFlags_ShowHSV; + if (RadioButton("HEX", (opts & ImGuiColorEditFlags_ShowHEX) != 0)) opts = (opts & ~ImGuiColorEditFlags__ShowMask) | ImGuiColorEditFlags_ShowHEX; } if (allow_opt_datatype) { From 6de09a5e480fc04019ecbd2e2eb46dc5c5fdc847 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 16:45:58 +0100 Subject: [PATCH 106/566] Renamed ColorEdit/ColorPicker's ImGuiColorEditFlags_RGB/_HSV/_HEX flags to respectively ImGuiColorEditFlags_DisplayRGB/_DisplayHSV/_DisplayHex. This is anticipation of adding new flags to ColorEdit/ColorPicker functions which would make those ambiguous. (#2384) [@haldean] --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 1 + imgui.h | 24 ++++++++++++----------- imgui_demo.cpp | 27 +++++++++++++------------- imgui_widgets.cpp | 47 +++++++++++++++++++++++----------------------- 5 files changed, 58 insertions(+), 47 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 99c2ee48..caa78523 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -33,6 +33,12 @@ HOW TO UPDATE? VERSION 1.69 (In Progress) ----------------------------------------------------------------------- +Breaking Changes: + +- Renamed ColorEdit/ColorPicker's ImGuiColorEditFlags_RGB/_HSV/_HEX flags to respectively + ImGuiColorEditFlags_DisplayRGB/_DisplayHSV/_DisplayHex. This is anticipation of adding new + flags to ColorEdit/ColorPicker functions which would make those ambiguous. (#2384) [@haldean] + Other Changes: - Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigation to the menu layer. diff --git a/imgui.cpp b/imgui.cpp index 80fb3e33..28c1277a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -364,6 +364,7 @@ CODE When you are not sure about a 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. + - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! diff --git a/imgui.h b/imgui.h index 13e5c2ed..f301ccf4 100644 --- a/imgui.h +++ b/imgui.h @@ -1095,7 +1095,7 @@ enum ImGuiStyleVar_ enum ImGuiColorEditFlags_ { ImGuiColorEditFlags_None = 0, - ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer). + ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square. ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs) @@ -1105,28 +1105,30 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. - // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup. + // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). + // The intent is that you probably don't want to override them in most of your calls, let the user choose via the option menu and/or call SetColorEditOptions() during startup. ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). - ImGuiColorEditFlags_ShowRGB = 1 << 20, // [Show] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX. - ImGuiColorEditFlags_ShowHSV = 1 << 21, // [Show] // " - ImGuiColorEditFlags_ShowHEX = 1 << 22, // [Show] // " + ImGuiColorEditFlags_DisplayRGB = 1 << 20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + ImGuiColorEditFlags_DisplayHSV = 1 << 21, // [Display] // " + ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // " ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value. ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value. - // Obsolete names (will be removed) -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_ShowRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_ShowHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_ShowHEX, -#endif // [Internal] Masks - ImGuiColorEditFlags__ShowMask = ImGuiColorEditFlags_ShowRGB|ImGuiColorEditFlags_ShowHSV|ImGuiColorEditFlags_ShowHEX, + ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_DisplayHSV|ImGuiColorEditFlags_DisplayHex, ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, - ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_ShowRGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() + ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex +#endif }; // Enumeration for GetMouseCursor() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4ec1561f..09e36693 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1045,7 +1045,7 @@ static void ShowDemoWindowWidgets() ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); ImGui::Text("Color widget HSV with Alpha:"); - ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_ShowHSV | misc_flags); + ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags); ImGui::Text("Color widget with Float Display:"); ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); @@ -1127,7 +1127,7 @@ static void ShowDemoWindowWidgets() static bool side_preview = true; static bool ref_color = false; static ImVec4 ref_color_v(1.0f,0.0f,1.0f,0.5f); - static int show_mode = 2; + static int display_mode = 0; static int picker_mode = 0; ImGui::Checkbox("With Alpha", &alpha); ImGui::Checkbox("With Alpha Bar", &alpha_bar); @@ -1142,25 +1142,26 @@ static void ShowDemoWindowWidgets() ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags); } } - ImGui::Combo("Show Mode", &show_mode, "All\0None\0Show RGB\0Show HSV\0Show HEX\0"); + ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0"); + ImGui::SameLine(); ShowHelpMarker("ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0"); ImGui::SameLine(); ShowHelpMarker("User can right-click the picker to change mode."); ImGuiColorEditFlags flags = misc_flags; - if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4() - if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar; - if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview; - if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; - if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; - if (show_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; - if (show_mode == 2) flags |= ImGuiColorEditFlags_ShowRGB; - if (show_mode == 3) flags |= ImGuiColorEditFlags_ShowHSV; - if (show_mode == 4) flags |= ImGuiColorEditFlags_ShowHEX; + if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4() + if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar; + if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview; + if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar; + if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel; + if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays + if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; // Override display mode + if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV; + if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex; ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); ImGui::Text("Programmatically set defaults:"); ImGui::SameLine(); ShowHelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible."); if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) - ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_ShowHSV | ImGuiColorEditFlags_PickerHueBar); + ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); if (ImGui::Button("Default: Float + HDR + Hue Wheel")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a1741f6f..b1e17f12 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3898,20 +3898,20 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // If we're not showing any slider there's no point in doing any HSV conversions const ImGuiColorEditFlags flags_untouched = flags; if (flags & ImGuiColorEditFlags_NoInputs) - flags = (flags & (~ImGuiColorEditFlags__ShowMask)) | ImGuiColorEditFlags_ShowRGB | ImGuiColorEditFlags_NoOptions; + flags = (flags & (~ImGuiColorEditFlags__DisplayMask)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions; // Context menu: display and modify options (before defaults are applied) if (!(flags & ImGuiColorEditFlags_NoOptions)) ColorEditOptionsPopup(col, flags); // Read stored options - if (!(flags & ImGuiColorEditFlags__ShowMask)) - flags |= (g.ColorEditOptions & ImGuiColorEditFlags__ShowMask); + if (!(flags & ImGuiColorEditFlags__DisplayMask)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DisplayMask); if (!(flags & ImGuiColorEditFlags__DataTypeMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask); if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask); - flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__ShowMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask)); + flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask)); const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; @@ -3919,14 +3919,14 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // Convert to the formats we need float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; - if (flags & ImGuiColorEditFlags_ShowHSV) + if (flags & ImGuiColorEditFlags_DisplayHSV) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; bool value_changed = false; bool value_changed_as_float = false; - if ((flags & (ImGuiColorEditFlags_ShowRGB | ImGuiColorEditFlags_ShowHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); @@ -3946,7 +3946,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA }; - const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_ShowHSV) ? 2 : 1; + const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1; PushItemWidth(w_item_one); for (int n = 0; n < components; n++) @@ -3970,7 +3970,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag PopItemWidth(); PopItemWidth(); } - else if ((flags & ImGuiColorEditFlags_ShowHEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) + else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB Hexadecimal Input char buf[64]; @@ -4025,7 +4025,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag Spacing(); } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; - ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__ShowMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); PopItemWidth(); @@ -4045,7 +4045,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (!value_changed_as_float) for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; - if (flags & ImGuiColorEditFlags_ShowHSV) + if (flags & ImGuiColorEditFlags_DisplayHSV) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { @@ -4330,18 +4330,18 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; - if (flags & ImGuiColorEditFlags_ShowRGB || (flags & ImGuiColorEditFlags__ShowMask) == 0) - if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_ShowRGB)) + if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags__DisplayMask) == 0) + if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB)) { // FIXME: Hackily differenciating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050) value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap); value_changed = true; } - if (flags & ImGuiColorEditFlags_ShowHSV || (flags & ImGuiColorEditFlags__ShowMask) == 0) - value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_ShowHSV); - if (flags & ImGuiColorEditFlags_ShowHEX || (flags & ImGuiColorEditFlags__ShowMask) == 0) - value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_ShowHEX); + if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags__DisplayMask) == 0) + value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV); + if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags__DisplayMask) == 0) + value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex); PopItemWidth(); } @@ -4536,16 +4536,17 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl return pressed; } +// Initialize/override default color options void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; - if ((flags & ImGuiColorEditFlags__ShowMask) == 0) - flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__ShowMask; + if ((flags & ImGuiColorEditFlags__DisplayMask) == 0) + flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DisplayMask; if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask; if ((flags & ImGuiColorEditFlags__PickerMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask; - IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__ShowMask))); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DisplayMask))); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected g.ColorEditOptions = flags; @@ -4578,7 +4579,7 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) { - bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__ShowMask); + bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__DisplayMask); bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask); if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) return; @@ -4586,9 +4587,9 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) ImGuiColorEditFlags opts = g.ColorEditOptions; if (allow_opt_inputs) { - if (RadioButton("RGB", (opts & ImGuiColorEditFlags_ShowRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__ShowMask) | ImGuiColorEditFlags_ShowRGB; - if (RadioButton("HSV", (opts & ImGuiColorEditFlags_ShowHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__ShowMask) | ImGuiColorEditFlags_ShowHSV; - if (RadioButton("HEX", (opts & ImGuiColorEditFlags_ShowHEX) != 0)) opts = (opts & ~ImGuiColorEditFlags__ShowMask) | ImGuiColorEditFlags_ShowHEX; + if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayRGB; + if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHSV; + if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHex; } if (allow_opt_datatype) { From ac47710db7ebaf2637de4b1517231d93e0e03baa Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 16:49:55 +0100 Subject: [PATCH 107/566] Internal: InputText: Tweaks to make PVS static analyzer relax a little with its false positive. --- imgui_widgets.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b1e17f12..0857f4b8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3284,7 +3284,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 ClearActiveID(); // Release focus when we click outside - if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) + if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560 clear_active_id = true; bool value_changed = false; @@ -3295,8 +3295,8 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :( if (is_readonly && state != NULL) { - const bool will_render_cursor = (g.ActiveId == id) || (state && user_scroll_active); - const bool will_render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || will_render_cursor); + const bool will_render_cursor = (g.ActiveId == id) || (user_scroll_active); + const bool will_render_selection = state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || will_render_cursor); if (will_render_cursor || will_render_selection) { const char* buf_end = NULL; From 525a53a86bdf6f5f1979e2e1ab5be95117f1bb38 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 17:26:18 +0100 Subject: [PATCH 108/566] Comments --- imgui.h | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/imgui.h b/imgui.h index f301ccf4..180db980 100644 --- a/imgui.h +++ b/imgui.h @@ -3,7 +3,7 @@ // See imgui.cpp file for documentation. // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. -// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. +// Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui /* @@ -26,7 +26,7 @@ Index of this file: #pragma once -// Configuration file (edit imconfig.h or define IMGUI_USER_CONFIG to your own filename) +// Configuration file with compile-time options (edit imconfig.h or define IMGUI_USER_CONFIG to your own filename) #ifdef IMGUI_USER_CONFIG #include IMGUI_USER_CONFIG #endif @@ -44,7 +44,7 @@ Index of this file: #include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp // Version -// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY00 then bounced up to XYY01 when release tagging happens) +// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.69 WIP" #define IMGUI_VERSION_NUM 16899 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) @@ -215,12 +215,12 @@ namespace ImGui // Demo, Debug, Information IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create about window. display Dear ImGui version, credits and build/system information. - IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics/debug window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). - IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.23" + IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.23" (essentially the compiled value for IMGUI_VERSION) // Styles IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) @@ -385,7 +385,7 @@ namespace ImGui // - Most widgets return true when the value has been changed or when pressed/selected IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text - IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding @@ -582,7 +582,7 @@ namespace ImGui // Drag and Drop // [BETA API] API may evolve! IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource() - IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t size, ImGuiCond cond = 0);// type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. + IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. @@ -610,9 +610,9 @@ namespace ImGui IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive). IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing. IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). - IMGUI_API bool IsAnyItemHovered(); - IMGUI_API bool IsAnyItemActive(); - IMGUI_API bool IsAnyItemFocused(); + IMGUI_API bool IsAnyItemHovered(); // is any item hovered? + IMGUI_API bool IsAnyItemActive(); // is any item active? + IMGUI_API bool IsAnyItemFocused(); // is any item focused? IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) IMGUI_API ImVec2 GetItemRectSize(); // get size of last item @@ -624,8 +624,8 @@ namespace ImGui IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text - IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances - IMGUI_API const char* GetStyleColorName(ImGuiCol idx); + IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. + IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) IMGUI_API ImGuiStorage* GetStateStorage(); IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); @@ -652,7 +652,7 @@ namespace ImGui IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. - IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // + IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse position at the time of opening popup we have BeginPopup() into IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position. This is locked and return 0.0f until the mouse moves past a distance threshold at least once. If lock_threshold < -1.0f uses io.MouseDraggingThreshold @@ -671,12 +671,12 @@ namespace ImGui // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. - IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); + IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. - // Memory Utilities + // Memory Allocators // - All those functions are not reliant on the current context. - // - If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again. + // - If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again because we use global storage for those. IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL); IMGUI_API void* MemAlloc(size_t size); IMGUI_API void MemFree(void* ptr); @@ -737,7 +737,7 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus - ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function. ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling) ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer. @@ -1059,7 +1059,7 @@ enum ImGuiCol_ // NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. enum ImGuiStyleVar_ { - // Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + // Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions) ImGuiStyleVar_Alpha, // float Alpha ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding ImGuiStyleVar_WindowRounding, // float WindowRounding From 736d3e265436b4bef715d67e63fda13f27858c28 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 18:16:03 +0100 Subject: [PATCH 109/566] DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. We are reusing function instances for larger types to reduce code size. (#643, #320, #708, #1011) --- docs/CHANGELOG.txt | 2 + imgui.h | 12 ++++- imgui_demo.cpp | 20 ++++++++ imgui_widgets.cpp | 125 ++++++++++++++++++++++++++++++++++----------- 4 files changed, 126 insertions(+), 33 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index caa78523..3501f907 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,8 @@ Breaking Changes: Other Changes: - Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigation to the menu layer. +- DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. + We are reusing function instances for larger types to reduce code size. (#643, #320, #708, #1011) - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) diff --git a/imgui.h b/imgui.h index 180db980..63132d46 100644 --- a/imgui.h +++ b/imgui.h @@ -150,6 +150,10 @@ typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Scalar data types +typedef char ImS8; // 8-bit signed integer == char +typedef unsigned char ImU8; // 8-bit unsigned integer +typedef short ImS16; // 16-bit signed integer +typedef unsigned short ImU16; // 16-bit unsigned integer typedef signed int ImS32; // 32-bit signed integer == int typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) #if defined(_MSC_VER) && !defined(__clang__) @@ -884,10 +888,14 @@ enum ImGuiDragDropFlags_ // A primary data type enum ImGuiDataType_ { + ImGuiDataType_S8, // char + ImGuiDataType_U8, // unsigned char + ImGuiDataType_S16, // short + ImGuiDataType_U16, // unsigned short ImGuiDataType_S32, // int ImGuiDataType_U32, // unsigned int - ImGuiDataType_S64, // long long, __int64 - ImGuiDataType_U64, // unsigned long long, unsigned __int64 + ImGuiDataType_S64, // long long / __int64 + ImGuiDataType_U64, // unsigned long long / unsigned __int64 ImGuiDataType_Float, // float ImGuiDataType_Double, // double ImGuiDataType_COUNT diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 09e36693..a9d1ce11 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1198,6 +1198,10 @@ static void ShowDemoWindowWidgets() ImS64 LLONG_MAX = 9223372036854775807LL; ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1); #endif + const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127; + const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255; + const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767; + const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535; const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN/2, s32_max = INT_MAX/2, s32_hi_a = INT_MAX/2 - 100, s32_hi_b = INT_MAX/2; const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX/2, u32_hi_a = UINT_MAX/2 - 100, u32_hi_b = UINT_MAX/2; const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2, s64_hi_a = LLONG_MAX/2 - 100, s64_hi_b = LLONG_MAX/2; @@ -1206,6 +1210,10 @@ static void ShowDemoWindowWidgets() const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0; // State + static char s8_v = 127; + static ImU8 u8_v = 255; + static short s16_v = 32767; + static ImU16 u16_v = 65535; static ImS32 s32_v = -1; static ImU32 u32_v = (ImU32)-1; static ImS64 s64_v = -1; @@ -1217,6 +1225,10 @@ static void ShowDemoWindowWidgets() static bool drag_clamp = false; ImGui::Text("Drags:"); ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); ImGui::SameLine(); ShowHelpMarker("As with every widgets in dear imgui, we never modify values unless there is a user interaction.\nYou can override the clamping limits by using CTRL+Click to input a value."); + ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); + ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); + ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); + ImGui::DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms"); ImGui::DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL); ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms"); ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); @@ -1227,6 +1239,10 @@ static void ShowDemoWindowWidgets() ImGui::DragScalar("drag double ^2", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", 2.0f); ImGui::Text("Sliders"); + ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); + ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u"); + ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d"); + ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u"); ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d"); ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d"); ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d"); @@ -1249,6 +1265,10 @@ static void ShowDemoWindowWidgets() static bool inputs_step = true; ImGui::Text("Inputs"); ImGui::Checkbox("Show step buttons", &inputs_step); + ImGui::InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d"); + ImGui::InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u"); + ImGui::InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d"); + ImGui::InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u"); ImGui::InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d"); ImGui::InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%08X", ImGuiInputTextFlags_CharsHexadecimal); ImGui::InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u"); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0857f4b8..9b3dfbd2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -74,22 +74,30 @@ Index of this file: //------------------------------------------------------------------------- // Those MIN/MAX values are not define because we need to point to them -static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000); -static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF) -static const ImU32 IM_U32_MIN = 0; -static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF) +static const char IM_S8_MIN = -128; +static const char IM_S8_MAX = 127; +static const unsigned char IM_U8_MIN = 0; +static const unsigned char IM_U8_MAX = 0xFF; +static const short IM_S16_MIN = -32768; +static const short IM_S16_MAX = 32767; +static const unsigned short IM_U16_MIN = 0; +static const unsigned short IM_U16_MAX = 0xFFFF; +static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000); +static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF) +static const ImU32 IM_U32_MIN = 0; +static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF) #ifdef LLONG_MIN -static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll); -static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll); +static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll); +static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll); #else -static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1; -static const ImS64 IM_S64_MAX = 9223372036854775807LL; +static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1; +static const ImS64 IM_S64_MAX = 9223372036854775807LL; #endif -static const ImU64 IM_U64_MIN = 0; +static const ImU64 IM_U64_MIN = 0; #ifdef ULLONG_MAX -static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull); +static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull); #else -static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); +static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); #endif //------------------------------------------------------------------------- @@ -1495,17 +1503,21 @@ struct ImGuiDataTypeInfo static const ImGuiDataTypeInfo GDataTypeInfo[] = { - { sizeof(int), "%d", "%d" }, - { sizeof(unsigned int), "%u", "%u" }, + { sizeof(char), "%d", "%d" }, // ImGuiDataType_S8 + { sizeof(unsigned char), "%u", "%u" }, + { sizeof(short), "%d", "%d" }, // ImGuiDataType_S16 + { sizeof(unsigned short), "%u", "%u" }, + { sizeof(int), "%d", "%d" }, // ImGuiDataType_S32 + { sizeof(unsigned int), "%u", "%u" }, #ifdef _MSC_VER - { sizeof(ImS64), "%I64d","%I64d" }, - { sizeof(ImU64), "%I64u","%I64u" }, + { sizeof(ImS64), "%I64d","%I64d" }, // ImGuiDataType_S64 + { sizeof(ImU64), "%I64u","%I64u" }, #else - { sizeof(ImS64), "%lld", "%lld" }, - { sizeof(ImU64), "%llu", "%llu" }, + { sizeof(ImS64), "%lld", "%lld" }, // ImGuiDataType_S64 + { sizeof(ImU64), "%llu", "%llu" }, #endif - { sizeof(float), "%f", "%f" }, // float are promoted to double in va_arg - { sizeof(double), "%f", "%lf" }, + { sizeof(float), "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) + { sizeof(double), "%f", "%lf" }, // ImGuiDataType_Double }; IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); @@ -1535,14 +1547,23 @@ static const char* PatchFormatStringFloatToInt(const char* fmt) static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format) { - if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32) // Signedness doesn't matter when pushing the argument + // Signedness doesn't matter when pushing integer arguments + if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32) return ImFormatString(buf, buf_size, format, *(const ImU32*)data_ptr); - if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) // Signedness doesn't matter when pushing the argument + if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) return ImFormatString(buf, buf_size, format, *(const ImU64*)data_ptr); if (data_type == ImGuiDataType_Float) return ImFormatString(buf, buf_size, format, *(const float*)data_ptr); if (data_type == ImGuiDataType_Double) return ImFormatString(buf, buf_size, format, *(const double*)data_ptr); + if (data_type == ImGuiDataType_S8) + return ImFormatString(buf, buf_size, format, *(const ImS8*)data_ptr); + if (data_type == ImGuiDataType_U8) + return ImFormatString(buf, buf_size, format, *(const ImU8*)data_ptr); + if (data_type == ImGuiDataType_S16) + return ImFormatString(buf, buf_size, format, *(const ImS16*)data_ptr); + if (data_type == ImGuiDataType_U16) + return ImFormatString(buf, buf_size, format, *(const ImU16*)data_ptr); IM_ASSERT(0); return 0; } @@ -1553,13 +1574,29 @@ static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* IM_ASSERT(op == '+' || op == '-'); switch (data_type) { + case ImGuiDataType_S8: + if (op == '+') *(ImS8*)output = *(const ImS8*)arg1 + *(const ImS8*)arg2; + else if (op == '-') *(ImS8*)output = *(const ImS8*)arg1 - *(const ImS8*)arg2; + return; + case ImGuiDataType_U8: + if (op == '+') *(ImU8*)output = *(const ImU8*)arg1 + *(const ImU8*)arg2; + else if (op == '-') *(ImU8*)output = *(const ImU8*)arg1 - *(const ImU8*)arg2; + return; + case ImGuiDataType_S16: + if (op == '+') *(ImS16*)output = *(const ImS16*)arg1 + *(const ImS16*)arg2; + else if (op == '-') *(ImS16*)output = *(const ImS16*)arg1 - *(const ImS16*)arg2; + return; + case ImGuiDataType_U16: + if (op == '+') *(ImU16*)output = *(const ImU16*)arg1 + *(const ImU16*)arg2; + else if (op == '-') *(ImU16*)output = *(const ImU16*)arg1 - *(const ImU16*)arg2; + return; case ImGuiDataType_S32: - if (op == '+') *(int*)output = *(const int*)arg1 + *(const int*)arg2; - else if (op == '-') *(int*)output = *(const int*)arg1 - *(const int*)arg2; + if (op == '+') *(ImS32*)output = *(const ImS32*)arg1 + *(const ImS32*)arg2; + else if (op == '-') *(ImS32*)output = *(const ImS32*)arg1 - *(const ImS32*)arg2; return; case ImGuiDataType_U32: - if (op == '+') *(unsigned int*)output = *(const unsigned int*)arg1 + *(const ImU32*)arg2; - else if (op == '-') *(unsigned int*)output = *(const unsigned int*)arg1 - *(const ImU32*)arg2; + if (op == '+') *(ImU32*)output = *(const ImU32*)arg1 + *(const ImU32*)arg2; + else if (op == '-') *(ImU32*)output = *(const ImU32*)arg1 - *(const ImU32*)arg2; return; case ImGuiDataType_S64: if (op == '+') *(ImS64*)output = *(const ImS64*)arg1 + *(const ImS64*)arg2; @@ -1614,6 +1651,7 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b if (format == NULL) format = GDataTypeInfo[data_type].ScanFmt; + // FIXME-LEGACY: The aim is to remove those operators and write a proper expression evaluator at some point.. int arg1i = 0; if (data_type == ImGuiDataType_S32) { @@ -1628,12 +1666,6 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b else if (op == '/') { if (sscanf(buf, "%f", &arg1f) && arg1f != 0.0f) *v = (int)(arg0i / arg1f); } // Divide else { if (sscanf(buf, format, &arg1i) == 1) *v = arg1i; } // Assign constant } - else if (data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) - { - // Assign constant - // FIXME: We don't bother handling support for legacy operators since they are a little too crappy. Instead we may implement a proper expression evaluator in the future. - sscanf(buf, format, data_ptr); - } else if (data_type == ImGuiDataType_Float) { // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in @@ -1663,6 +1695,29 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide else { *v = arg1f; } // Assign constant } + else if (data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) + { + // All other types assign constant + // We don't bother handling support for legacy operators since they are a little too crappy. Instead we will later implement a proper expression evaluator in the future. + sscanf(buf, format, data_ptr); + } + else + { + // Small types need a 32-bit buffer to receive the result from scanf() + int v32; + sscanf(buf, format, &v32); + if (data_type == ImGuiDataType_S8) + *(ImS8*)data_ptr = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX); + else if (data_type == ImGuiDataType_U8) + *(ImU8*)data_ptr = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX); + else if (data_type == ImGuiDataType_S16) + *(ImS16*)data_ptr = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX); + else if (data_type == ImGuiDataType_U16) + *(ImU16*)data_ptr = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX); + else + IM_ASSERT(0); + } + return memcmp(data_backup, data_ptr, GDataTypeInfo[data_type].Size) != 0; } @@ -1845,6 +1900,10 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_s switch (data_type) { + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS8*) v_min : IM_S8_MIN, v_max ? *(const ImS8*)v_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU8*) v_min : IM_U8_MIN, v_max ? *(const ImU8*)v_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS16*)v_min : IM_S16_MIN, v_max ? *(const ImS16*)v_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU16*)v_min : IM_U16_MIN, v_max ? *(const ImU16*)v_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)v = (ImU16)v32; return r; } case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)v, v_speed, v_min ? *(const ImS32* )v_min : IM_S32_MIN, v_max ? *(const ImS32* )v_max : IM_S32_MAX, format, power, flags); case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)v, v_speed, v_min ? *(const ImU32* )v_min : IM_U32_MIN, v_max ? *(const ImU32* )v_max : IM_U32_MAX, format, power, flags); case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)v, v_speed, v_min ? *(const ImS64* )v_min : IM_S64_MIN, v_max ? *(const ImS64* )v_max : IM_S64_MAX, format, power, flags); @@ -2269,6 +2328,10 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type { switch (data_type) { + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)v_min, *(const ImS8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)v_min, *(const ImU8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)v_min, *(const ImS16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)v_min, *(const ImU16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)v = (ImU16)v32; return r; } case ImGuiDataType_S32: IM_ASSERT(*(const ImS32*)v_min >= IM_S32_MIN/2 && *(const ImS32*)v_max <= IM_S32_MAX/2); return SliderBehaviorT(bb, id, data_type, (ImS32*)v, *(const ImS32*)v_min, *(const ImS32*)v_max, format, power, flags, out_grab_bb); From f02705fbaa22cad03f0b033d901f8b232dfb1ce5 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Feb 2019 18:59:17 +0100 Subject: [PATCH 110/566] InputInt, InputScalar: +/- buttons now respects the natural type limits instead of overflowing or underflowing the value. --- docs/CHANGELOG.txt | 2 ++ imgui_internal.h | 5 ++++- imgui_widgets.cpp | 41 ++++++++++++++++++++--------------------- 3 files changed, 26 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3501f907..ea012ef4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,8 @@ Other Changes: - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) +- InputInt, InputScalar: +/- buttons now respects the natural type limits instead of + overflowing or underflowing the value. - InputText: Fixed an edge case crash that would happen if another widget sharing the same ID is being swapped with an InputText that has yet to be activated. - InputText: Fixed various display corruption related to swapping the underlying buffer while diff --git a/imgui_internal.h b/imgui_internal.h index 40e10748..fdc55aad 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -225,12 +225,15 @@ static inline double ImAtof(const char* s) static inline float ImFloorStd(float x) { return floorf(x); } // we already uses our own ImFloor() { return (float)(int)v } internally so the standard one wrapper is named differently (it's used by stb_truetype) static inline float ImCeil(float x) { return ceilf(x); } #endif -// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support for variety of types: signed/unsigned int/long long float/double, using templates here but we could also redefine them 6 times +// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support for variety of types: signed/unsigned int/long long float/double +// (Exceptionally using templates here but we could also redefine them for variety of types) template static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } template static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } template static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } template static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } template static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } +template static inline 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 static inline 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; } // - Misc maths helpers static 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); } static 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 9b3dfbd2..dc8c7cf2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1568,51 +1568,50 @@ static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType da return 0; } -// FIXME: Adding support for clamping on boundaries of the data type would be nice. static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2) { IM_ASSERT(op == '+' || op == '-'); switch (data_type) { case ImGuiDataType_S8: - if (op == '+') *(ImS8*)output = *(const ImS8*)arg1 + *(const ImS8*)arg2; - else if (op == '-') *(ImS8*)output = *(const ImS8*)arg1 - *(const ImS8*)arg2; + if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } + if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } return; case ImGuiDataType_U8: - if (op == '+') *(ImU8*)output = *(const ImU8*)arg1 + *(const ImU8*)arg2; - else if (op == '-') *(ImU8*)output = *(const ImU8*)arg1 - *(const ImU8*)arg2; + if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } + if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } return; case ImGuiDataType_S16: - if (op == '+') *(ImS16*)output = *(const ImS16*)arg1 + *(const ImS16*)arg2; - else if (op == '-') *(ImS16*)output = *(const ImS16*)arg1 - *(const ImS16*)arg2; + if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } + if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } return; case ImGuiDataType_U16: - if (op == '+') *(ImU16*)output = *(const ImU16*)arg1 + *(const ImU16*)arg2; - else if (op == '-') *(ImU16*)output = *(const ImU16*)arg1 - *(const ImU16*)arg2; + if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } + if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } return; case ImGuiDataType_S32: - if (op == '+') *(ImS32*)output = *(const ImS32*)arg1 + *(const ImS32*)arg2; - else if (op == '-') *(ImS32*)output = *(const ImS32*)arg1 - *(const ImS32*)arg2; + if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } + if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } return; case ImGuiDataType_U32: - if (op == '+') *(ImU32*)output = *(const ImU32*)arg1 + *(const ImU32*)arg2; - else if (op == '-') *(ImU32*)output = *(const ImU32*)arg1 - *(const ImU32*)arg2; + if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } + if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } return; case ImGuiDataType_S64: - if (op == '+') *(ImS64*)output = *(const ImS64*)arg1 + *(const ImS64*)arg2; - else if (op == '-') *(ImS64*)output = *(const ImS64*)arg1 - *(const ImS64*)arg2; + if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } + if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } return; case ImGuiDataType_U64: - if (op == '+') *(ImU64*)output = *(const ImU64*)arg1 + *(const ImU64*)arg2; - else if (op == '-') *(ImU64*)output = *(const ImU64*)arg1 - *(const ImU64*)arg2; + if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } + if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } return; case ImGuiDataType_Float: - if (op == '+') *(float*)output = *(const float*)arg1 + *(const float*)arg2; - else if (op == '-') *(float*)output = *(const float*)arg1 - *(const float*)arg2; + if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; } + if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; } return; case ImGuiDataType_Double: - if (op == '+') *(double*)output = *(const double*)arg1 + *(const double*)arg2; - else if (op == '-') *(double*)output = *(const double*)arg1 - *(const double*)arg2; + if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; } + if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; } return; case ImGuiDataType_COUNT: break; } From 1d0b4df3d95698b117fbe6172f883867f4722422 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 28 Feb 2019 16:59:01 +0100 Subject: [PATCH 111/566] Misc: Asserting in NewFrame() if style.WindowMinSize is zero or smaller than (1.0f,1.0f). Internal: ImHash functions tweaks. Added InputText() to query status section. --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 15 ++++++++------- imgui_demo.cpp | 11 +++++++---- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ea012ef4..9a3e42af 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,7 +41,7 @@ Breaking Changes: Other Changes: -- Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigation to the menu layer. +- Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigating to the menu layer. - DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. We are reusing function instances for larger types to reduce code size. (#643, #320, #708, #1011) - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when @@ -63,6 +63,7 @@ Other Changes: - Log/Capture: Fixed LogXXX functions 'auto_open_depth' parameter being treated as an absolute tree depth instead of a relative one. - Log/Capture: Fixed CollapsingHeader trailing ascii representation being "#" instead of "##". +- Misc: Asserting in NewFrame() if style.WindowMinSize is zero or smaller than (1.0f,1.0f). - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) - Examples: Allegro: Added support for touch events (emulating mouse). (#2219) [@dos1] diff --git a/imgui.cpp b/imgui.cpp index 28c1277a..1a8f1f2c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1480,27 +1480,27 @@ ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed) // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build) // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. -ImU32 ImHashStr(const char* data, size_t data_size, ImU32 seed) +ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed) { seed = ~seed; ImU32 crc = seed; - const unsigned char* src = (const unsigned char*)data; + const unsigned char* data = (const unsigned char*)data_p; const ImU32* crc32_lut = GCrc32LookupTable; if (data_size != 0) { while (data_size-- != 0) { - unsigned char c = *src++; - if (c == '#' && src[0] == '#' && src[1] == '#') + unsigned char c = *data++; + if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } else { - while (unsigned char c = *src++) + while (unsigned char c = *data++) { - if (c == '#' && src[0] == '#' && src[1] == '#') + if (c == '#' && data[0] == '#' && data[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } @@ -3368,12 +3368,13 @@ void ImGui::NewFrame() // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) IM_ASSERT(g.Initialized); IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); + IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!"); - IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); + IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a9d1ce11..9ef8fa64 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1460,20 +1460,23 @@ static void ShowDemoWindowWidgets() static int item_type = 1; static bool b = false; static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; + static char str[16] = {}; ImGui::RadioButton("Text", &item_type, 0); ImGui::RadioButton("Button", &item_type, 1); ImGui::RadioButton("Checkbox", &item_type, 2); ImGui::RadioButton("SliderFloat", &item_type, 3); - ImGui::RadioButton("ColorEdit4", &item_type, 4); - ImGui::RadioButton("ListBox", &item_type, 5); + ImGui::RadioButton("InputText", &item_type, 4); + ImGui::RadioButton("ColorEdit4", &item_type, 5); + ImGui::RadioButton("ListBox", &item_type, 6); ImGui::Separator(); bool ret = false; if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button if (item_type == 2) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox if (item_type == 3) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item - if (item_type == 4) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) - if (item_type == 5) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } + if (item_type == 4) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) + if (item_type == 5) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 6) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } ImGui::BulletText( "Return value = %d\n" "IsItemFocused() = %d\n" From 1c67d09c0bd99a1fe9122ffa478e4b4455573b59 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 1 Mar 2019 00:05:39 +0100 Subject: [PATCH 112/566] ColorPicker: Fix assertion when running in a collapsed window and dragging its title bar (#2389) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9a3e42af..5d04377b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,8 @@ Other Changes: - InputText: Fixed various display corruption related to swapping the underlying buffer while a input widget is active (both for writable and read-only paths). Often they would manifest when manipulating the scrollbar of a multi-line input text. +- ColorPicker: Fixed a bug/assertion when displaying a color picker in a collapsed window + while dragging its title bar. (#2389) - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dc8c7cf2..dbb98ab3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4219,8 +4219,10 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - ImDrawList* draw_list = window->DrawList; + if (window->SkipItems) + return false; + ImDrawList* draw_list = window->DrawList; ImGuiStyle& style = g.Style; ImGuiIO& io = g.IO; From 7a536f1bd2138c47933f8c26f49ebf9e45139bdc Mon Sep 17 00:00:00 2001 From: Richard Mitton Date: Fri, 1 Mar 2019 18:55:55 -0800 Subject: [PATCH 113/566] Examples + Viewport: GLFW: context wasn't set when using multiple windows. (#2392) --- examples/imgui_impl_glfw.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 45b2d0e7..8fae67cc 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -602,8 +602,11 @@ static void ImGui_ImplGlfw_RenderWindow(ImGuiViewport* viewport, void*) static void ImGui_ImplGlfw_SwapBuffers(ImGuiViewport* viewport, void*) { ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData; - if (g_ClientApi == GlfwClientApi_OpenGL) + if (g_ClientApi == GlfwClientApi_OpenGL) + { + glfwMakeContextCurrent(data->Window); glfwSwapBuffers(data->Window); + } } //-------------------------------------------------------------------------------------------------------- From 9d1a392d7d0aa8c55047c90ae2e740561369f1c1 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 3 Mar 2019 23:14:30 +0100 Subject: [PATCH 114/566] Examples: OpenGL: Comments about versions and loaders. (#2393, #2351) --- examples/README.txt | 4 ++-- examples/imgui_impl_opengl3.cpp | 31 ++++++++++++++++--------------- examples/imgui_impl_opengl3.h | 21 +++++++++++---------- 3 files changed, 29 insertions(+), 27 deletions(-) diff --git a/examples/README.txt b/examples/README.txt index 017af6ee..a058601b 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -111,8 +111,8 @@ List of Renderer Bindings in this repository: imgui_impl_dx11.cpp ; DirectX11 imgui_impl_dx12.cpp ; DirectX12 imgui_impl_metal.mm ; Metal (with ObjC) - imgui_impl_opengl2.cpp ; OpenGL2 (legacy, fixed pipeline <- don't use with modern OpenGL context) - imgui_impl_opengl3.cpp ; OpenGL3, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) + imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context) + imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) imgui_impl_vulkan.cpp ; Vulkan List of high-level Frameworks Bindings in this repository: (combine Platform + Renderer) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 9a53d3c6..f48ad60b 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -1,6 +1,7 @@ -// dear imgui: Renderer for OpenGL3 / OpenGL ES2 / OpenGL ES3 (modern OpenGL with shaders / programmatic pipeline) +// dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline +// - Desktop GL: 3.x 4.x +// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) -// (Note: We are using GL3W as a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. @@ -39,17 +40,17 @@ // version version string //---------------------------------------- // 2.0 110 "#version 110" -// 2.1 120 -// 3.0 130 -// 3.1 140 +// 2.1 110 "#version 120" +// 3.0 130 "#version 130" +// 3.1 140 "#version 140" // 3.2 150 "#version 150" -// 3.3 330 -// 4.0 400 +// 3.3 330 "#version 330 core" +// 4.0 400 "#version 400 core" // 4.1 410 "#version 410 core" -// 4.2 420 -// 4.3 430 -// ES 2.0 100 "#version 100" -// ES 3.0 300 "#version 300 es" +// 4.2 420 "#version 410 core" +// 4.3 430 "#version 430 core" +// ES 2.0 100 "#version 100" = WebGL 1.0 +// ES 3.0 300 "#version 300 es" = WebGL 2.0 //---------------------------------------- #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) @@ -78,10 +79,10 @@ // OpenGL ES 3 #include // Use GL ES 3 #else -// Regular OpenGL -// About OpenGL function loaders: modern OpenGL doesn't have a standard header file and requires individual function pointers to be loaded manually. -// Helper libraries are often used for this purpose! Here we are supporting a few common ones: gl3w, glew, glad. -// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. +// About Desktop OpenGL function loaders: +// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. +// Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad). +// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) #include #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index 0be9dcd8..741a35d4 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -1,6 +1,7 @@ -// dear imgui: Renderer for OpenGL3 / OpenGL ES2 / OpenGL ES3 (modern OpenGL with shaders / programmatic pipeline) +// dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline +// - Desktop GL: 3.x 4.x +// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) -// (Note: We are using GL3W as a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. @@ -9,19 +10,19 @@ // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui -// About OpenGL function loaders: -// About OpenGL function loaders: modern OpenGL doesn't have a standard header file and requires individual function pointers to be loaded manually. -// Helper libraries are often used for this purpose! Here we are supporting a few common ones: gl3w, glew, glad. -// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. +// About Desktop OpenGL function loaders: +// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. +// Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad). +// You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. // About GLSL version: -// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string. -// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" -// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. +// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string. +// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" +// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. #pragma once -// Set default OpenGL loader to be gl3w +// Set default OpenGL3 loader to be gl3w #if !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \ From beb3062dc5da2b8f6057ff57ea16a6246ba32b99 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 3 Mar 2019 23:32:40 +0100 Subject: [PATCH 115/566] Examples: OpenGL: Fix to be able to run on ES 2.0 / WebGL 1.0. [@rmitton, @gabrielcuvillier] --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_opengl3.cpp | 40 ++++++++++++++++++++++++++------- examples/imgui_impl_opengl3.h | 4 ++++ 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5d04377b..394effcd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,7 @@ Other Changes: tree depth instead of a relative one. - Log/Capture: Fixed CollapsingHeader trailing ascii representation being "#" instead of "##". - Misc: Asserting in NewFrame() if style.WindowMinSize is zero or smaller than (1.0f,1.0f). +- Examples: OpenGL: Fix to be able to run on ES 2.0 / WebGL 1.0. [@rmitton, @gabrielcuvillier] - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) - Examples: Allegro: Added support for touch events (emulating mouse). (#2219) [@dos1] diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index f48ad60b..01cfa398 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). // 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450). @@ -69,14 +70,18 @@ #include "TargetConditionals.h" #endif -// iOS, Android and Emscripten can use GL ES 3 -// Call ImGui_ImplOpenGL3_Init() with "#version 300 es" -#if (defined(__APPLE__) && TARGET_OS_IOS) || (defined(__ANDROID__)) || (defined(__EMSCRIPTEN__)) -#define USE_GL_ES3 +// Auto-detect GL version +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) +#if (defined(__APPLE__) && TARGET_OS_IOS) || (defined(__ANDROID__)) +#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" +#elif defined(__EMSCRIPTEN__) +#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" +#endif #endif -#ifdef USE_GL_ES3 -// OpenGL ES 3 +#if defined(IMGUI_IMPL_OPENGL_ES2) +#include +#elif defined(IMGUI_IMPL_OPENGL_ES3) #include // Use GL ES 3 #else // About Desktop OpenGL function loaders: @@ -109,7 +114,10 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) io.BackendRendererName = "imgui_impl_opengl3"; // Store GLSL version string so we can refer to it later in case we recreate shaders. Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure. -#ifdef USE_GL_ES3 +#if defined(IMGUI_IMPL_OPENGL_ES2) + if (glsl_version == NULL) + glsl_version = "#version 100"; +#elif defined(IMGUI_IMPL_OPENGL_ES3) if (glsl_version == NULL) glsl_version = "#version 300 es"; #else @@ -154,7 +162,9 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler); #endif GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); +#ifndef IMGUI_IMPL_OPENGL_ES2 GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); +#endif #ifdef GL_POLYGON_MODE GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); #endif @@ -208,11 +218,14 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) #ifdef GL_SAMPLER_BINDING glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. #endif + +#ifndef IMGUI_IMPL_OPENGL_ES2 // Recreate the VAO every time // (This is to easily allow multiple GL contexts. VAO are not shared among GL contexts, and we don't track creation/deletion of windows so we don't have an obvious key to use to cache them.) GLuint vao_handle = 0; glGenVertexArrays(1, &vao_handle); glBindVertexArray(vao_handle); +#endif glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glEnableVertexAttribArray(g_AttribLocationPosition); glEnableVertexAttribArray(g_AttribLocationUV); @@ -270,7 +283,9 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) idx_buffer_offset += pcmd->ElemCount * sizeof(ImDrawIdx); } } +#ifndef IMGUI_IMPL_OPENGL_ES2 glDeleteVertexArrays(1, &vao_handle); +#endif // Restore modified GL state glUseProgram(last_program); @@ -279,7 +294,9 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) glBindSampler(0, last_sampler); #endif glActiveTexture(last_active_texture); +#ifndef IMGUI_IMPL_OPENGL_ES2 glBindVertexArray(last_vertex_array); +#endif glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); @@ -309,7 +326,9 @@ bool ImGui_ImplOpenGL3_CreateFontsTexture() glBindTexture(GL_TEXTURE_2D, g_FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +#ifdef GL_UNPACK_ROW_LENGTH glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); +#endif glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier @@ -371,10 +390,13 @@ static bool CheckProgram(GLuint handle, const char* desc) bool ImGui_ImplOpenGL3_CreateDeviceObjects() { // Backup GL state - GLint last_texture, last_array_buffer, last_vertex_array; + GLint last_texture, last_array_buffer; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); +#ifndef IMGUI_IMPL_OPENGL_ES2 + GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); +#endif // Parse GLSL version string int glsl_version = 130; @@ -538,7 +560,9 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); +#ifndef IMGUI_IMPL_OPENGL_ES2 glBindVertexArray(last_vertex_array); +#endif return true; } diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index 741a35d4..9fe2a88d 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -22,6 +22,10 @@ #pragma once +// Specific OpenGL versions +//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten +//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android + // Set default OpenGL3 loader to be gl3w #if !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \ From 96b13760d450b251e823a09ba2409f9f83ec2124 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 Mar 2019 16:10:51 +0100 Subject: [PATCH 116/566] Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered behind every other windows. (#2391) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 19 +++++++++++++++++-- imgui.h | 3 ++- imgui_internal.h | 5 ++++- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 394effcd..69607949 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ Breaking Changes: Other Changes: +- Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered + behind every other windows. (#2391) - Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigating to the menu layer. - DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. We are reusing function instances for larger types to reduce code size. (#643, #320, #708, #1011) diff --git a/imgui.cpp b/imgui.cpp index 1a8f1f2c..fea25c02 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -874,7 +874,8 @@ CODE A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags. (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse) Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows. + - You can call ImGui::GetBackgroundDrawList() or ImGui::GetOverlayDrawList() and use those draw list to display contents + behind or over every other imgui windows. - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data. @@ -3067,9 +3068,14 @@ int ImGui::GetFrameCount() return GImGui->FrameCount; } +ImDrawList* ImGui::GetBackgroundDrawList() +{ + return &GImGui->BackgroundDrawList; +} + static ImDrawList* GetOverlayDrawList(ImGuiWindow*) { - // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'viewport' branches. + // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. return &GImGui->OverlayDrawList; } @@ -3422,6 +3428,11 @@ void ImGui::NewFrame() g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; + g.BackgroundDrawList.Clear(); + g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); + g.BackgroundDrawList.PushClipRectFullScreen(); + g.BackgroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); + g.OverlayDrawList.Clear(); g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); g.OverlayDrawList.PushClipRectFullScreen(); @@ -3603,6 +3614,7 @@ void ImGui::Shutdown(ImGuiContext* context) g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); + g.BackgroundDrawList.ClearFreeMemory(); g.OverlayDrawList.ClearFreeMemory(); g.PrivateClipboard.clear(); g.InputTextState.ClearFreeMemory(); @@ -3860,6 +3872,9 @@ void ImGui::Render() // Gather ImDrawList to render (for each active window) g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0; g.DrawDataBuilder.Clear(); + if (!g.BackgroundDrawList.VtxBuffer.empty()) + AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList); + ImGuiWindow* windows_to_render_front_most[2]; windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL; diff --git a/imgui.h b/imgui.h index 63132d46..bcc6fe09 100644 --- a/imgui.h +++ b/imgui.h @@ -627,7 +627,8 @@ namespace ImGui IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. - IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text + IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. + IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) diff --git a/imgui_internal.h b/imgui_internal.h index fdc55aad..0929e153 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -888,6 +888,7 @@ struct ImGuiContext ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user ImDrawDataBuilder DrawDataBuilder; float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) + ImDrawList BackgroundDrawList; ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays ImGuiMouseCursor MouseCursor; @@ -962,7 +963,7 @@ struct ImGuiContext int WantTextInputNextFrame; char TempBuffer[1024*3+1]; // Temporary text buffer - ImGuiContext(ImFontAtlas* shared_font_atlas) : OverlayDrawList(NULL) + ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(NULL), OverlayDrawList(NULL) { Initialized = false; FrameScopeActive = FrameScopePushedImplicitWindow = false; @@ -1030,6 +1031,8 @@ struct ImGuiContext NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; DimBgRatio = 0.0f; + BackgroundDrawList._Data = &DrawListSharedData; + BackgroundDrawList._OwnerName = "##Background"; // Give it a name for debugging OverlayDrawList._Data = &DrawListSharedData; OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging MouseCursor = ImGuiMouseCursor_Arrow; From 94e794f81be1bd31c843b4fa94f5235e6e97e366 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 Mar 2019 16:20:32 +0100 Subject: [PATCH 117/566] Renamed GetOverlayDrawList() to GetForegroundDrawList() for consistency. Kept redirection function (will obsolete). (#2391) Demo: Using GetBackgroundDrawList() and GetForegroundDrawList() in "Custom Rendering" demo. --- docs/CHANGELOG.txt | 4 +- imgui.cpp | 75 +++++++++--------- imgui.h | 4 +- imgui_demo.cpp | 184 +++++++++++++++++++++++++-------------------- imgui_internal.h | 10 +-- imgui_widgets.cpp | 2 +- 6 files changed, 156 insertions(+), 123 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 69607949..1062c86e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,10 +38,11 @@ Breaking Changes: - Renamed ColorEdit/ColorPicker's ImGuiColorEditFlags_RGB/_HSV/_HEX flags to respectively ImGuiColorEditFlags_DisplayRGB/_DisplayHSV/_DisplayHex. This is anticipation of adding new flags to ColorEdit/ColorPicker functions which would make those ambiguous. (#2384) [@haldean] +- Renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). (#2391) Other Changes: -- Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered +- Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered behind every other windows. (#2391) - Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigating to the menu layer. - DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. @@ -68,6 +69,7 @@ Other Changes: tree depth instead of a relative one. - Log/Capture: Fixed CollapsingHeader trailing ascii representation being "#" instead of "##". - Misc: Asserting in NewFrame() if style.WindowMinSize is zero or smaller than (1.0f,1.0f). +- Demo: Using GetBackgroundDrawList() and GetForegroundDrawList() in "Custom Rendering" demo. - Examples: OpenGL: Fix to be able to run on ES 2.0 / WebGL 1.0. [@rmitton, @gabrielcuvillier] - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) diff --git a/imgui.cpp b/imgui.cpp index fea25c02..099c9178 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -364,6 +364,7 @@ CODE When you are not sure about a 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. + - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). @@ -874,8 +875,8 @@ CODE A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags. (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse) Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - - You can call ImGui::GetBackgroundDrawList() or ImGui::GetOverlayDrawList() and use those draw list to display contents - behind or over every other imgui windows. + - You can call ImGui::GetBackgroundDrawList() or ImGui::GetForegroundDrawList() and use those draw list to display + contents behind or over every other imgui windows. - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data. @@ -3073,15 +3074,15 @@ ImDrawList* ImGui::GetBackgroundDrawList() return &GImGui->BackgroundDrawList; } -static ImDrawList* GetOverlayDrawList(ImGuiWindow*) +static ImDrawList* GetForegroundDrawList(ImGuiWindow*) { // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. - return &GImGui->OverlayDrawList; + return &GImGui->ForegroundDrawList; } -ImDrawList* ImGui::GetOverlayDrawList() +ImDrawList* ImGui::GetForegroundDrawList() { - return &GImGui->OverlayDrawList; + return &GImGui->ForegroundDrawList; } ImDrawListSharedData* ImGui::GetDrawListSharedData() @@ -3433,10 +3434,10 @@ void ImGui::NewFrame() g.BackgroundDrawList.PushClipRectFullScreen(); g.BackgroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); - g.OverlayDrawList.Clear(); - g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); - g.OverlayDrawList.PushClipRectFullScreen(); - g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); + g.ForegroundDrawList.Clear(); + g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); + g.ForegroundDrawList.PushClipRectFullScreen(); + g.ForegroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); // Mark rendering data as invalid to prevent user who may have a handle on it to use it. g.DrawData.Clear(); @@ -3615,7 +3616,7 @@ void ImGui::Shutdown(ImGuiContext* context) g.BeginPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); g.BackgroundDrawList.ClearFreeMemory(); - g.OverlayDrawList.ClearFreeMemory(); + g.ForegroundDrawList.ClearFreeMemory(); g.PrivateClipboard.clear(); g.InputTextState.ClearFreeMemory(); @@ -3891,10 +3892,10 @@ void ImGui::Render() // Draw software mouse cursor if requested if (g.IO.MouseDrawCursor) - RenderMouseCursor(&g.OverlayDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor); + RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor); - if (!g.OverlayDrawList.VtxBuffer.empty()) - AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList); + if (!g.ForegroundDrawList.VtxBuffer.empty()) + AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList); // Setup ImDrawData structure for end-user SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData); @@ -4739,7 +4740,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y); bool hovered, held; ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); - //GetOverlayDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); + //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); if (hovered || held) g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE; @@ -4764,7 +4765,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au bool hovered, held; ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren); - //GetOverlayDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); + //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held) { g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; @@ -7037,8 +7038,8 @@ ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow*) ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy) { ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size); - //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); - //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); + //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); + //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); // Combo Box policy (we want a connecting edge) if (policy == ImGuiPopupPositionPolicy_ComboBox) @@ -7237,7 +7238,7 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max)) { ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]); - ImDrawList* draw_list = ImGui::GetOverlayDrawList(window); + ImDrawList* draw_list = ImGui::GetForegroundDrawList(window); draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100)); draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200)); draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150)); @@ -7249,7 +7250,7 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) if (quadrant == g.NavMoveDir) { ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center); - ImDrawList* draw_list = ImGui::GetOverlayDrawList(window); + ImDrawList* draw_list = ImGui::GetForegroundDrawList(window); draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200)); draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf); } @@ -7555,7 +7556,7 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) { ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1)); - //GetOverlayDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] + //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] if (window_rect.Contains(item_rect)) return; @@ -7845,11 +7846,15 @@ static void ImGui::NavUpdate() g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x); g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x; IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem(). - //g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG] + //GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG] g.NavScoringCount = 0; #if IMGUI_DEBUG_NAV_RECTS - if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) GetOverlayDrawList(g.NavWindow)->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] - if (g.NavWindow) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); GetOverlayDrawList(g.NavWindow)->AddCircleFilled(p, 3.0f, col); GetOverlayDrawList(g.NavWindow)->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } + if (g.NavWindow) + { + ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow); + if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] + if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } + } #endif } @@ -9356,9 +9361,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; } - ImDrawList* overlay_draw_list = GetOverlayDrawList(window); // Render additional visuals into the top-most draw list + ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list if (window && IsItemHovered()) - overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!node_open) return; @@ -9380,8 +9385,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImRect vtxs_rect; for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); - clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); - vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); + clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); + vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); } if (!pcmd_node_open) continue; @@ -9405,10 +9410,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Selectable(buf, false); if (ImGui::IsItemHovered()) { - ImDrawListFlags backup_flags = overlay_draw_list->Flags; - overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles. - overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f); - overlay_draw_list->Flags = backup_flags; + ImDrawListFlags backup_flags = fg_draw_list->Flags; + fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles. + fg_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f); + fg_draw_list->Flags = backup_flags; } } ImGui::TreePop(); @@ -9545,9 +9550,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); float font_size = ImGui::GetFontSize() * 2; - ImDrawList* overlay_draw_list = GetOverlayDrawList(window); - overlay_draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); - overlay_draw_list->AddText(NULL, font_size, window->Pos, IM_COL32(255, 255, 255, 255), buf); + ImDrawList* fg_draw_list = GetForegroundDrawList(window); + fg_draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); + fg_draw_list->AddText(NULL, font_size, window->Pos, IM_COL32(255, 255, 255, 255), buf); } } ImGui::End(); diff --git a/imgui.h b/imgui.h index bcc6fe09..eeb9b81d 100644 --- a/imgui.h +++ b/imgui.h @@ -628,7 +628,7 @@ namespace ImGui IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. - IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. + IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances. IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) @@ -1500,6 +1500,8 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.69 (from Mar 2019) + static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.66 (from Sep 2018) static inline void SetScrollHere(float center_ratio=0.5f){ SetScrollHereY(center_ratio); } // OBSOLETED in 1.63 (between Aug 2018 and Sept 2018) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9ef8fa64..080d92bd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3974,97 +3974,121 @@ static void ShowExampleAppCustomRendering(bool* p_open) // In this example we are not using the maths operators! ImDrawList* draw_list = ImGui::GetWindowDrawList(); - // Primitives - ImGui::Text("Primitives"); - static float sz = 36.0f; - static float thickness = 4.0f; - static ImVec4 col = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); - ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f"); - ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f"); - ImGui::ColorEdit4("Color", &col.x); + if (ImGui::BeginTabBar("##TabBar")) { - const ImVec2 p = ImGui::GetCursorScreenPos(); - const ImU32 col32 = ImColor(col); - float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f; - for (int n = 0; n < 2; n++) + // Primitives + if (ImGui::BeginTabItem("Primitives")) { - // First line uses a thickness of 1.0, second line uses the configurable thickness - float th = (n == 0) ? 1.0f : thickness; - draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 6, th); x += sz+spacing; // Hexagon - draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, th); x += sz+spacing; // Circle - draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ImDrawCornerFlags_All, th); x += sz+spacing; - draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_All, th); x += sz+spacing; - draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight, th); x += sz+spacing; - draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, th); x += sz+spacing; - draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y ), col32, th); x += sz+spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x, y+sz), col32, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, th); x += sz+spacing; // Diagonal line - draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x+sz*1.3f,y+sz*0.3f), ImVec2(x+sz-sz*1.3f,y+sz-sz*0.3f), ImVec2(x+sz, y+sz), col32, th); - x = p.x + 4; - y += sz+spacing; - } - draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 6); x += sz+spacing; // Hexagon - draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 32); x += sz+spacing; // Circle - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32); x += sz+spacing; - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing; - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight); x += sz+spacing; - draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing; - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+thickness), col32); x += sz+spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+thickness, y+sz), col32); x += spacing+spacing; // Vertical line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+1, y+1), col32); x += sz; // Pixel (faster than AddLine) - 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)); - ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3)); - } - ImGui::Separator(); - { - static ImVector points; - static bool adding_line = false; - ImGui::Text("Canvas example"); - if (ImGui::Button("Clear")) points.clear(); - if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } - ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); - - // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() - // But you can also draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). - // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). - ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! - ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available - if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; - if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; - draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(50, 50, 50, 255), IM_COL32(50, 50, 60, 255), IM_COL32(60, 60, 70, 255), IM_COL32(50, 50, 60, 255)); - draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(255, 255, 255, 255)); - - bool adding_preview = false; - ImGui::InvisibleButton("canvas", canvas_size); - ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); - if (adding_line) - { - adding_preview = true; - points.push_back(mouse_pos_in_canvas); - if (!ImGui::IsMouseDown(0)) - adding_line = adding_preview = false; + static float sz = 36.0f; + static float thickness = 4.0f; + static ImVec4 col = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f"); + ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f"); + ImGui::ColorEdit4("Color", &col.x); + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col32 = ImColor(col); + float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f; + for (int n = 0; n < 2; n++) + { + // First line uses a thickness of 1.0, second line uses the configurable thickness + float th = (n == 0) ? 1.0f : thickness; + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6, th); x += sz + spacing; // Hexagon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 20, th); x += sz + spacing; // Circle + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 0.0f, ImDrawCornerFlags_All, th); x += sz + spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_All, th); x += sz + spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight, th); x += sz + spacing; + draw_list->AddTriangle(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32, th); x += sz + spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col32, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col32, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, th); x += sz + spacing; // Diagonal line + draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz*1.3f, y + sz*0.3f), ImVec2(x + sz - sz*1.3f, y + sz - sz*0.3f), ImVec2(x + sz, y + sz), col32, th); + x = p.x + 4; + y += sz + spacing; + } + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6); x += sz + spacing; // Hexagon + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 32); x += sz + spacing; // Circle + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32); x += sz + spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f); x += sz + spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight); x += sz + spacing; + draw_list->AddTriangleFilled(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32); x += sz + spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col32); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col32); x += spacing + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col32); x += sz; // Pixel (faster than AddLine) + 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)); + ImGui::Dummy(ImVec2((sz + spacing) * 8, (sz + spacing) * 3)); + ImGui::EndTabItem(); } - if (ImGui::IsItemHovered()) + + if (ImGui::BeginTabItem("Canvas")) { - if (!adding_line && ImGui::IsMouseClicked(0)) + static ImVector points; + static bool adding_line = false; + if (ImGui::Button("Clear")) points.clear(); + if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } + ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); + + // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() + // But you can also draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). + // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). + ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; + if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; + draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(50, 50, 50, 255), IM_COL32(50, 50, 60, 255), IM_COL32(60, 60, 70, 255), IM_COL32(50, 50, 60, 255)); + draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(255, 255, 255, 255)); + + bool adding_preview = false; + ImGui::InvisibleButton("canvas", canvas_size); + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); + if (adding_line) { + adding_preview = true; points.push_back(mouse_pos_in_canvas); - adding_line = true; + if (!ImGui::IsMouseDown(0)) + adding_line = adding_preview = false; } - if (ImGui::IsMouseClicked(1) && !points.empty()) + if (ImGui::IsItemHovered()) { - adding_line = adding_preview = false; - points.pop_back(); - points.pop_back(); + if (!adding_line && ImGui::IsMouseClicked(0)) + { + points.push_back(mouse_pos_in_canvas); + adding_line = true; + } + if (ImGui::IsMouseClicked(1) && !points.empty()) + { + adding_line = adding_preview = false; + points.pop_back(); + points.pop_back(); + } } + draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), true); // clip lines within the canvas (if we resize it, etc.) + for (int i = 0; i < points.Size - 1; i += 2) + draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i + 1].x, canvas_pos.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); + draw_list->PopClipRect(); + if (adding_preview) + points.pop_back(); + ImGui::EndTabItem(); } - draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), true); // clip lines within the canvas (if we resize it, etc.) - for (int i = 0; i < points.Size - 1; i += 2) - draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i + 1].x, canvas_pos.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); - draw_list->PopClipRect(); - if (adding_preview) - points.pop_back(); + + if (ImGui::BeginTabItem("BG/FG draw lists")) + { + static bool draw_bg = true; + static bool draw_fg = true; + ImGui::Checkbox("Draw in Background draw list", &draw_bg); + ImGui::Checkbox("Draw in Foreground draw list", &draw_fg); + ImVec2 window_pos = ImGui::GetWindowPos(); + ImVec2 window_size = ImGui::GetWindowSize(); + ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); + if (draw_bg) + ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 32, 10); + if (draw_fg) + ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 32, 10); + ImGui::EndTabItem(); + } + + ImGui::EndTabBar(); } + ImGui::End(); } diff --git a/imgui_internal.h b/imgui_internal.h index 0929e153..de099c48 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -888,8 +888,8 @@ struct ImGuiContext ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user ImDrawDataBuilder DrawDataBuilder; float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) - ImDrawList BackgroundDrawList; - ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays + ImDrawList BackgroundDrawList; // First draw list to be rendered. + ImDrawList ForegroundDrawList; // Last draw list to be rendered. This is where we the render software mouse cursor (if io.MouseDrawCursor is set) and most debug overlays. ImGuiMouseCursor MouseCursor; // Drag and Drop @@ -963,7 +963,7 @@ struct ImGuiContext int WantTextInputNextFrame; char TempBuffer[1024*3+1]; // Temporary text buffer - ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(NULL), OverlayDrawList(NULL) + ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(NULL), ForegroundDrawList(NULL) { Initialized = false; FrameScopeActive = FrameScopePushedImplicitWindow = false; @@ -1033,8 +1033,8 @@ struct ImGuiContext DimBgRatio = 0.0f; BackgroundDrawList._Data = &DrawListSharedData; BackgroundDrawList._OwnerName = "##Background"; // Give it a name for debugging - OverlayDrawList._Data = &DrawListSharedData; - OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging + ForegroundDrawList._Data = &DrawListSharedData; + ForegroundDrawList._OwnerName = "##Foreground"; // Give it a name for debugging MouseCursor = ImGuiMouseCursor_Arrow; DragDropActive = DragDropWithinSourceOrTarget = false; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dbb98ab3..abdeca0c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6635,7 +6635,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, { // Enlarge tab display when hovering bb.Max.x = bb.Min.x + (float)(int)ImLerp(bb.GetWidth(), tab->WidthContents, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)); - display_draw_list = GetOverlayDrawList(window); + display_draw_list = GetForegroundDrawList(window); TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive)); } #endif From f4dd990e38e22b7df860ea702f15261c4ddc4b4f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 11:03:32 +0100 Subject: [PATCH 118/566] Comments and Issue Template --- docs/issue_template.md | 8 ++++++-- imgui.h | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/issue_template.md b/docs/issue_template.md index 73330b22..6d88b271 100644 --- a/docs/issue_template.md +++ b/docs/issue_template.md @@ -3,12 +3,16 @@ 1. PLEASE CAREFULLY READ: https://github.com/ocornut/imgui/issues/2261 -2. IF YOU ARE HAVING AN ISSUE COMPILING/LINKING/RUNNING/DISPLAYING/ADDING FONTS, please post on the "Getting Started" Discourse forum: +2. IF YOU ARE HAVING AN ISSUE COMPILING/LINKING/RUNNING/LOADING FONTS, please post on the "Getting Started" Discourse forum: https://discourse.dearimgui.org/c/getting-started 3. PLEASE MAKE SURE that you have: read the FAQ in imgui.cpp; explored the contents of ShowDemoWindow() including the Examples menu; searched among Issues; used your IDE to search for keywords in all sources and text files; and read the link provided in (1). -4. Delete points 1-4 and PLEASE FILL THE TEMPLATE BELOW before submitting your issue. +4. Be mindful that messages are being sent to the mailbox of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users, unless they browse the site. + +5. Delete points 1-5 and PLEASE FILL THE TEMPLATE BELOW before submitting your issue. + +Thank you! ---- diff --git a/imgui.h b/imgui.h index eeb9b81d..52cdd06d 100644 --- a/imgui.h +++ b/imgui.h @@ -267,7 +267,7 @@ namespace ImGui IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() - IMGUI_API float GetContentRegionAvailWidth(); // + IMGUI_API float GetContentRegionAvailWidth(); // == GetContentRegionAvail().x IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates IMGUI_API float GetWindowContentRegionWidth(); // From ac4842fa173e4ab15db19aa0ded444fc4858154d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 12:03:54 +0100 Subject: [PATCH 119/566] Nav: Fixed Ctrl+Tab keeping active InputText() of a previous window active after the switch. (#2380) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1062c86e..6335cd3b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other Changes: - Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered behind every other windows. (#2391) - Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigating to the menu layer. +- Nav: Fixed Ctrl+Tab keeping active InputText() of a previous window active after the switch. (#2380) - DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. We are reusing function instances for larger types to reduce code size. (#643, #320, #708, #1011) - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when diff --git a/imgui.cpp b/imgui.cpp index 099c9178..79482658 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7993,7 +7993,9 @@ static void NavUpdateWindowingHighlightWindow(int focus_change_dir) g.NavWindowingToggleLayer = false; } -// Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer) +// Windowing management mode +// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer) +// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) static void ImGui::NavUpdateWindowing() { ImGuiContext& g = *GImGui; @@ -8096,6 +8098,7 @@ static void ImGui::NavUpdateWindowing() g.NavDisableMouseHover = true; apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window); ClosePopupsOverWindow(apply_focus_window); + ClearActiveID(); FocusWindow(apply_focus_window); if (apply_focus_window->NavLastIds[0] == 0) NavInitWindow(apply_focus_window, false); From 622a27506ac473ea3a28ee3c298beffdd803c863 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 15:23:11 +0100 Subject: [PATCH 120/566] Text: Fixed large Text/TextUnformatted call not declaring its size when starting below the lower point of the current clipping rectangle. Somehow this bug has been there since v1.0! It was hardly noticeable but would affect the scrolling range, which in turn would affect some scrolling request functions when called during the opening frame of a window. --- docs/CHANGELOG.txt | 4 +++ docs/TODO.txt | 3 +- imgui.h | 2 +- imgui_widgets.cpp | 85 ++++++++++++++++++++++------------------------ 4 files changed, 47 insertions(+), 47 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6335cd3b..11485779 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,10 @@ Other Changes: - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) +- Text: Fixed large Text/TextUnformatted call not declaring its size when starting below the + lower point of the current clipping rectangle. Somehow this bug has been there since v1.0! + It was hardly noticeable but would affect the scrolling range, which in turn would affect + some scrolling request functions when called during the opening frame of a window. - Plot: Fixed divide-by-zero in PlotLines() when passing a count of 1. (#2387) [@Lectem] - Log/Capture: Fixed extraneous leading carriage return. - Log/Capture: Fixed an issue when empty string on a new line would not emit a carriage return. diff --git a/docs/TODO.txt b/docs/TODO.txt index d0fa9755..34f6f946 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -191,6 +191,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - text wrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) - text: it's currently impossible to have a window title with "##". perhaps an official workaround would be nice. \ style inhibitor? non-visible ascii code to insert between #? - text: provided a framed text helper, e.g. https://pastebin.com/1Laxy8bT + - text: refactor TextUnformatted (or underlying function) to more explicitly request if we need width measurement or not - text link/url button: underlined. should api expose an ID or use text contents as ID? which colors enum to use? - tree node / optimization: avoid formatting when clipped. @@ -222,7 +223,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. - log: obsolete LogButtons() all together. - log: LogButtons() options for specifying depth and/or hiding depth slider - + - filters: set a current filter that tree node can automatically query to hide themselves - filters: handle wild-cards (with implicit leading/trailing *), reg-exprs - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb) diff --git a/imgui.h b/imgui.h index 52cdd06d..8cc826f5 100644 --- a/imgui.h +++ b/imgui.h @@ -297,7 +297,7 @@ namespace ImGui IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. - IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. + IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. // Parameters stacks (shared) IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index abdeca0c..865cd8ad 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -159,53 +159,15 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) const ImRect clip_rect = window->ClipRect; ImVec2 text_size(0,0); - if (text_pos.y <= clip_rect.Max.y) + // Lines to skip (can't skip when logging text) + ImVec2 pos = text_pos; + if (!g.LogEnabled) { - ImVec2 pos = text_pos; - - // Lines to skip (can't skip when logging text) - if (!g.LogEnabled) + int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); + if (lines_skippable > 0) { - int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); - if (lines_skippable > 0) - { - int lines_skipped = 0; - while (line < text_end && lines_skipped < lines_skippable) - { - const char* line_end = (const char*)memchr(line, '\n', text_end - line); - if (!line_end) - line_end = text_end; - line = line_end + 1; - lines_skipped++; - } - pos.y += lines_skipped * line_height; - } - } - - // Lines to render - if (line < text_end) - { - ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); - while (line < text_end) - { - if (IsClippedEx(line_rect, 0, false)) - break; - - const char* line_end = (const char*)memchr(line, '\n', text_end - line); - if (!line_end) - line_end = text_end; - const ImVec2 line_size = CalcTextSize(line, line_end, false); - text_size.x = ImMax(text_size.x, line_size.x); - RenderText(pos, line, line_end, false); - line = line_end + 1; - line_rect.Min.y += line_height; - line_rect.Max.y += line_height; - pos.y += line_height; - } - - // Count remaining lines int lines_skipped = 0; - while (line < text_end) + while (line < text_end && lines_skipped < lines_skippable) { const char* line_end = (const char*)memchr(line, '\n', text_end - line); if (!line_end) @@ -215,9 +177,42 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) } pos.y += lines_skipped * line_height; } + } - text_size.y += (pos - text_pos).y; + // Lines to render + if (line < text_end) + { + ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); + while (line < text_end) + { + if (IsClippedEx(line_rect, 0, false)) + break; + + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + const ImVec2 line_size = CalcTextSize(line, line_end, false); + text_size.x = ImMax(text_size.x, line_size.x); + RenderText(pos, line, line_end, false); + line = line_end + 1; + line_rect.Min.y += line_height; + line_rect.Max.y += line_height; + pos.y += line_height; + } + + // Count remaining lines + int lines_skipped = 0; + while (line < text_end) + { + const char* line_end = (const char*)memchr(line, '\n', text_end - line); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; } + text_size.y = (pos - text_pos).y; ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); From 1ed3c4cf4abc1278c08ecad6354de67178902eb8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 16:08:18 +0100 Subject: [PATCH 121/566] Internal: Text: Extracted TextUnformatted into TextEx over which we can freely atter the signature. Clarified current large text behavior of TextUnformatted with explicit ImGuiTextFlags_NoWidthForLargeClippedText flag (always set). --- docs/TODO.txt | 2 ++ imgui_internal.h | 10 +++++++++- imgui_widgets.cpp | 44 +++++++++++++++++++++++++------------------- 3 files changed, 36 insertions(+), 20 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 34f6f946..85696c1e 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -138,6 +138,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - image button: not taking an explicit id is odd. + - slider/drag: ctrl+click when format doesn't include a % character.. disable? display underlying value in default format? (see InputScalarAsWidgetReplacement) - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). (#1946) - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. @@ -249,6 +250,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font: finish CustomRectRegister() to allow mapping Unicode codepoint to custom texture data - font: PushFontSize API (#1018) - font: MemoryTTF taking ownership confusing/not obvious, maybe default should be opposite? + - font: storing MinAdvanceX per font would allow us to skip calculating line width (under a threshold of character count) in loops looking for block width - font/demo: add tools to show glyphs used by a text blob, display U16 value, list missing glyphs. - font/demo: demonstrate use of ImFontGlyphRangesBuilder. - font/atlas: add a missing Glyphs.reserve() diff --git a/imgui_internal.h b/imgui_internal.h index de099c48..6fcb4830 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -83,6 +83,7 @@ struct ImGuiWindowSettings; // Storage for window settings stored in .in // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() +typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() @@ -90,7 +91,7 @@ typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for Separator() - internal typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior() -typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() +typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() //------------------------------------------------------------------------- // STB libraries includes @@ -381,6 +382,12 @@ enum ImGuiItemStatusFlags_ #endif }; +enum ImGuiTextFlags_ +{ + ImGuiTextFlags_None = 0, + ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0 +}; + // FIXME: this is in development, not exposed/functional as a generic feature yet. // Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 enum ImGuiLayoutType_ @@ -1501,6 +1508,7 @@ namespace ImGui IMGUI_API void RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, int count, ImU32 col); // Widgets + IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 865cd8ad..6de9319a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -132,7 +132,7 @@ static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const // - BulletTextV() //------------------------------------------------------------------------- -void ImGui::TextUnformatted(const char* text, const char* text_end) +void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -146,7 +146,7 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); const float wrap_pos_x = window->DC.TextWrapPos; - const bool wrap_enabled = wrap_pos_x >= 0.0f; + const bool wrap_enabled = (wrap_pos_x >= 0.0f); if (text_end - text > 2000 && !wrap_enabled) { // Long text! @@ -156,14 +156,13 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop. const char* line = text; const float line_height = GetTextLineHeight(); - const ImRect clip_rect = window->ClipRect; ImVec2 text_size(0,0); // Lines to skip (can't skip when logging text) ImVec2 pos = text_pos; if (!g.LogEnabled) { - int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); + int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; @@ -172,6 +171,8 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) const char* line_end = (const char*)memchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; + if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); line = line_end + 1; lines_skipped++; } @@ -191,8 +192,7 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) const char* line_end = (const char*)memchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; - const ImVec2 line_size = CalcTextSize(line, line_end, false); - text_size.x = ImMax(text_size.x, line_size.x); + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); RenderText(pos, line, line_end, false); line = line_end + 1; line_rect.Min.y += line_height; @@ -207,6 +207,8 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) const char* line_end = (const char*)memchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; + if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) + text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); line = line_end + 1; lines_skipped++; } @@ -223,7 +225,6 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); - // Account of baseline offset ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); if (!ItemAdd(bb, 0)) @@ -234,6 +235,11 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) } } +void ImGui::TextUnformatted(const char* text, const char* text_end) +{ + TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); +} + void ImGui::Text(const char* fmt, ...) { va_list args; @@ -250,7 +256,7 @@ void ImGui::TextV(const char* fmt, va_list args) ImGuiContext& g = *GImGui; const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); - TextUnformatted(g.TempBuffer, text_end); + TextEx(g.TempBuffer, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) @@ -2009,7 +2015,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int } PopID(); - TextUnformatted(label, FindRenderedTextEnd(label)); + TextEx(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } @@ -2052,7 +2058,7 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - TextUnformatted(label, FindRenderedTextEnd(label)); + TextEx(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); return value_changed; @@ -2097,7 +2103,7 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - TextUnformatted(label, FindRenderedTextEnd(label)); + TextEx(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); @@ -2450,7 +2456,7 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i } PopID(); - TextUnformatted(label, FindRenderedTextEnd(label)); + TextEx(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } @@ -2749,7 +2755,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p value_changed = true; } SameLine(0, style.ItemInnerSpacing.x); - TextUnformatted(label, FindRenderedTextEnd(label)); + TextEx(label, FindRenderedTextEnd(label)); style.FramePadding = backup_frame_padding; PopID(); @@ -2787,7 +2793,7 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, in } PopID(); - TextUnformatted(label, FindRenderedTextEnd(label)); + TextEx(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } @@ -4078,7 +4084,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag picker_active_window = g.CurrentWindow; if (label != label_display_end) { - TextUnformatted(label, label_display_end); + TextEx(label, label_display_end); Spacing(); } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; @@ -4093,7 +4099,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) { SameLine(0, style.ItemInnerSpacing.x); - TextUnformatted(label, label_display_end); + TextEx(label, label_display_end); } // Convert back @@ -4353,7 +4359,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl { if ((flags & ImGuiColorEditFlags_NoSidePreview)) SameLine(0, style.ItemInnerSpacing.x); - TextUnformatted(label, label_display_end); + TextEx(label, label_display_end); } } @@ -4581,7 +4587,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once); ColorButton(desc_id, col, flags); SameLine(); - TextUnformatted("Color"); + TextEx("Color"); EndDragDropSource(); } @@ -4622,7 +4628,7 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; if (text_end > text) { - TextUnformatted(text, text_end); + TextEx(text, text_end); Separator(); } From ce4e62649ae99ba4b0cd14526e75cfe13e4bd3ba Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 17:38:36 +0100 Subject: [PATCH 122/566] Internal: Tabbing: Tweaks to FocusableItemRegister and using the standard mechanism to allow/block Tab being interpreting by tabbing instead of InputText() widget. --- imgui.cpp | 21 +++++++++++++-------- imgui.h | 1 + imgui_internal.h | 7 ++++++- imgui_widgets.cpp | 5 ++++- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 79482658..d9010e94 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2895,19 +2895,21 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged return false; } -bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop) +bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) { ImGuiContext& g = *GImGui; + // Increment counters const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0; window->FocusIdxAllCounter++; if (is_tab_stop) window->FocusIdxTabCounter++; - // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item. - // Note that we can always TAB out of a widget that doesn't allow tabbing in. - if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)) - window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. + // Process TAB/Shift-TAB to tab *OUT* of the currently focused item. + // (Note that we can always TAB out of a widget that doesn't allow tabbing in) + if (g.ActiveId == id && g.FocusTabPressed && !(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_KeyTab_))) + if (window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX) + window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) return true; @@ -3513,7 +3515,9 @@ void ImGui::NewFrame() UpdateMouseWheel(); // Pressing TAB activate widget focus - if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false)) + // (This code is old and will be redesigned for Nav. In the meanwhile we use g.NavTabRequest as storage but this doesn't need ImGuiConfigFlags_NavEnableKeyboard to work!) + g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)); + if (g.ActiveId == 0 && g.FocusTabPressed) { if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); @@ -5167,8 +5171,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; // Prepare for item focus requests - window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); - window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); + window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : ImModPositive(window->FocusIdxAllRequestNext, window->FocusIdxAllCounter + 1); + window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : ImModPositive(window->FocusIdxTabRequestNext, window->FocusIdxTabCounter + 1); window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; @@ -7609,6 +7613,7 @@ static void ImGui::NavUpdate() NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_); NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ ); NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ ); + NAV_MAP_KEY(ImGuiKey_Tab, ImGuiNavInput_KeyTab_ ); if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; if (g.IO.KeyShift) diff --git a/imgui.h b/imgui.h index 8cc826f5..2ffe14dd 100644 --- a/imgui.h +++ b/imgui.h @@ -967,6 +967,7 @@ enum ImGuiNavInput_ // [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them. // Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from io.KeysDown[] instead of io.NavInputs[]. ImGuiNavInput_KeyMenu_, // toggle menu // = io.KeyAlt + ImGuiNavInput_KeyTab_, // tab // = Tab key ImGuiNavInput_KeyLeft_, // move left // = Arrow keys ImGuiNavInput_KeyRight_, // move right ImGuiNavInput_KeyUp_, // move up diff --git a/imgui_internal.h b/imgui_internal.h index 6fcb4830..dc1fc08d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -248,6 +248,7 @@ static inline float ImLengthSqr(const ImVec4& lhs) static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; } static inline float ImFloor(float f) { return (float)(int)f; } static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } +static inline int ImModPositive(int a, int b) { return (a + b) % b; } static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } static 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); } static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; } @@ -891,6 +892,9 @@ struct ImGuiContext ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) + // Tabbing system (older than Nav, active when Nav is disabled. Probably needs a redesign) + bool FocusTabPressed; // + // Render ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user ImDrawDataBuilder DrawDataBuilder; @@ -1036,6 +1040,7 @@ struct ImGuiContext NavMoveRequestFlags = 0; NavMoveRequestForward = ImGuiNavForward_None; NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; + FocusTabPressed = false; DimBgRatio = 0.0f; BackgroundDrawList._Data = &DrawListSharedData; @@ -1421,7 +1426,7 @@ namespace ImGui IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL); IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id); IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); - IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop = true); // Return true if focus is requested + IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6de9319a..ea0914ec 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3274,7 +3274,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (g.InputTextState.ID == id) state = &g.InputTextState; - const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing + const bool focus_requested = FocusableItemRegister(window, id); const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; @@ -3337,7 +3337,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); + IM_ASSERT(ImGuiNavInput_COUNT < 32); g.ActiveIdBlockNavInputFlags = (1 << ImGuiNavInput_Cancel); + if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out + g.ActiveIdBlockNavInputFlags |= (1 << ImGuiNavInput_KeyTab_); if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory)) g.ActiveIdAllowNavDirFlags = ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down)); } From 076be7ec4127b75af2ad88369d3d722cabbf6cd8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 19:00:19 +0100 Subject: [PATCH 123/566] MenuItem, Selectable: Fixed disabled widget interfering with navigation (fix c2db7f63 in 1.67). --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 11485779..4f1faee6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,7 @@ Other Changes: when manipulating the scrollbar of a multi-line input text. - ColorPicker: Fixed a bug/assertion when displaying a color picker in a collapsed window while dragging its title bar. (#2389) +- MenuItem, Selectable: Fixed disabled widget interfering with navigation (fix c2db7f63 in 1.67). - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ea0914ec..718d4764 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5179,7 +5179,20 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl bb.Min.y -= spacing_U; bb.Max.x += spacing_R; bb.Max.y += spacing_D; - if (!ItemAdd(bb, id)) + + bool item_add; + if (flags & ImGuiSelectableFlags_Disabled) + { + ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; + window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus; + item_add = ItemAdd(bb, id); + window->DC.ItemFlags = backup_item_flags; + } + else + { + item_add = ItemAdd(bb, id); + } + if (!item_add) { if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) PushColumnClipRect(); From 9c45072cb06534ec53a8f3629f5f7090593eb1fc Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 19:22:58 +0100 Subject: [PATCH 124/566] Demo: Added flags to InputTextMulttiline() demo. --- imgui_demo.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 080d92bd..45a21e48 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -940,7 +940,6 @@ static void ShowDemoWindowWidgets() { // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings. - static bool read_only = false; static char text[1024*16] = "/*\n" " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" @@ -953,9 +952,11 @@ static void ShowDemoWindowWidgets() "label:\n" "\tlock cmpxchg8b eax\n"; + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; ShowHelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp)"); - ImGui::Checkbox("Read-only", &read_only); - ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput); + ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine); ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), flags); ImGui::TreePop(); } From 26328fc9feded2282ff45c05f8f859285d7fd75f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 19:37:20 +0100 Subject: [PATCH 125/566] Internal: Tabbing/Focus: Tidying up old code, moved some state to context instead of window. Storing new data will allow us to fix the bug mentioned in #2215 (probably in next commit). --- imgui.cpp | 76 +++++++++++++++++++++++++++++------------------ imgui_internal.h | 27 ++++++++++------- imgui_widgets.cpp | 2 +- 3 files changed, 64 insertions(+), 41 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d9010e94..6d47dc8c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2552,10 +2552,6 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) NavLastIds[0] = NavLastIds[1] = 0; NavRectRel[0] = NavRectRel[1] = ImRect(); NavLastChildNavWindow = NULL; - - FocusIdxAllCounter = FocusIdxTabCounter = -1; - FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; - FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; } ImGuiWindow::~ImGuiWindow() @@ -2901,22 +2897,28 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) // Increment counters const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0; - window->FocusIdxAllCounter++; + window->DC.FocusCounterAll++; if (is_tab_stop) - window->FocusIdxTabCounter++; + window->DC.FocusCounterTab++; // Process TAB/Shift-TAB to tab *OUT* of the currently focused item. // (Note that we can always TAB out of a widget that doesn't allow tabbing in) - if (g.ActiveId == id && g.FocusTabPressed && !(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_KeyTab_))) - if (window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX) - window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. + if (g.ActiveId == id && g.FocusTabPressed && !(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_KeyTab_)) && g.FocusRequestNextWindow == NULL) + { + g.FocusRequestNextWindow = window; + g.FocusRequestNextCounterTab = window->DC.FocusCounterTab + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. + } - if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) - return true; - if (is_tab_stop && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) + // Handle focus requests + if (g.FocusRequestCurrWindow == window) { - g.NavJustTabbedId = id; - return true; + if (window->DC.FocusCounterAll == g.FocusRequestCurrCounterAll) + return true; + if (is_tab_stop && window->DC.FocusCounterTab == g.FocusRequestCurrCounterTab) + { + g.NavJustTabbedId = id; + return true; + } } return false; @@ -2924,8 +2926,8 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) void ImGui::FocusableItemUnregister(ImGuiWindow* window) { - window->FocusIdxAllCounter--; - window->FocusIdxTabCounter--; + window->DC.FocusCounterAll--; + window->DC.FocusCounterTab--; } ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) @@ -3515,15 +3517,34 @@ void ImGui::NewFrame() UpdateMouseWheel(); // Pressing TAB activate widget focus - // (This code is old and will be redesigned for Nav. In the meanwhile we use g.NavTabRequest as storage but this doesn't need ImGuiConfigFlags_NavEnableKeyboard to work!) g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)); if (g.ActiveId == 0 && g.FocusTabPressed) { + // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also + // manipulate the Next fields even, even though they will be turned into Curr fields by the code below. + g.FocusRequestNextWindow = g.NavWindow; + g.FocusRequestNextCounterAll = INT_MAX; if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) - g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); + g.FocusRequestNextCounterTab = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); else - g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0; + g.FocusRequestNextCounterTab = g.IO.KeyShift ? -1 : 0; } + + // Turn queued focus request into current one + g.FocusRequestCurrWindow = NULL; + g.FocusRequestCurrCounterAll = g.FocusRequestCurrCounterTab = INT_MAX; + if (g.FocusRequestNextWindow != NULL) + { + ImGuiWindow* window = g.FocusRequestNextWindow; + g.FocusRequestCurrWindow = window; + if (g.FocusRequestNextCounterAll != INT_MAX && window->DC.FocusCounterAll != -1) + g.FocusRequestCurrCounterAll = ImModPositive(g.FocusRequestNextCounterAll, window->DC.FocusCounterAll + 1); + if (g.FocusRequestNextCounterTab != INT_MAX && window->DC.FocusCounterTab != -1) + g.FocusRequestCurrCounterTab = ImModPositive(g.FocusRequestNextCounterTab, window->DC.FocusCounterTab + 1); + g.FocusRequestNextWindow = NULL; + g.FocusRequestNextCounterAll = g.FocusRequestNextCounterTab = INT_MAX; + } + g.NavIdTabCounter = INT_MAX; // Mark all windows as not visible @@ -5170,12 +5191,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; - // Prepare for item focus requests - window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : ImModPositive(window->FocusIdxAllRequestNext, window->FocusIdxAllCounter + 1); - window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : ImModPositive(window->FocusIdxTabRequestNext, window->FocusIdxTabCounter + 1); - window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; - window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; - // Apply scrolling window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true); window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); @@ -5350,6 +5365,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.ChildWindows.resize(0); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; + window->DC.FocusCounterAll = window->DC.FocusCounterTab = -1; window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_; window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled @@ -6462,9 +6478,11 @@ void ImGui::ActivateItem(ImGuiID id) void ImGui::SetKeyboardFocusHere(int offset) { IM_ASSERT(offset >= -1); // -1 is allowed but not below - ImGuiWindow* window = GetCurrentWindow(); - window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; - window->FocusIdxTabRequestNext = INT_MAX; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + g.FocusRequestNextWindow = window; + g.FocusRequestNextCounterAll = window->DC.FocusCounterAll + 1 + offset; + g.FocusRequestNextCounterTab = INT_MAX; } void ImGui::SetItemDefaultFocus() @@ -7373,7 +7391,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window. g.NavLayer = window->DC.NavLayerCurrent; g.NavIdIsAlive = true; - g.NavIdTabCounter = window->FocusIdxTabCounter; + g.NavIdTabCounter = window->DC.FocusCounterTab; window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position) } } diff --git a/imgui_internal.h b/imgui_internal.h index dc1fc08d..4f5ac884 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -892,7 +892,13 @@ struct ImGuiContext ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) - // Tabbing system (older than Nav, active when Nav is disabled. Probably needs a redesign) + // Tabbing system (older than Nav, active even if Nav is disabled. FIXME-NAV: This needs a redesign!) + ImGuiWindow* FocusRequestCurrWindow; // + ImGuiWindow* FocusRequestNextWindow; // + int FocusRequestCurrCounterAll; // Any item being requested for focus, stored as an index (we on layout to be stable between the frame pressing TAB and the next frame, semi-ouch) + int FocusRequestCurrCounterTab; // Tab item being requested for focus, stored as an index + int FocusRequestNextCounterAll; // Stored for next frame + int FocusRequestNextCounterTab; // " bool FocusTabPressed; // // Render @@ -1040,6 +1046,10 @@ struct ImGuiContext NavMoveRequestFlags = 0; NavMoveRequestForward = ImGuiNavForward_None; NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; + + FocusRequestCurrWindow = FocusRequestNextWindow = NULL; + FocusRequestCurrCounterAll = FocusRequestCurrCounterTab = INT_MAX; + FocusRequestNextCounterAll = FocusRequestNextCounterTab = INT_MAX; FocusTabPressed = false; DimBgRatio = 0.0f; @@ -1127,6 +1137,8 @@ struct IMGUI_API ImGuiWindowTempData ImGuiStorage* StateStorage; ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() + int FocusCounterAll; // Counter for focus/tabbing system. Start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign) + int FocusCounterTab; // (same, but only count widgets which you can Tab through) // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default] @@ -1162,8 +1174,10 @@ struct IMGUI_API ImGuiWindowTempData MenuBarOffset = ImVec2(0.0f, 0.0f); StateStorage = NULL; LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical; - ItemWidth = 0.0f; + FocusCounterAll = FocusCounterTab = -1; + ItemFlags = ImGuiItemFlags_Default_; + ItemWidth = 0.0f; TextWrapPos = -1.0f; memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); @@ -1248,15 +1262,6 @@ struct IMGUI_API ImGuiWindow ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space - // Navigation / Focus - // FIXME-NAV: Merge all this with the new Nav system, at least the request variables should be moved to ImGuiContext - int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() - int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) - int FocusIdxAllRequestCurrent; // Item being requested for focus - int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus - int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) - int FocusIdxTabRequestNext; // " - public: ImGuiWindow(ImGuiContext* context, const char* name); ~ImGuiWindow(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 718d4764..63583c34 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3275,7 +3275,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 state = &g.InputTextState; const bool focus_requested = FocusableItemRegister(window, id); - const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); + const bool focus_requested_by_code = focus_requested && (g.FocusRequestCurrWindow == window && g.FocusRequestCurrCounterAll == window->DC.FocusCounterAll); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool user_clicked = hovered && io.MouseClicked[0]; From 344140004bbc3546443a546913688e810f84a1db Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 Mar 2019 22:09:25 +0100 Subject: [PATCH 126/566] Fixed IsItemDeactivated()/IsItemDeactivatedAfterEdit() from not correctly returning true when tabbing out of a focusable widget (Input/Slider/Drag) in most situations. (#2215, #1875) + Minor renaming of a local variable in widget code. --- docs/CHANGELOG.txt | 6 ++++-- imgui.cpp | 5 +++++ imgui_widgets.cpp | 12 ++++++------ 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4f1faee6..7f002f30 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,10 +44,12 @@ Other Changes: - Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered behind every other windows. (#2391) -- Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigating to the menu layer. -- Nav: Fixed Ctrl+Tab keeping active InputText() of a previous window active after the switch. (#2380) - DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. We are reusing function instances for larger types to reduce code size. (#643, #320, #708, #1011) +- Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigating to the menu layer. +- Nav: Fixed Ctrl+Tab keeping active InputText() of a previous window active after the switch. (#2380) +- Fixed IsItemDeactivated()/IsItemDeactivatedAfterEdit() from not correctly returning true + when tabbing out of a focusable widget (Input/Slider/Drag) in most situations. (#2215, #1875) - InputInt, InputFloat, InputScalar: Fix to keep the label of the +/- buttons centered when style.FramePadding.x is abnormally larger than style.FramePadding.y. Since the buttons are meant to be square (to align with e.g. color button) we always use FramePadding.y. (#2367) diff --git a/imgui.cpp b/imgui.cpp index 6d47dc8c..4805c673 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2891,6 +2891,7 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged return false; } +// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) { ImGuiContext& g = *GImGui; @@ -2919,6 +2920,10 @@ bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) g.NavJustTabbedId = id; return true; } + + // If another item is about to be focused, we clear our own active id + if (g.ActiveId == id) + ClearActiveID(); } return false; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 63583c34..a3683613 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1950,14 +1950,14 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa // Tabbing or CTRL-clicking on Drag turns it into an input box bool start_text_input = false; - const bool tab_focus_requested = FocusableItemRegister(window, id); - if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) + const bool focus_requested = FocusableItemRegister(window, id); + if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); - if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) + if (focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) { start_text_input = true; g.ScalarAsInputTextId = 0; @@ -2385,15 +2385,15 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co // Tabbing or CTRL-clicking on Slider turns it into an input box bool start_text_input = false; - const bool tab_focus_requested = FocusableItemRegister(window, id); + const bool focus_requested = FocusableItemRegister(window, id); const bool hovered = ItemHoverable(frame_bb, id); - if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) + if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); - if (tab_focus_requested || g.IO.KeyCtrl || g.NavInputId == id) + if (focus_requested || g.IO.KeyCtrl || g.NavInputId == id) { start_text_input = true; g.ScalarAsInputTextId = 0; From 8b8ab1db5b8047f95761d8ab74bd951246f497be Mon Sep 17 00:00:00 2001 From: David Maas Date: Wed, 6 Mar 2019 00:39:16 -0800 Subject: [PATCH 127/566] Removed redundant declaration of SetNextWindowClass. (#2402) --- imgui.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index d5988bde..c00e0b42 100644 --- a/imgui.h +++ b/imgui.h @@ -290,7 +290,6 @@ namespace ImGui IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. IMGUI_API void SetNextWindowViewport(ImGuiID viewport_id); // set next window viewport - IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (rare/advanced uses: provide hints to the platform back-end via altered viewport flags and parent/child info) IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). @@ -595,7 +594,7 @@ namespace ImGui IMGUI_API void DockSpace(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags dockspace_flags = 0, const ImGuiWindowClass* window_class = NULL); IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id (FIXME-DOCK) - IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class / user type (docking filters by same user_type) + IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (rare/advanced uses: provide hints to the platform back-end via altered viewport flags and parent/child info) IMGUI_API ImGuiID GetWindowDockID(); IMGUI_API bool IsWindowDocked(); // is current window docked into another window? From fe48368cb2f198b5ea4c3e1629144b0682b86944 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Mar 2019 15:44:21 +0100 Subject: [PATCH 128/566] InputText: Moving some code in anticipation of supporting hint display with password. This commit is aimed at having no visible side effect. (#2400) --- imgui_widgets.cpp | 47 ++++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a3683613..543bcf8b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3252,23 +3252,6 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (hovered) g.MouseCursor = ImGuiMouseCursor_TextInput; - // Password pushes a temporary font with only a fallback glyph - if (is_password) - { - const ImFontGlyph* glyph = g.Font->FindGlyph('*'); - ImFont* password_font = &g.InputTextPasswordFont; - password_font->FontSize = g.Font->FontSize; - password_font->Scale = g.Font->Scale; - password_font->DisplayOffset = g.Font->DisplayOffset; - password_font->Ascent = g.Font->Ascent; - password_font->Descent = g.Font->Descent; - password_font->ContainerAtlas = g.Font->ContainerAtlas; - password_font->FallbackGlyph = glyph; - password_font->FallbackAdvanceX = glyph->AdvanceX; - IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty()); - PushFont(password_font); - } - // NB: we are only allowed to access 'edit_state' if we are the active widget. ImGuiInputTextState* state = NULL; if (g.InputTextState.ID == id) @@ -3353,10 +3336,6 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560 clear_active_id = true; - bool value_changed = false; - bool enter_pressed = false; - int backup_current_text_length = 0; - // When read-only we always use the live data passed to the function // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :( if (is_readonly && state != NULL) @@ -3373,7 +3352,31 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } } + // Lock the decision of whether we are going to take the path displaying the cursor or selection + const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active); + const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); + bool value_changed = false; + bool enter_pressed = false; + + // Password pushes a temporary font with only a fallback glyph + if (is_password) + { + const ImFontGlyph* glyph = g.Font->FindGlyph('*'); + ImFont* password_font = &g.InputTextPasswordFont; + password_font->FontSize = g.Font->FontSize; + password_font->Scale = g.Font->Scale; + password_font->DisplayOffset = g.Font->DisplayOffset; + password_font->Ascent = g.Font->Ascent; + password_font->Descent = g.Font->Descent; + password_font->ContainerAtlas = g.Font->ContainerAtlas; + password_font->FallbackGlyph = glyph; + password_font->FallbackAdvanceX = glyph->AdvanceX; + IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty()); + PushFont(password_font); + } + // Process mouse inputs and character inputs + int backup_current_text_length = 0; if (g.ActiveId == id) { IM_ASSERT(state != NULL); @@ -3725,8 +3728,6 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. - const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active); - const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); if (render_cursor || render_selection) { // Render text (with cursor and selection) From ab80ee645316f36c172fcef9fe9a7d225516dbb2 Mon Sep 17 00:00:00 2001 From: Lucas Lazare Date: Wed, 6 Mar 2019 14:31:19 +0100 Subject: [PATCH 129/566] Added InputTextWithHint() (#2400) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Squashed commit of the following: commit 1970d84051d3878f8c1354d9c33c795d9c66143f Author: Lucas Lazare Date: Tue Mar 5 12:20:39 2019 -0500 Removing sneaky tabulations #2 (why, editor T-T) I should update my settings, I guess commit 219bdfcb7fbd17edf3048cb0edfde2532e4d6ac3 Author: Lucas Lazare Date: Tue Mar 5 12:17:27 2019 -0500 Removing useless check introduced in b0d172 commit 8afd7a2b459df0eb14eca88d832d2bebd1e684e6 Author: Lucas Lazare Date: Tue Mar 5 11:49:24 2019 -0500 Removing sneaky tabulations commit 8e0490863126d63cafc782a6aac8707e44f95653 Author: Lucas Lazare Date: Tue Mar 5 11:45:13 2019 -0500 Moving InputTextHinted code to InputTextEx commit b0d1723a2fb02d17ba15b9c1e679dedbbe3c17fd Author: Lucas Lazare Date: Tue Mar 5 00:23:02 2019 -0500 C++11 to C++98 commit 9afeae399826015357962607b4aeb0109fde698e Author: Lucas Lazare Date: Mon Mar 4 23:43:28 2019 -0500 Added InputTextHinted --- imgui.h | 1 + imgui_demo.cpp | 5 +++- imgui_internal.h | 2 +- imgui_widgets.cpp | 52 ++++++++++++++++++++++++++++++++------- misc/cpp/imgui_stdlib.cpp | 12 +++++++++ misc/cpp/imgui_stdlib.h | 1 + 6 files changed, 62 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 2ffe14dd..748313ec 100644 --- a/imgui.h +++ b/imgui.h @@ -450,6 +450,7 @@ namespace ImGui // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 45a21e48..1ecf49b8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -481,10 +481,13 @@ static void ShowDemoWindowWidgets() { static char str0[128] = "Hello, world!"; - static int i0 = 123; ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); ImGui::SameLine(); ShowHelpMarker("USER:\nHold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n\nPROGRAMMER:\nYou can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated in imgui_demo.cpp)."); + static char str1[128] = ""; + ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1)); + + static int i0 = 123; ImGui::InputInt("input int", &i0); ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); diff --git a/imgui_internal.h b/imgui_internal.h index 4f5ac884..576e3366 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1545,7 +1545,7 @@ namespace ImGui template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // InputText - IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format); // Color diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 543bcf8b..388d5547 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2692,7 +2692,7 @@ bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const c DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, data_ptr, format); ImStrTrimBlanks(data_buf); ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); - bool value_changed = InputTextEx(label, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags); + bool value_changed = InputTextEx(label, NULL, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags); if (g.ScalarAsInputTextId == 0) { // First frame we started displaying the InputText widget, we expect it to take the active id. @@ -2883,9 +2883,10 @@ bool ImGui::InputDouble(const char* label, double* v, double step, double step_f } //------------------------------------------------------------------------- -// [SECTION] Widgets: InputText, InputTextMultiline +// [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint //------------------------------------------------------------------------- // - InputText() +// - InputTextWithHint() // - InputTextMultiline() // - InputTextEx() [Internal] //------------------------------------------------------------------------- @@ -2893,12 +2894,17 @@ bool ImGui::InputDouble(const char* label, double* v, double step, double step_f bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() - return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); + return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); } bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { - return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); + return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); +} + +bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); } static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) @@ -3193,7 +3199,7 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f // - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h // (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are // doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188) -bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) +bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3725,6 +3731,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 const int buf_display_max_length = 2 * 1024 * 1024; const char* buf_display = NULL; const char* buf_display_end = NULL; + ImGuiCol text_color = ImGuiCol_COUNT; // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. @@ -3861,11 +3868,26 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 } } + if (state->CurLenA != 0 || hint == NULL) + { + buf_display = (!is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; + buf_display_end = buf_display + state->CurLenA; + text_color = ImGuiCol_Text; + } + else + { + buf_display = hint; + buf_display_end = hint + strlen(hint); + text_color = ImGuiCol_TextDisabled; + } + + // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. - buf_display = (!is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; - buf_display_end = buf_display + state->CurLenA; if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + { + IM_ASSERT(text_color != ImGuiCol_COUNT); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, GetColorU32(text_color), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + } // Draw blinking cursor if (render_cursor) @@ -3885,6 +3907,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 else { // Render text only (no selection, no cursor) + text_color = ImGuiCol_Text; buf_display = (g.ActiveId == id && !is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; if (is_multiline) text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width @@ -3892,8 +3915,19 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2 buf_display_end = buf_display + state->CurLenA; else buf_display_end = buf_display + strlen(buf_display); + + if (buf_display_end == buf_display && hint != NULL) + { + buf_display = hint; + buf_display_end = buf_display + strlen(buf_display); + text_color = ImGuiCol_TextDisabled; + } + if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + { + IM_ASSERT(text_color != ImGuiCol_COUNT); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, GetColorU32(text_color), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + } } if (is_multiline) diff --git a/misc/cpp/imgui_stdlib.cpp b/misc/cpp/imgui_stdlib.cpp index 694813a4..fda60f4d 100644 --- a/misc/cpp/imgui_stdlib.cpp +++ b/misc/cpp/imgui_stdlib.cpp @@ -63,3 +63,15 @@ bool ImGui::InputTextMultiline(const char* label, std::string* str, const ImVec2 cb_user_data.ChainCallbackUserData = user_data; return InputTextMultiline(label, (char*)str->c_str(), str->capacity() + 1, size, flags, InputTextCallback, &cb_user_data); } + +bool ImGui::InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) +{ + IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); + flags |= ImGuiInputTextFlags_CallbackResize; + + InputTextCallback_UserData cb_user_data; + cb_user_data.Str = str; + cb_user_data.ChainCallback = callback; + cb_user_data.ChainCallbackUserData = user_data; + return InputTextWithHint(label, hint, (char*)str->c_str(), str->capacity() + 1, flags, InputTextCallback, &cb_user_data); +} diff --git a/misc/cpp/imgui_stdlib.h b/misc/cpp/imgui_stdlib.h index 06b06b9a..5bccb032 100644 --- a/misc/cpp/imgui_stdlib.h +++ b/misc/cpp/imgui_stdlib.h @@ -19,4 +19,5 @@ namespace ImGui // Because text input needs dynamic resizing, we need to setup a callback to grow the capacity IMGUI_API bool InputText(const char* label, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputTextMultiline(const char* label, std::string* str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); } From c779fbb651a5979e0701949b90898e6b7cae3390 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Mar 2019 17:33:24 +0100 Subject: [PATCH 130/566] InputTextWithHint: Fix for Password fields. Update changelog, demo. (#2400) --- docs/CHANGELOG.txt | 4 +++- imgui_demo.cpp | 4 +++- imgui_widgets.cpp | 60 +++++++++++++++++++--------------------------- 3 files changed, 30 insertions(+), 38 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7f002f30..1f928008 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,7 +45,9 @@ Other Changes: - Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered behind every other windows. (#2391) - DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. - We are reusing function instances for larger types to reduce code size. (#643, #320, #708, #1011) + We are reusing function instances of larger types to reduce code size. (#643, #320, #708, #1011) +- Added InputTextWithHint() to display a description/hint in the text box when no text + has been entered. (#2400) [@Organic-Code, @ocornut] - Nav: Fixed a tap on AltGR (e.g. German keyboard) from navigating to the menu layer. - Nav: Fixed Ctrl+Tab keeping active InputText() of a previous window active after the switch. (#2380) - Fixed IsItemDeactivated()/IsItemDeactivatedAfterEdit() from not correctly returning true diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1ecf49b8..f8f23c2f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -770,6 +770,7 @@ static void ShowDemoWindowWidgets() // Expose flags as checkbox for the demo static ImGuiComboFlags flags = 0; ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", (unsigned int*)&flags, ImGuiComboFlags_PopupAlignLeft); + ImGui::SameLine(); ShowHelpMarker("Only makes a difference if the popup is larger than the combo"); if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", (unsigned int*)&flags, ImGuiComboFlags_NoArrowButton)) flags &= ~ImGuiComboFlags_NoPreview; // Clear the other flag, as we cannot combine both if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", (unsigned int*)&flags, ImGuiComboFlags_NoPreview)) @@ -934,6 +935,7 @@ static void ShowDemoWindowWidgets() static char bufpass[64] = "password123"; ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); ImGui::SameLine(); ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputTextWithHint("password (w/ hint)", "", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); ImGui::TreePop(); @@ -2177,7 +2179,7 @@ static void ShowDemoWindowPopups() // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the Begin call. // So here we will make it that clicking on the text field with the right mouse button (1) will toggle the visibility of the popup above. - ImGui::Text("(You can also right-click me to the same popup as above.)"); + ImGui::Text("(You can also right-click me to open the same popup as above.)"); ImGui::OpenPopupOnItemClick("item context menu", 1); // When used after an item that has an ID (here the Button), we can skip providing an ID to BeginPopupContextItem(). diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 388d5547..bb514efc 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2904,7 +2904,8 @@ bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, co bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { - return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); } static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) @@ -3364,8 +3365,18 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ bool value_changed = false; bool enter_pressed = false; + // Select the buffer to render. + const char* buf_display = ((render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; + const char* buf_display_end = NULL; // We have specialized paths below for setting the length + const bool is_displaying_hint = (hint != NULL && buf_display[0] == 0); + if (is_displaying_hint) + { + buf_display = hint; + buf_display_end = hint + strlen(hint); + } + // Password pushes a temporary font with only a fallback glyph - if (is_password) + if (is_password && !is_displaying_hint) { const ImFontGlyph* glyph = g.Font->FindGlyph('*'); ImFont* password_font = &g.InputTextPasswordFont; @@ -3729,14 +3740,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. const int buf_display_max_length = 2 * 1024 * 1024; - const char* buf_display = NULL; - const char* buf_display_end = NULL; - ImGuiCol text_color = ImGuiCol_COUNT; // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. if (render_cursor || render_selection) { + if (!is_displaying_hint) + buf_display_end = buf_display + state->CurLenA; + // Render text (with cursor and selection) // This is going to be messy. We need to: // - Display the text (this alone can be more easily clipped) @@ -3868,25 +3879,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } } - if (state->CurLenA != 0 || hint == NULL) - { - buf_display = (!is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; - buf_display_end = buf_display + state->CurLenA; - text_color = ImGuiCol_Text; - } - else - { - buf_display = hint; - buf_display_end = hint + strlen(hint); - text_color = ImGuiCol_TextDisabled; - } - - // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { - IM_ASSERT(text_color != ImGuiCol_COUNT); - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, GetColorU32(text_color), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); } // Draw blinking cursor @@ -3907,26 +3904,17 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else { // Render text only (no selection, no cursor) - text_color = ImGuiCol_Text; - buf_display = (g.ActiveId == id && !is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; if (is_multiline) text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width - else if (g.ActiveId == id) + else if (!is_displaying_hint && g.ActiveId == id) buf_display_end = buf_display + state->CurLenA; - else + else if (!is_displaying_hint) buf_display_end = buf_display + strlen(buf_display); - if (buf_display_end == buf_display && hint != NULL) - { - buf_display = hint; - buf_display_end = buf_display + strlen(buf_display); - text_color = ImGuiCol_TextDisabled; - } - if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { - IM_ASSERT(text_color != ImGuiCol_COUNT); - draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, GetColorU32(text_color), buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); + ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); + draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); } } @@ -3937,11 +3925,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ EndGroup(); } - if (is_password) + if (is_password && !is_displaying_hint) PopFont(); // Log as text - if (g.LogEnabled && !is_password) + if (g.LogEnabled && !(is_password && !is_displaying_hint)) LogRenderedText(&draw_pos, buf_display, buf_display_end); if (label_size.x > 0) From 510342f02483f930c2f07e24e05ced024bbd6bef Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Mar 2019 18:00:04 +0100 Subject: [PATCH 131/566] Examples: DirectX9: Minor changes to match the other DirectX examples more closely. (#2394) --- docs/CHANGELOG.txt | 1 + examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 82 +++++++++++++---------- 4 files changed, 51 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1f928008..722ca610 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -84,6 +84,7 @@ Other Changes: - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) - Examples: Allegro: Added support for touch events (emulating mouse). (#2219) [@dos1] +- Examples: DirectX9: Minor changes to match the other DirectX examples more closely. (#2394) ----------------------------------------------------------------------- diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 344af239..7e3dd922 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -18,7 +18,7 @@ static ID3D10RenderTargetView* g_mainRenderTargetView = NULL; void CreateRenderTarget() { ID3D10Texture2D* pBackBuffer; - g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer); + g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); pBackBuffer->Release(); } diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 7cfa0abc..a08c8cb4 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -18,7 +18,7 @@ static ID3D11RenderTargetView* g_mainRenderTargetView = NULL; void CreateRenderTarget() { ID3D11Texture2D* pBackBuffer; - g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); + g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); pBackBuffer->Release(); } diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 11ef1bac..eee800e0 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -10,8 +10,44 @@ #include // Data +static LPDIRECT3D9 g_pD3D = NULL; static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; -static D3DPRESENT_PARAMETERS g_d3dpp; +static D3DPRESENT_PARAMETERS g_d3dpp = {}; + +HRESULT CreateDeviceD3D(HWND hWnd) +{ + if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) + return E_FAIL; + + // Create the D3DDevice + ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); + g_d3dpp.Windowed = TRUE; + g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; + g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; + g_d3dpp.EnableAutoDepthStencil = TRUE; + g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; + g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync + //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate + if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) + return E_FAIL; + + return S_OK; +} + +void CleanupDeviceD3D() +{ + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } + if (g_pD3D) { g_pD3D->Release(); g_pD3D = NULL; } +} + +void ResetDevice() +{ + ImGui_ImplDX9_InvalidateDeviceObjects(); + HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); + if (hr == D3DERR_INVALIDCALL) + IM_ASSERT(0); + ImGui_ImplDX9_CreateDeviceObjects(); +} extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) @@ -24,13 +60,9 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { - ImGui_ImplDX9_InvalidateDeviceObjects(); - g_d3dpp.BackBufferWidth = LOWORD(lParam); + g_d3dpp.BackBufferWidth = LOWORD(lParam); g_d3dpp.BackBufferHeight = HIWORD(lParam); - HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); - if (hr == D3DERR_INVALIDCALL) - IM_ASSERT(0); - ImGui_ImplDX9_CreateDeviceObjects(); + ResetDevice(); } return 0; case WM_SYSCOMMAND: @@ -52,28 +84,16 @@ int main(int, char**) HWND hwnd = CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D - LPDIRECT3D9 pD3D; - if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) + if (CreateDeviceD3D(hwnd) < 0) { + CleanupDeviceD3D(); UnregisterClass(wc.lpszClassName, wc.hInstance); - return 0; + return 1; } - ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); - g_d3dpp.Windowed = TRUE; - g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; - g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; - g_d3dpp.EnableAutoDepthStencil = TRUE; - g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; - g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync - //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate - // Create the D3DDevice - if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) - { - pD3D->Release(); - UnregisterClass(wc.lpszClassName, wc.hInstance); - return 0; - } + // Show the window + ShowWindow(hwnd, SW_SHOWDEFAULT); + UpdateWindow(hwnd); // Setup Dear ImGui context IMGUI_CHECKVERSION(); @@ -104,6 +124,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); @@ -111,8 +132,6 @@ int main(int, char**) // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); - ShowWindow(hwnd, SW_SHOWDEFAULT); - UpdateWindow(hwnd); while (msg.message != WM_QUIT) { // Poll and handle messages (inputs, window resize, etc.) @@ -186,19 +205,14 @@ int main(int, char**) // Handle loss of D3D9 device if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET) - { - ImGui_ImplDX9_InvalidateDeviceObjects(); - g_pd3dDevice->Reset(&g_d3dpp); - ImGui_ImplDX9_CreateDeviceObjects(); - } + ResetDevice(); } ImGui_ImplDX9_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); - if (g_pd3dDevice) g_pd3dDevice->Release(); - if (pD3D) pD3D->Release(); + CleanupDeviceD3D(); DestroyWindow(hwnd); UnregisterClass(wc.lpszClassName, wc.hInstance); From ea8158acdf943ed90f0d3f7c72bddae5ee30f005 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Mar 2019 18:19:28 +0100 Subject: [PATCH 132/566] Demo: Renamed ShowHelpMarker() -> HelpMarker(). Fixed minor PVS warning. Removed unnecessary casts. --- imgui_demo.cpp | 110 +++++++++++++++++++++++----------------------- imgui_widgets.cpp | 14 +++--- 2 files changed, 62 insertions(+), 62 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f8f23c2f..13757b29 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -126,7 +126,7 @@ static void ShowExampleAppCustomRendering(bool* p_open); static void ShowExampleMenuFile(); // Helper to display a little (?) mark which shows a tooltip when hovered. -static void ShowHelpMarker(const char* desc) +static void HelpMarker(const char* desc) { ImGui::TextDisabled("(?)"); if (ImGui::IsItemHovered()) @@ -311,9 +311,9 @@ void ImGui::ShowDemoWindow(bool* p_open) { ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); - ImGui::SameLine(); ShowHelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); + ImGui::SameLine(); HelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); - ImGui::SameLine(); ShowHelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); + ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) // Create a way to restore this flag otherwise we could be stuck completely! { @@ -326,21 +326,21 @@ void ImGui::ShowDemoWindow(bool* p_open) io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; } ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); - ImGui::SameLine(); ShowHelpMarker("Instruct back-end to not alter mouse cursor shape and visibility."); + ImGui::SameLine(); HelpMarker("Instruct back-end to not alter mouse cursor shape and visibility."); ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); - ImGui::SameLine(); ShowHelpMarker("Set to false to disable blinking cursor, for users who consider it distracting"); + ImGui::SameLine(); HelpMarker("Set to false to disable blinking cursor, for users who consider it distracting"); ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges); - ImGui::SameLine(); ShowHelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback."); + ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback."); ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly); ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); - ImGui::SameLine(); ShowHelpMarker("Instruct Dear ImGui to render a mouse cursor for you. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); + ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor for you. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); ImGui::TreePop(); ImGui::Separator(); } if (ImGui::TreeNode("Backend Flags")) { - ShowHelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities."); + HelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities."); ImGuiBackendFlags backend_flags = io.BackendFlags; // Make a local copy to avoid modifying the back-end flags. ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); @@ -359,7 +359,7 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Capture/Logging")) { ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded."); - ShowHelpMarker("Try opening any of the contents below in this window and then click one of the \"Log To\" button."); + HelpMarker("Try opening any of the contents below in this window and then click one of the \"Log To\" button."); ImGui::LogButtons(); ImGui::TextWrapped("You can also call ImGui::LogText() to output directly to the log without a visual output."); if (ImGui::Button("Copy \"Hello, world!\" to clipboard")) @@ -476,20 +476,20 @@ static void ShowDemoWindowWidgets() const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; static int item_current = 0; ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); - ImGui::SameLine(); ShowHelpMarker("Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n"); + ImGui::SameLine(); HelpMarker("Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n"); } { static char str0[128] = "Hello, world!"; ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); - ImGui::SameLine(); ShowHelpMarker("USER:\nHold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n\nPROGRAMMER:\nYou can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated in imgui_demo.cpp)."); + ImGui::SameLine(); HelpMarker("USER:\nHold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n\nPROGRAMMER:\nYou can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated in imgui_demo.cpp)."); static char str1[128] = ""; ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1)); static int i0 = 123; ImGui::InputInt("input int", &i0); - ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); + ImGui::SameLine(); HelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); static float f0 = 0.001f; ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); @@ -499,7 +499,7 @@ static void ShowDemoWindowWidgets() static float f1 = 1.e10f; ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); - ImGui::SameLine(); ShowHelpMarker("You can input value using the scientific notation,\n e.g. \"1e+8\" becomes \"100000000\".\n"); + ImGui::SameLine(); HelpMarker("You can input value using the scientific notation,\n e.g. \"1e+8\" becomes \"100000000\".\n"); static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; ImGui::InputFloat3("input float3", vec4a); @@ -508,7 +508,7 @@ static void ShowDemoWindowWidgets() { static int i1 = 50, i2 = 42; ImGui::DragInt("drag int", &i1, 1); - ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value."); + ImGui::SameLine(); HelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value."); ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%"); @@ -520,7 +520,7 @@ static void ShowDemoWindowWidgets() { static int i1=0; ImGui::SliderInt("slider int", &i1, -1, 3); - ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value."); + ImGui::SameLine(); HelpMarker("CTRL+click to input value."); static float f1=0.123f, f2=0.0f; ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); @@ -533,7 +533,7 @@ static void ShowDemoWindowWidgets() static float col1[3] = { 1.0f,0.0f,0.2f }; static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; ImGui::ColorEdit3("color 1", col1); - ImGui::SameLine(); ShowHelpMarker("Click on the colored square to open a color picker.\nClick and hold to use drag and drop.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n"); + ImGui::SameLine(); HelpMarker("Click on the colored square to open a color picker.\nClick and hold to use drag and drop.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n"); ImGui::ColorEdit4("color 2", col2); } @@ -576,7 +576,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Advanced, with Selectable nodes")) { - ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); + HelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); static bool align_label_with_current_x_position = false; ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position); ImGui::Text("Hello!"); @@ -663,7 +663,7 @@ static void ShowDemoWindowWidgets() ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); ImGui::TextDisabled("Disabled"); - ImGui::SameLine(); ShowHelpMarker("The TextDisabled color is stored in ImGuiStyle."); + ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle."); ImGui::TreePop(); } @@ -770,7 +770,7 @@ static void ShowDemoWindowWidgets() // Expose flags as checkbox for the demo static ImGuiComboFlags flags = 0; ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", (unsigned int*)&flags, ImGuiComboFlags_PopupAlignLeft); - ImGui::SameLine(); ShowHelpMarker("Only makes a difference if the popup is larger than the combo"); + ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo"); if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", (unsigned int*)&flags, ImGuiComboFlags_NoArrowButton)) flags &= ~ImGuiComboFlags_NoPreview; // Clear the other flag, as we cannot combine both if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", (unsigned int*)&flags, ImGuiComboFlags_NoPreview)) @@ -841,7 +841,7 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Selection State: Multiple Selection")) { - ShowHelpMarker("Hold CTRL and click to select multiple items."); + HelpMarker("Hold CTRL and click to select multiple items."); static bool selection[5] = { false, false, false, false, false }; for (int n = 0; n < 5; n++) { @@ -901,7 +901,7 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Alignment")) { - ShowHelpMarker("Alignment applies when a selectable is larger than its text content.\nBy default, Selectables uses style.SelectableTextAlign but it can be overriden on a per-item basis using PushStyleVar()."); + HelpMarker("Alignment applies when a selectable is larger than its text content.\nBy default, Selectables uses style.SelectableTextAlign but it can be overriden on a per-item basis using PushStyleVar()."); static bool selected[3*3] = { true, false, true, false, true, false, true, false, true }; for (int y = 0; y < 3; y++) { @@ -934,7 +934,7 @@ static void ShowDemoWindowWidgets() ImGui::Text("Password input"); static char bufpass[64] = "password123"; ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); - ImGui::SameLine(); ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); ImGui::InputTextWithHint("password (w/ hint)", "", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); @@ -958,7 +958,7 @@ static void ShowDemoWindowWidgets() "\tlock cmpxchg8b eax\n"; static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; - ShowHelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp)"); + HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp)"); ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly); ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput); ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine); @@ -1042,12 +1042,12 @@ static void ShowDemoWindowWidgets() ImGui::Checkbox("With Alpha Preview", &alpha_preview); ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview); ImGui::Checkbox("With Drag and Drop", &drag_and_drop); - ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); ShowHelpMarker("Right-click on the individual color widget to show options."); - ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); ShowHelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); + ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); + ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); int misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions); ImGui::Text("Color widget:"); - ImGui::SameLine(); ShowHelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n"); + ImGui::SameLine(); HelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n"); ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); ImGui::Text("Color widget HSV with Alpha:"); @@ -1057,7 +1057,7 @@ static void ShowDemoWindowWidgets() ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); ImGui::Text("Color button with Picker:"); - ImGui::SameLine(); ShowHelpMarker("With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\nWith the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only be used for the tooltip and picker popup."); + ImGui::SameLine(); HelpMarker("With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\nWith the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only be used for the tooltip and picker popup."); ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags); ImGui::Text("Color button with Custom Picker Popup:"); @@ -1149,9 +1149,9 @@ static void ShowDemoWindowWidgets() } } ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0"); - ImGui::SameLine(); ShowHelpMarker("ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); + ImGui::SameLine(); HelpMarker("ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0"); - ImGui::SameLine(); ShowHelpMarker("User can right-click the picker to change mode."); + ImGui::SameLine(); HelpMarker("User can right-click the picker to change mode."); ImGuiColorEditFlags flags = misc_flags; if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4() if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar; @@ -1165,7 +1165,7 @@ static void ShowDemoWindowWidgets() ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); ImGui::Text("Programmatically set defaults:"); - ImGui::SameLine(); ShowHelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible."); + ImGui::SameLine(); HelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible."); if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); if (ImGui::Button("Default: Float + HDR + Hue Wheel")) @@ -1230,7 +1230,7 @@ static void ShowDemoWindowWidgets() const float drag_speed = 0.2f; static bool drag_clamp = false; ImGui::Text("Drags:"); - ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); ImGui::SameLine(); ShowHelpMarker("As with every widgets in dear imgui, we never modify values unless there is a user interaction.\nYou can override the clamping limits by using CTRL+Click to input a value."); + ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); ImGui::SameLine(); HelpMarker("As with every widgets in dear imgui, we never modify values unless there is a user interaction.\nYou can override the clamping limits by using CTRL+Click to input a value."); ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); @@ -1240,7 +1240,7 @@ static void ShowDemoWindowWidgets() ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL); ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", 1.0f); - ImGui::DragScalar("drag float ^2", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", 2.0f); ImGui::SameLine(); ShowHelpMarker("You can use the 'power' parameter to increase tweaking precision on one side of the range."); + ImGui::DragScalar("drag float ^2", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", 2.0f); ImGui::SameLine(); HelpMarker("You can use the 'power' parameter to increase tweaking precision on one side of the range."); ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams", 1.0f); ImGui::DragScalar("drag double ^2", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", 2.0f); @@ -1589,7 +1589,7 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Child windows")) { - ShowHelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window."); + 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; ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel); @@ -1673,31 +1673,31 @@ static void ShowDemoWindowLayout() { static float f = 0.0f; ImGui::Text("PushItemWidth(100)"); - ImGui::SameLine(); ShowHelpMarker("Fixed width."); + ImGui::SameLine(); HelpMarker("Fixed width."); ImGui::PushItemWidth(100); ImGui::DragFloat("float##1", &f); ImGui::PopItemWidth(); ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)"); - ImGui::SameLine(); ShowHelpMarker("Half of window width."); + ImGui::SameLine(); HelpMarker("Half of window width."); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::DragFloat("float##2", &f); ImGui::PopItemWidth(); ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); - ImGui::SameLine(); ShowHelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); + ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); ImGui::DragFloat("float##3", &f); ImGui::PopItemWidth(); ImGui::Text("PushItemWidth(-100)"); - ImGui::SameLine(); ShowHelpMarker("Align to right edge minus 100"); + ImGui::SameLine(); HelpMarker("Align to right edge minus 100"); ImGui::PushItemWidth(-100); ImGui::DragFloat("float##4", &f); ImGui::PopItemWidth(); ImGui::Text("PushItemWidth(-1)"); - ImGui::SameLine(); ShowHelpMarker("Align to right edge"); + ImGui::SameLine(); HelpMarker("Align to right edge"); ImGui::PushItemWidth(-1); ImGui::DragFloat("float##5", &f); ImGui::PopItemWidth(); @@ -1866,7 +1866,7 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Groups")) { - ShowHelpMarker("Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it."); + HelpMarker("Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it."); ImGui::BeginGroup(); { ImGui::BeginGroup(); @@ -1910,7 +1910,7 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Text Baseline Alignment")) { - ShowHelpMarker("This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets."); + HelpMarker("This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets."); ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); ImGui::Text("Hello\nWorld"); ImGui::SameLine(); @@ -1965,7 +1965,7 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Scrolling")) { - ShowHelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given position."); + HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given position."); static bool track = true; static int track_line = 50, scroll_to_px = 200; @@ -2007,7 +2007,7 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Horizontal Scrolling")) { - ShowHelpMarker("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\nYou may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); + HelpMarker("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\nYou may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); static int lines = 7; ImGui::SliderInt("Lines", &lines, 1, 15); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); @@ -2460,7 +2460,7 @@ static void ShowDemoWindowColumns() } bool node_open = ImGui::TreeNode("Tree within single cell"); - ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell. There's no storage of state per-cell."); + ImGui::SameLine(); HelpMarker("NB: Tree node must be poped before ending the cell. There's no storage of state per-cell."); if (node_open) { ImGui::Columns(2, "tree items"); @@ -2543,7 +2543,7 @@ static void ShowDemoWindowMisc() ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); ImGui::PushAllowKeyboardFocus(false); ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); - //ImGui::SameLine(); ShowHelperMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + //ImGui::SameLine(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); ImGui::PopAllowKeyboardFocus(); ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); ImGui::TreePop(); @@ -2621,7 +2621,7 @@ static void ShowDemoWindowMisc() ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]); ImGui::Text("Hover to see mouse cursors:"); - ImGui::SameLine(); ShowHelpMarker("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, otherwise your backend needs to handle it."); + ImGui::SameLine(); HelpMarker("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, otherwise your backend needs to handle it."); for (int i = 0; i < ImGuiMouseCursor_COUNT; i++) { char label[32]; @@ -2799,7 +2799,7 @@ void ImGui::ShowFontSelector(const char* label) ImGui::EndCombo(); } ImGui::SameLine(); - ShowHelpMarker( + HelpMarker( "- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n" "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n" "- Read FAQ and documentation in misc/fonts/ for more details.\n" @@ -2842,7 +2842,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::Button("Revert Ref")) style = *ref; ImGui::SameLine(); - ShowHelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. Use \"Export Colors\" below to save them somewhere."); + HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. Use \"Export Colors\" below to save them somewhere."); ImGui::Separator(); @@ -2875,9 +2875,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); ImGui::Text("Alignment"); ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); - ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a button is larger than its text content."); - ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a selectable is larger than its text content."); - ImGui::Text("Safe Area Padding"); ImGui::SameLine(); ShowHelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); + ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); + ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); + ImGui::Text("Safe Area Padding"); ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); ImGui::EndTabItem(); } @@ -2912,7 +2912,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::RadioButton("Opaque", &alpha_flags, 0); ImGui::SameLine(); ImGui::RadioButton("Alpha", &alpha_flags, ImGuiColorEditFlags_AlphaPreview); ImGui::SameLine(); ImGui::RadioButton("Both", &alpha_flags, ImGuiColorEditFlags_AlphaPreviewHalf); ImGui::SameLine(); - ShowHelpMarker("In the color list:\nLeft-click on colored square to open color picker,\nRight-click to open edit options menu."); + HelpMarker("In the color list:\nLeft-click on colored square to open color picker,\nRight-click to open edit options menu."); ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); ImGui::PushItemWidth(-160); @@ -2944,7 +2944,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGuiIO& io = ImGui::GetIO(); ImFontAtlas* atlas = io.Fonts; - ShowHelpMarker("Read FAQ and misc/fonts/README.txt for details on font loading."); + HelpMarker("Read FAQ and misc/fonts/README.txt for details on font loading."); ImGui::PushItemWidth(120); for (int i = 0; i < atlas->Fonts.Size; i++) { @@ -2958,7 +2958,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::Text("The quick brown fox jumps over the lazy dog"); ImGui::PopFont(); ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font - ImGui::SameLine(); ShowHelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.\n\n(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)"); + ImGui::SameLine(); HelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.\n\n(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)"); ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, "%.0f"); ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar); @@ -3027,7 +3027,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::BeginTabItem("Rendering")) { - ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); ShowHelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); + ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, "%.2f", 2.0f); @@ -3701,7 +3701,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open) return; } - ShowHelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API."); + HelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API."); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); ImGui::Columns(2); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bb514efc..0e63a14d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1155,7 +1155,7 @@ void ImGui::Separator() // Those flags should eventually be overridable by the user ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; - IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected if (flags & ImGuiSeparatorFlags_Vertical) { VerticalSeparator(); @@ -3366,7 +3366,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ bool enter_pressed = false; // Select the buffer to render. - const char* buf_display = ((render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state->TextAIsValid) ? state->TextA.Data : buf; + const char* buf_display = ((render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid) ? state->TextA.Data : buf; const char* buf_display_end = NULL; // We have specialized paths below for setting the length const bool is_displaying_hint = (hint != NULL && buf_display[0] == 0); if (is_displaying_hint) @@ -3745,6 +3745,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. if (render_cursor || render_selection) { + IM_ASSERT(state != NULL); if (!is_displaying_hint) buf_display_end = buf_display + state->CurLenA; @@ -3755,7 +3756,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. - IM_ASSERT(state != NULL); const ImWchar* text_begin = state->TextW.Data; ImVec2 cursor_offset, select_start_offset; @@ -4266,7 +4266,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // Read stored options if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask; - IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check that only 1 is selected if (!(flags & ImGuiColorEditFlags_NoOptions)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar); @@ -4637,9 +4637,9 @@ void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask; if ((flags & ImGuiColorEditFlags__PickerMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask; - IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DisplayMask))); // Check only 1 option is selected - IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected - IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DataTypeMask)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check only 1 option is selected g.ColorEditOptions = flags; } From 8464df1f6e0e7349e2fc4db797bbc552358b9078 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 6 Mar 2019 19:12:53 +0100 Subject: [PATCH 133/566] Internals: ColorEdit: Minor optimizations. Initialize internal arrays as static const, avoid unnecessary HSV->RGB conversion. --- imgui_widgets.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0e63a14d..965cef97 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4022,14 +4022,14 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); - const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; - const char* fmt_table_int[3][4] = + static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; + static const char* fmt_table_int[3][4] = { { "%3d", "%3d", "%3d", "%3d" }, // Short display { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA }; - const char* fmt_table_float[3][4] = + static const char* fmt_table_float[3][4] = { { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA @@ -4129,21 +4129,19 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag } // Convert back - if (picker_active_window == NULL) + if (value_changed && picker_active_window == NULL) { if (!value_changed_as_float) for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if (flags & ImGuiColorEditFlags_DisplayHSV) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); - if (value_changed) - { - col[0] = f[0]; - col[1] = f[1]; - col[2] = f[2]; - if (alpha) - col[3] = f[3]; - } + + col[0] = f[0]; + col[1] = f[1]; + col[2] = f[2]; + if (alpha) + col[3] = f[3]; } PopID(); @@ -4395,12 +4393,14 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); if ((flags & ImGuiColorEditFlags_NoLabel)) Text("Current"); - ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)); + + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip; + ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)); if (ref_col != NULL) { Text("Original"); ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]); - if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2))) + if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2))) { memcpy(col, ref_col, components * sizeof(float)); value_changed = true; From 0a6c5bc2347a27e4922281353ee6cb56cd66fe28 Mon Sep 17 00:00:00 2001 From: Gilad Reich Date: Wed, 6 Mar 2019 21:34:37 +0100 Subject: [PATCH 134/566] Examples: DirectX9: Added support for multi-viewport (#2394) --- examples/example_win32_directx9/main.cpp | 31 ++++++ examples/imgui_impl_dx9.cpp | 123 ++++++++++++++++++++++- examples/imgui_impl_dx9.h | 1 + 3 files changed, 154 insertions(+), 1 deletion(-) diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 6b5e731e..9833ca93 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -49,6 +49,10 @@ void ResetDevice() ImGui_ImplDX9_CreateDeviceObjects(); } +#ifndef WM_DPICHANGED +#define WM_DPICHANGED 0x02E0 // From Windows SDK 8.1+ headers +#endif + extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { @@ -72,12 +76,23 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) case WM_DESTROY: PostQuitMessage(0); return 0; + case WM_DPICHANGED: + if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) + { + //const int dpi = HIWORD(wParam); + //printf("WM_DPICHANGED to %d (%.0f%%)\n", dpi, (float)dpi / 96.0f * 100.0f); + const RECT* suggested_rect = (RECT*)lParam; + ::SetWindowPos(hWnd, NULL, suggested_rect->left, suggested_rect->top, suggested_rect->right - suggested_rect->left, suggested_rect->bottom - suggested_rect->top, SWP_NOZORDER | SWP_NOACTIVATE); + } + break; } return DefWindowProc(hWnd, msg, wParam, lParam); } int main(int, char**) { + ImGui_ImplWin32_EnableDpiAwareness(); + // Create application window WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; RegisterClassEx(&wc); @@ -109,6 +124,14 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); + // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. + ImGuiStyle& style = ImGui::GetStyle(); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + style.WindowRounding = 0.0f; + style.Colors[ImGuiCol_WindowBg].w = 1.0f; + } + // Setup Platform/Renderer bindings ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX9_Init(g_pd3dDevice); @@ -205,6 +228,14 @@ int main(int, char**) ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); g_pd3dDevice->EndScene(); } + + // Update and Render additional Platform Windows + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + ImGui::UpdatePlatformWindows(); + ImGui::RenderPlatformWindowsDefault(); + } + HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL); // Handle loss of D3D9 device diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 378524e0..e4f46850 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -10,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2018-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example. @@ -41,6 +43,10 @@ struct CUSTOMVERTEX }; #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) +// Forward Declarations +static void ImGui_ImplDX9_InitPlatformInterface(); +static void ImGui_ImplDX9_ShutdownPlatformInterface(); + // Render function. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) @@ -203,16 +209,22 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { ImGuiIO& io = ImGui::GetIO(); + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) io.BackendRendererName = "imgui_impl_dx9"; g_pd3dDevice = device; + + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + ImGui_ImplDX9_InitPlatformInterface(); + return true; } void ImGui_ImplDX9_Shutdown() { + ImGui_ImplDX9_ShutdownPlatformInterface(); ImGui_ImplDX9_InvalidateDeviceObjects(); - g_pd3dDevice = NULL; + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } } static bool ImGui_ImplDX9_CreateFontsTexture() @@ -278,3 +290,112 @@ void ImGui_ImplDX9_NewFrame() if (!g_FontTexture) ImGui_ImplDX9_CreateDeviceObjects(); } + +//-------------------------------------------------------------------------------------------------------- +// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT +// This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously. +// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. +//-------------------------------------------------------------------------------------------------------- + +struct ImGuiViewportDataDx9 +{ + IDirect3DSwapChain9* SwapChain; + D3DPRESENT_PARAMETERS d3dpp; + + ImGuiViewportDataDx9() { SwapChain = NULL; ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS)); } + ~ImGuiViewportDataDx9() { IM_ASSERT(SwapChain == NULL); } +}; + +static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport) +{ + ImGuiViewportDataDx9* data = IM_NEW(ImGuiViewportDataDx9)(); + viewport->RendererUserData = data; + + HWND hWnd = (HWND)viewport->PlatformHandle; + IM_ASSERT(hWnd != 0); + + ZeroMemory(&data->d3dpp, sizeof(D3DPRESENT_PARAMETERS)); + data->d3dpp.Windowed = TRUE; + data->d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; + data->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; + data->d3dpp.hDeviceWindow = hWnd; + data->d3dpp.EnableAutoDepthStencil = TRUE; + data->d3dpp.AutoDepthStencilFormat = D3DFMT_D16; + data->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync + + g_pd3dDevice->CreateAdditionalSwapChain(&data->d3dpp, &data->SwapChain); + IM_ASSERT(data->SwapChain != NULL); +} + +static void ImGui_ImplDX9_DestroyWindow(ImGuiViewport* viewport) +{ + // The main viewport (owned by the application) will always have RendererUserData == NULL since we didn't create the data for it. + if (ImGuiViewportDataDx9* data = (ImGuiViewportDataDx9*)viewport->RendererUserData) + { + if (data->SwapChain) + data->SwapChain->Release(); + data->SwapChain = NULL; + ZeroMemory(&data->d3dpp, sizeof(D3DPRESENT_PARAMETERS)); + IM_DELETE(data); + } + viewport->RendererUserData = NULL; +} + +static void ImGui_ImplDX9_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) +{ + ImGuiViewportDataDx9* data = (ImGuiViewportDataDx9*)viewport->RendererUserData; + if (data->SwapChain) + { + data->SwapChain->Release(); + data->SwapChain = NULL; + data->d3dpp.BackBufferWidth = (UINT)size.x; + data->d3dpp.BackBufferHeight = (UINT)size.y; + g_pd3dDevice->CreateAdditionalSwapChain(&data->d3dpp, &data->SwapChain); + } +} + +static void ImGui_ImplDX9_RenderWindow(ImGuiViewport* viewport, void*) +{ + ImGuiViewportDataDx9* data = (ImGuiViewportDataDx9*)viewport->RendererUserData; + ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + + LPDIRECT3DSURFACE9 render_target = NULL; + LPDIRECT3DSURFACE9 last_render_target = NULL; + data->SwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &render_target); + g_pd3dDevice->GetRenderTarget(0, &last_render_target); + g_pd3dDevice->SetRenderTarget(0, render_target); + + if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear)) + { + D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f)); + g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); + } + + ImGui_ImplDX9_RenderDrawData(viewport->DrawData); + + // Restore render target + g_pd3dDevice->SetRenderTarget(0, last_render_target); + render_target->Release(); + last_render_target->Release(); +} + +static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*) +{ + ImGuiViewportDataDx9* data = (ImGuiViewportDataDx9*)viewport->RendererUserData; + data->SwapChain->Present(NULL, NULL, data->d3dpp.hDeviceWindow, NULL, NULL); +} + +static void ImGui_ImplDX9_InitPlatformInterface() +{ + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + platform_io.Renderer_CreateWindow = ImGui_ImplDX9_CreateWindow; + platform_io.Renderer_DestroyWindow = ImGui_ImplDX9_DestroyWindow; + platform_io.Renderer_SetWindowSize = ImGui_ImplDX9_SetWindowSize; + platform_io.Renderer_RenderWindow = ImGui_ImplDX9_RenderWindow; + platform_io.Renderer_SwapBuffers = ImGui_ImplDX9_SwapBuffers; +} + +static void ImGui_ImplDX9_ShutdownPlatformInterface() +{ + ImGui::DestroyPlatformWindows(); +} diff --git a/examples/imgui_impl_dx9.h b/examples/imgui_impl_dx9.h index 95902f74..86953684 100644 --- a/examples/imgui_impl_dx9.h +++ b/examples/imgui_impl_dx9.h @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. From 28d8eb220b7307df4a5c9b90b8cdf6f9cc44f2c8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 16:07:16 +0100 Subject: [PATCH 135/566] Fix for Android char being unsigned by default (#2408) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index deedfc15..214cfc05 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10684,7 +10684,7 @@ struct ImGuiDockNodeSettings ImGuiID ID; ImGuiID ParentID; ImGuiID SelectedTabID; - char SplitAxis; + signed char SplitAxis; char Depth; char IsDockSpace; char IsCentralNode; From 1c23981782a9c1c20b97f6a5bfb101f29b5bca55 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 16:09:11 +0100 Subject: [PATCH 136/566] Made ImS8 and ImS16 explicitly signed in case some crazy SDK decide to flip the signedness over. (#2408) --- imgui.h | 4 ++-- imgui_widgets.cpp | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui.h b/imgui.h index 748313ec..9ee597bf 100644 --- a/imgui.h +++ b/imgui.h @@ -150,9 +150,9 @@ typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Scalar data types -typedef char ImS8; // 8-bit signed integer == char +typedef signed char ImS8; // 8-bit signed integer == char typedef unsigned char ImU8; // 8-bit unsigned integer -typedef short ImS16; // 16-bit signed integer +typedef signed short ImS16; // 16-bit signed integer typedef unsigned short ImU16; // 16-bit unsigned integer typedef signed int ImS32; // 32-bit signed integer == int typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 965cef97..0f52b454 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -74,12 +74,12 @@ Index of this file: //------------------------------------------------------------------------- // Those MIN/MAX values are not define because we need to point to them -static const char IM_S8_MIN = -128; -static const char IM_S8_MAX = 127; +static const signed char IM_S8_MIN = -128; +static const signed char IM_S8_MAX = 127; static const unsigned char IM_U8_MIN = 0; static const unsigned char IM_U8_MAX = 0xFF; -static const short IM_S16_MIN = -32768; -static const short IM_S16_MAX = 32767; +static const signed short IM_S16_MIN = -32768; +static const signed short IM_S16_MAX = 32767; static const unsigned short IM_U16_MIN = 0; static const unsigned short IM_U16_MAX = 0xFFFF; static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000); From e9651aaa77ae1b58ee824a3958141bbb1bcbe12e Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 17:45:59 +0100 Subject: [PATCH 137/566] TabBar: Fixed ImGuiTabItemFlags_SetSelected being ignored if the tab is not visible (with scrolling policy enabled) or if is currently appearing. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 6 ++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 722ca610..7894556e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,8 @@ Other Changes: - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) +- TabBar: Fixed ImGuiTabItemFlags_SetSelected being ignored if the tab is not visible (with + scrolling policy enabled) or if is currently appearing. - Text: Fixed large Text/TextUnformatted call not declaring its size when starting below the lower point of the current clipping rectangle. Somehow this bug has been there since v1.0! It was hardly noticeable but would affect the scrolling range, which in turn would affect diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0f52b454..f276b3f7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6592,6 +6592,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0) if (!tab_bar_appearing || tab_bar->SelectedTabId == 0) tab_bar->NextSelectedTabId = id; // New tabs gets activated + if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar + tab_bar->NextSelectedTabId = id; // Lock visibility bool tab_contents_visible = (tab_bar->VisibleTabId == id); @@ -6643,9 +6645,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); - hovered |= (g.HoveredId == id); - if (pressed || ((flags & ImGuiTabItemFlags_SetSelected) && !tab_contents_visible)) // SetSelected can only be passed on explicit tab bar + if (pressed) tab_bar->NextSelectedTabId = id; + hovered |= (g.HoveredId == id); // Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered) if (!held) From f717df4eb6892cde25c711e76abcdc72db4782e3 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 18:21:56 +0100 Subject: [PATCH 138/566] Internal: Columns: Allow to use BeginColumns(1) so code designed for variable number of columns can still call NextColumn etc. (#125) --- imgui.cpp | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4805c673..35ba2d7e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8210,10 +8210,18 @@ void ImGui::NextColumn() return; ImGuiContext& g = *GImGui; + ImGuiColumnsSet* columns = window->DC.ColumnsSet; + + if (columns->Count == 1) + { + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + IM_ASSERT(columns->Current == 0); + return; + } + PopItemWidth(); PopClipRect(); - ImGuiColumnsSet* columns = window->DC.ColumnsSet; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); if (++columns->Current < columns->Count) { @@ -8223,6 +8231,7 @@ void ImGui::NextColumn() } else { + // New line window->DC.ColumnsOffset.x = 0.0f; window->DrawList->ChannelsSetCurrent(0); columns->Current = 0; @@ -8377,7 +8386,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(columns_count > 1); + IM_ASSERT(columns_count >= 1); IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. @@ -8431,8 +8440,11 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag column->ClipRect.ClipWith(window->ClipRect); } - window->DrawList->ChannelsSplit(columns->Count); - PushColumnClipRect(); + if (columns->Count > 1) + { + window->DrawList->ChannelsSplit(columns->Count); + PushColumnClipRect(); + } PushItemWidth(GetColumnWidth() * 0.65f); } @@ -8444,8 +8456,11 @@ void ImGui::EndColumns() IM_ASSERT(columns != NULL); PopItemWidth(); - PopClipRect(); - window->DrawList->ChannelsMerge(); + if (columns->Count > 1) + { + PopClipRect(); + window->DrawList->ChannelsMerge(); + } columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = columns->LineMaxY; From bbb543fc16d38952ff6b72231889e69abbd456dd Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 18:33:45 +0100 Subject: [PATCH 139/566] Refactor: Move viewport code under other subsystem to simplify merging (1) (moving in multiple commits to make diff/patch behave nicely) --- imgui.cpp | 258 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 132 insertions(+), 126 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 214cfc05..21d4b2a0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -69,12 +69,12 @@ CODE // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) // [SECTION] TOOLTIPS // [SECTION] POPUPS -// [SECTION] VIEWPORTS, PLATFORM WINDOWS // [SECTION] KEYBOARD/GAMEPAD NAVIGATION // [SECTION] COLUMNS // [SECTION] DRAG AND DROP // [SECTION] LOGGING/CAPTURING // [SECTION] SETTINGS +// [SECTION] VIEWPORTS, PLATFORM WINDOWS // [SECTION] DOCKING // [SECTION] PLATFORM DEPENDENT HELPERS // [SECTION] METRICS/DEBUG WINDOW @@ -7786,135 +7786,11 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) return window->Pos; } + //----------------------------------------------------------------------------- // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- -ImGuiViewport* ImGui::GetMainViewport() -{ - ImGuiContext& g = *GImGui; - return g.Viewports[0]; -} - -ImGuiViewport* ImGui::FindViewportByID(ImGuiID id) -{ - ImGuiContext& g = *GImGui; - for (int n = 0; n < g.Viewports.Size; n++) - if (g.Viewports[n]->ID == id) - return g.Viewports[n]; - return NULL; -} - -ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle) -{ - ImGuiContext& g = *GImGui; - for (int i = 0; i != g.Viewports.Size; i++) - if (g.Viewports[i]->PlatformHandle == platform_handle) - return g.Viewports[i]; - return NULL; -} - -void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport) -{ - ImGuiContext& g = *GImGui; - (void)current_window; - - if (viewport) - viewport->LastFrameActive = g.FrameCount; - if (g.CurrentViewport == viewport) - return; - g.CurrentViewport = viewport; - //IMGUI_DEBUG_LOG("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); - - // Notify platform layer of viewport changes - // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI - if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport) - g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport); -} - -static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) -{ - window->Viewport = viewport; - window->ViewportId = viewport->ID; - window->ViewportOwned = (viewport->Window == window); -} - -static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) -{ - // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protude and create their own. - ImGuiContext& g = *GImGui; - if (g.IO.ConfigViewportsNoAutoMerge && (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) - if (!window->DockIsActive) - if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0) - return true; - return false; -} - -static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport) -{ - ImGuiContext& g = *GImGui; - if (!(viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) || window->Viewport == viewport || viewport->PlatformWindowMinimized) - return false; - if (!viewport->GetRect().Contains(window->Rect())) - return false; - if (GetWindowAlwaysWantOwnViewport(window)) - return false; - - for (int n = 0; n < g.Windows.Size; n++) - { - ImGuiWindow* window_behind = g.Windows[n]; - if (window_behind == window) - break; - if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow)) - if (window_behind->Viewport->GetRect().Overlaps(window->Rect())) - return false; - } - - // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child) - ImGuiViewportP* old_viewport = window->Viewport; - if (window->ViewportOwned) - for (int n = 0; n < g.Windows.Size; n++) - if (g.Windows[n]->Viewport == old_viewport) - SetWindowViewport(g.Windows[n], viewport); - SetWindowViewport(window, viewport); - BringWindowToDisplayFront(window); - - return true; -} - -// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) -void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) -{ - ImGuiContext& g = *GImGui; - if (viewport->Window) - { - ScaleWindow(viewport->Window, scale); - } - else - { - for (int i = 0; i != g.Windows.Size; i++) - if (g.Windows[i]->Viewport == viewport) - ScaleWindow(g.Windows[i], scale); - } -} - -// If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves. -// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. -// B) It requires Platform_GetWindowFocus to be implemented by back-end. -static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 mouse_platform_pos) -{ - ImGuiContext& g = *GImGui; - ImGuiViewportP* best_candidate = NULL; - for (int n = 0; n < g.Viewports.Size; n++) - { - ImGuiViewportP* viewport = g.Viewports[n]; - if (!(viewport->Flags & ImGuiViewportFlags_NoInputs) && !viewport->PlatformWindowMinimized && viewport->GetRect().Contains(mouse_platform_pos)) - if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount) - best_candidate = viewport; - } - return best_candidate; -} - static void ImGui::UpdateViewportsNewFrame() { ImGuiContext& g = *GImGui; @@ -10611,6 +10487,136 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSetting } +//----------------------------------------------------------------------------- +// [SECTION] VIEWPORTS, PLATFORM WINDOWS +//----------------------------------------------------------------------------- + +ImGuiViewport* ImGui::GetMainViewport() +{ + ImGuiContext& g = *GImGui; + return g.Viewports[0]; +} + +ImGuiViewport* ImGui::FindViewportByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + for (int n = 0; n < g.Viewports.Size; n++) + if (g.Viewports[n]->ID == id) + return g.Viewports[n]; + return NULL; +} + +ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle) +{ + ImGuiContext& g = *GImGui; + for (int i = 0; i != g.Viewports.Size; i++) + if (g.Viewports[i]->PlatformHandle == platform_handle) + return g.Viewports[i]; + return NULL; +} + +void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport) +{ + ImGuiContext& g = *GImGui; + (void)current_window; + + if (viewport) + viewport->LastFrameActive = g.FrameCount; + if (g.CurrentViewport == viewport) + return; + g.CurrentViewport = viewport; + //IMGUI_DEBUG_LOG("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); + + // Notify platform layer of viewport changes + // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI + if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport) + g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport); +} + +static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) +{ + window->Viewport = viewport; + window->ViewportId = viewport->ID; + window->ViewportOwned = (viewport->Window == window); +} + +static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) +{ + // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protude and create their own. + ImGuiContext& g = *GImGui; + if (g.IO.ConfigViewportsNoAutoMerge && (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + if (!window->DockIsActive) + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0) + return true; + return false; +} + +static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport) +{ + ImGuiContext& g = *GImGui; + if (!(viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) || window->Viewport == viewport || viewport->PlatformWindowMinimized) + return false; + if (!viewport->GetRect().Contains(window->Rect())) + return false; + if (GetWindowAlwaysWantOwnViewport(window)) + return false; + + for (int n = 0; n < g.Windows.Size; n++) + { + ImGuiWindow* window_behind = g.Windows[n]; + if (window_behind == window) + break; + if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow)) + if (window_behind->Viewport->GetRect().Overlaps(window->Rect())) + return false; + } + + // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child) + ImGuiViewportP* old_viewport = window->Viewport; + if (window->ViewportOwned) + for (int n = 0; n < g.Windows.Size; n++) + if (g.Windows[n]->Viewport == old_viewport) + SetWindowViewport(g.Windows[n], viewport); + SetWindowViewport(window, viewport); + BringWindowToDisplayFront(window); + + return true; +} + +// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) +void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) +{ + ImGuiContext& g = *GImGui; + if (viewport->Window) + { + ScaleWindow(viewport->Window, scale); + } + else + { + for (int i = 0; i != g.Windows.Size; i++) + if (g.Windows[i]->Viewport == viewport) + ScaleWindow(g.Windows[i], scale); + } +} + +// If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves. +// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. +// B) It requires Platform_GetWindowFocus to be implemented by back-end. +static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 mouse_platform_pos) +{ + ImGuiContext& g = *GImGui; + ImGuiViewportP* best_candidate = NULL; + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP* viewport = g.Viewports[n]; + if (!(viewport->Flags & ImGuiViewportFlags_NoInputs) && !viewport->PlatformWindowMinimized && viewport->GetRect().Contains(mouse_platform_pos)) + if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount) + best_candidate = viewport; + } + return best_candidate; +} + + //----------------------------------------------------------------------------- // [SECTION] DOCKING //----------------------------------------------------------------------------- From bdf60dac6a723d2bb937929a7174145143929aee Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 18:35:14 +0100 Subject: [PATCH 140/566] Refactor: Move viewport code under other subsystem to simplify merging (2) (moving in multiple commits to make diff/patch behave nicely) --- imgui.cpp | 485 +++++++++++++++++++++++++++--------------------------- 1 file changed, 241 insertions(+), 244 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 21d4b2a0..86c93e8f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7791,246 +7791,6 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- -static void ImGui::UpdateViewportsNewFrame() -{ - ImGuiContext& g = *GImGui; - IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); - - // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) - for (int n = 0; n < g.Viewports.Size; n++) - { - ImGuiViewportP* viewport = g.Viewports[n]; - const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated); - if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) - if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) - viewport->PlatformWindowMinimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); - } - - // Create/update main viewport with current platform position and size - ImGuiViewportP* main_viewport = g.Viewports[0]; - IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID); - IM_ASSERT(main_viewport->Window == NULL); - ImVec2 main_viewport_platform_pos = ImVec2(0.0f, 0.0f); - ImVec2 main_viewport_platform_size = g.IO.DisplaySize; - if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) - main_viewport_platform_pos = main_viewport->PlatformWindowMinimized ? main_viewport->Pos : g.PlatformIO.Platform_GetWindowPos(main_viewport); - AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_platform_pos, main_viewport_platform_size, ImGuiViewportFlags_CanHostOtherWindows); - - g.CurrentViewport = NULL; - g.MouseViewport = NULL; - for (int n = 0; n < g.Viewports.Size; n++) - { - // Erase unused viewports - ImGuiViewportP* viewport = g.Viewports[n]; - viewport->Idx = n; - - if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2) - { - // Clear references to this viewport in windows (window->ViewportId becomes the master data) - for (int window_n = 0; window_n < g.Windows.Size; window_n++) - if (g.Windows[window_n]->Viewport == viewport) - { - g.Windows[window_n]->Viewport = NULL; - g.Windows[window_n]->ViewportOwned = false; - } - if (viewport == g.MouseLastHoveredViewport) - g.MouseLastHoveredViewport = NULL; - g.Viewports.erase(g.Viewports.Data + n); - - // Destroy - //IMGUI_DEBUG_LOG("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); - DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here. - IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false); - IM_DELETE(viewport); - n--; - continue; - } - - const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated); - if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) - { - // Update Position and Size (from Platform Window to ImGui) if requested. - // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. - if (!viewport->PlatformWindowMinimized && platform_funcs_available) - { - if (viewport->PlatformRequestMove) - viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); - if (viewport->PlatformRequestResize) - viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); - } - - // Update monitor (we'll use this info to clamp windows and save windows lost in a removed monitor) - viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect()); - } - - // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. - viewport->Alpha = 1.0f; - - // Translate imgui windows when a Host Viewport has been moved - // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) - ImVec2 viewport_delta = viewport->Pos - viewport->LastPos; - if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta.x != 0.0f || viewport_delta.y != 0.0f)) - for (int window_n = 0; window_n < g.Windows.Size; window_n++) - if (g.Windows[window_n]->Viewport == viewport || (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) == 0) - TranslateWindow(g.Windows[window_n], viewport_delta); - - // Update DPI scale - float new_dpi_scale; - if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available) - new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport); - else if (viewport->PlatformMonitor != -1) - new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; - else - new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f; - if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale) - { - float scale_factor = new_dpi_scale / viewport->DpiScale; - if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) - ScaleWindowsInViewport(viewport, scale_factor); - //if (viewport == GetMainViewport()) - // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor); - - // Scale our window moving pivot so that the window will rescale roughly around the mouse position. - // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border. - // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.) - //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport) - // g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor); - } - viewport->DpiScale = new_dpi_scale; - } - - if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) - { - g.MouseViewport = main_viewport; - return; - } - - // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport. - // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set. - ImGuiViewportP* viewport_hovered = NULL; - if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) - { - viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL; - if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) - { - // Back-end failed at honoring its contract if it returned a viewport with the _NoInputs flag. - IM_ASSERT(0); - viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos); - } - } - else - { - // If the back-end doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search: - // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. - // B) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO) - viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos); - } - if (viewport_hovered != NULL) - g.MouseLastHoveredViewport = viewport_hovered; - else if (g.MouseLastHoveredViewport == NULL) - g.MouseLastHoveredViewport = g.Viewports[0]; - - // Update mouse reference viewport - // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode) - if (g.MovingWindow) - g.MouseViewport = g.MovingWindow->Viewport; - else - g.MouseViewport = g.MouseLastHoveredViewport; - - // When dragging something, always refer to the last hovered viewport. - // - when releasing a moving window we will revert to aiming behind (at viewport_hovered) - // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info) - // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release. - const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive; - if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL) - viewport_hovered = g.MouseLastHoveredViewport; - if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown()) - if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) - g.MouseViewport = viewport_hovered; - - IM_ASSERT(g.MouseViewport != NULL); -} - -// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) -static void ImGui::UpdateViewportsEndFrame() -{ - ImGuiContext& g = *GImGui; - g.PlatformIO.MainViewport = g.Viewports[0]; - g.PlatformIO.Viewports.resize(0); - for (int i = 0; i < g.Viewports.Size; i++) - { - ImGuiViewportP* viewport = g.Viewports[i]; - viewport->LastPos = viewport->Pos; - if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f) - if (i > 0) // Always include main viewport in the list - continue; - if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)) - continue; - if (i > 0) - IM_ASSERT(viewport->Window != NULL); - g.PlatformIO.Viewports.push_back(viewport); - } - g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called -} - -// FIXME: We should ideally refactor the system to call this every frame (we currently don't) -ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags) -{ - ImGuiContext& g = *GImGui; - IM_ASSERT(id != 0); - - if (window != NULL) - { - if (g.MovingWindow && g.MovingWindow->RootWindow == window) - flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing; - if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) - flags |= ImGuiViewportFlags_NoInputs; - if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing) - flags |= ImGuiViewportFlags_NoFocusOnAppearing; - } - - ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id); - if (viewport) - { - if (!viewport->PlatformRequestMove) - viewport->Pos = pos; - if (!viewport->PlatformRequestResize) - viewport->Size = size; - } - else - { - // New viewport - viewport = IM_NEW(ImGuiViewportP)(); - viewport->ID = id; - viewport->Idx = g.Viewports.Size; - viewport->Pos = viewport->LastPos = pos; - viewport->Size = size; - viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect()); - g.Viewports.push_back(viewport); - //IMGUI_DEBUG_LOG("Add Viewport %08X (%s)\n", id, window->Name); - - // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. - // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame - g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x); - g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y); - - // Store initial DpiScale before the OS platform window creation, based on expected monitor data. - // This is so we can select an appropriate font size on the first frame of our window lifetime - if (viewport->PlatformMonitor != -1) - viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; - } - - viewport->Window = window; - viewport->Flags = flags; - viewport->LastFrameActive = g.FrameCount; - IM_ASSERT(window == NULL || viewport->ID == window->ID); - - if (window != NULL) - window->ViewportOwned = true; - - return viewport; -} - // FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) { @@ -8045,7 +7805,6 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) SetWindowViewport(window, main_viewport); return; } - window->ViewportOwned = false; // Appearing popups reset their viewport so they can inherit again @@ -8138,7 +7897,6 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); } } - // Regular (non-child, non-popup) windows by default are also allowed to protrude // Child windows are kept contained within their parent. else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) @@ -8146,12 +7904,11 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) // Update flags window->ViewportOwned = (window == window->Viewport->Window); + window->ViewportId = window->Viewport->ID; // If the OS window has a title bar, hide our imgui title bar //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) // window->Flags |= ImGuiWindowFlags_NoTitleBar; - - window->ViewportId = window->Viewport->ID; } // Called by user at the end of the main loop, after EndFrame() @@ -10616,6 +10373,246 @@ static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 m return best_candidate; } +static void ImGui::UpdateViewportsNewFrame() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); + + // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP* viewport = g.Viewports[n]; + const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated); + if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) + viewport->PlatformWindowMinimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); + } + + // Create/update main viewport with current platform position and size + ImGuiViewportP* main_viewport = g.Viewports[0]; + IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID); + IM_ASSERT(main_viewport->Window == NULL); + ImVec2 main_viewport_platform_pos = ImVec2(0.0f, 0.0f); + ImVec2 main_viewport_platform_size = g.IO.DisplaySize; + if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) + main_viewport_platform_pos = main_viewport->PlatformWindowMinimized ? main_viewport->Pos : g.PlatformIO.Platform_GetWindowPos(main_viewport); + AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_platform_pos, main_viewport_platform_size, ImGuiViewportFlags_CanHostOtherWindows); + + g.CurrentViewport = NULL; + g.MouseViewport = NULL; + for (int n = 0; n < g.Viewports.Size; n++) + { + // Erase unused viewports + ImGuiViewportP* viewport = g.Viewports[n]; + viewport->Idx = n; + + if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2) + { + // Clear references to this viewport in windows (window->ViewportId becomes the master data) + for (int window_n = 0; window_n < g.Windows.Size; window_n++) + if (g.Windows[window_n]->Viewport == viewport) + { + g.Windows[window_n]->Viewport = NULL; + g.Windows[window_n]->ViewportOwned = false; + } + if (viewport == g.MouseLastHoveredViewport) + g.MouseLastHoveredViewport = NULL; + g.Viewports.erase(g.Viewports.Data + n); + + // Destroy + //IMGUI_DEBUG_LOG("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here. + IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false); + IM_DELETE(viewport); + n--; + continue; + } + + const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated); + if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + { + // Update Position and Size (from Platform Window to ImGui) if requested. + // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. + if (!viewport->PlatformWindowMinimized && platform_funcs_available) + { + if (viewport->PlatformRequestMove) + viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); + if (viewport->PlatformRequestResize) + viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); + } + + // Update monitor (we'll use this info to clamp windows and save windows lost in a removed monitor) + viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect()); + } + + // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. + viewport->Alpha = 1.0f; + + // Translate imgui windows when a Host Viewport has been moved + // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) + ImVec2 viewport_delta = viewport->Pos - viewport->LastPos; + if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta.x != 0.0f || viewport_delta.y != 0.0f)) + for (int window_n = 0; window_n < g.Windows.Size; window_n++) + if (g.Windows[window_n]->Viewport == viewport || (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) == 0) + TranslateWindow(g.Windows[window_n], viewport_delta); + + // Update DPI scale + float new_dpi_scale; + if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available) + new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport); + else if (viewport->PlatformMonitor != -1) + new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; + else + new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f; + if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale) + { + float scale_factor = new_dpi_scale / viewport->DpiScale; + if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) + ScaleWindowsInViewport(viewport, scale_factor); + //if (viewport == GetMainViewport()) + // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor); + + // Scale our window moving pivot so that the window will rescale roughly around the mouse position. + // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border. + // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.) + //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport) + // g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor); + } + viewport->DpiScale = new_dpi_scale; + } + + if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + { + g.MouseViewport = main_viewport; + return; + } + + // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport. + // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set. + ImGuiViewportP* viewport_hovered = NULL; + if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) + { + viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL; + if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) + { + // Back-end failed at honoring its contract if it returned a viewport with the _NoInputs flag. + IM_ASSERT(0); + viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos); + } + } + else + { + // If the back-end doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search: + // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. + // B) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO) + viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos); + } + if (viewport_hovered != NULL) + g.MouseLastHoveredViewport = viewport_hovered; + else if (g.MouseLastHoveredViewport == NULL) + g.MouseLastHoveredViewport = g.Viewports[0]; + + // Update mouse reference viewport + // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode) + if (g.MovingWindow) + g.MouseViewport = g.MovingWindow->Viewport; + else + g.MouseViewport = g.MouseLastHoveredViewport; + + // When dragging something, always refer to the last hovered viewport. + // - when releasing a moving window we will revert to aiming behind (at viewport_hovered) + // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info) + // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release. + const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive; + if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL) + viewport_hovered = g.MouseLastHoveredViewport; + if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown()) + if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) + g.MouseViewport = viewport_hovered; + + IM_ASSERT(g.MouseViewport != NULL); +} + +// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) +static void ImGui::UpdateViewportsEndFrame() +{ + ImGuiContext& g = *GImGui; + g.PlatformIO.MainViewport = g.Viewports[0]; + g.PlatformIO.Viewports.resize(0); + for (int i = 0; i < g.Viewports.Size; i++) + { + ImGuiViewportP* viewport = g.Viewports[i]; + viewport->LastPos = viewport->Pos; + if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f) + if (i > 0) // Always include main viewport in the list + continue; + if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)) + continue; + if (i > 0) + IM_ASSERT(viewport->Window != NULL); + g.PlatformIO.Viewports.push_back(viewport); + } + g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called +} + +// FIXME: We should ideally refactor the system to call this every frame (we currently don't) +ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(id != 0); + + if (window != NULL) + { + if (g.MovingWindow && g.MovingWindow->RootWindow == window) + flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing; + if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) + flags |= ImGuiViewportFlags_NoInputs; + if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing) + flags |= ImGuiViewportFlags_NoFocusOnAppearing; + } + + ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id); + if (viewport) + { + if (!viewport->PlatformRequestMove) + viewport->Pos = pos; + if (!viewport->PlatformRequestResize) + viewport->Size = size; + } + else + { + // New viewport + viewport = IM_NEW(ImGuiViewportP)(); + viewport->ID = id; + viewport->Idx = g.Viewports.Size; + viewport->Pos = viewport->LastPos = pos; + viewport->Size = size; + viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect()); + g.Viewports.push_back(viewport); + //IMGUI_DEBUG_LOG("Add Viewport %08X (%s)\n", id, window->Name); + + // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. + // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame + g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x); + g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y); + + // Store initial DpiScale before the OS platform window creation, based on expected monitor data. + // This is so we can select an appropriate font size on the first frame of our window lifetime + if (viewport->PlatformMonitor != -1) + viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; + } + + viewport->Window = window; + viewport->Flags = flags; + viewport->LastFrameActive = g.FrameCount; + IM_ASSERT(window == NULL || viewport->ID == window->ID); + + if (window != NULL) + window->ViewportOwned = true; + + return viewport; +} + //----------------------------------------------------------------------------- // [SECTION] DOCKING From 54a129a2e2f688e80455c46d8b8c6530b0ef4d28 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 18:38:40 +0100 Subject: [PATCH 141/566] Refactor: Move viewport code under other subsystem to simplify merging (3) (moving in multiple commits to make diff/patch behave nicely) --- imgui.cpp | 480 +++++++++++++++++++++++++++--------------------------- 1 file changed, 240 insertions(+), 240 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 86c93e8f..ca416971 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7791,246 +7791,6 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- -// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. -static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) -{ - ImGuiContext& g = *GImGui; - ImGuiWindowFlags flags = window->Flags; - window->ViewportAllowPlatformMonitorExtend = -1; - - // Restore main viewport if multi-viewport is not supported by the back-end - ImGuiViewportP* main_viewport = g.Viewports[0]; - if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) - { - SetWindowViewport(window, main_viewport); - return; - } - window->ViewportOwned = false; - - // Appearing popups reset their viewport so they can inherit again - if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing) - { - window->Viewport = NULL; - window->ViewportId = 0; - } - - if (!g.NextWindowData.ViewportCond) - { - // By default inherit from parent window - if (window->Viewport == NULL && window->ParentWindow) - window->Viewport = window->ParentWindow->Viewport; - - // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file - if (window->Viewport == NULL && window->ViewportId != 0) - { - window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId); - if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX) - window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None); - } - } - - if (g.NextWindowData.ViewportCond) - { - // Code explicitly request a viewport - window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId); - window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet. - } - else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu)) - { - // Always inherit viewport from parent window - window->Viewport = window->ParentWindow->Viewport; - } - else if (flags & ImGuiWindowFlags_Tooltip) - { - window->Viewport = g.MouseViewport; - } - else if (GetWindowAlwaysWantOwnViewport(window)) - { - window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); - } - else if (g.MovingWindow && g.MovingWindow->RootWindow == window && IsMousePosValid()) - { - if (window->Viewport != NULL && window->Viewport->Window == window) - window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); - } - else - { - // Merge into host viewport? - // We cannot test window->ViewportOwned as it set lower in the function. - bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0); - if (try_to_merge_into_host_viewport) - UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); - } - - // Fallback to default viewport - if (window->Viewport == NULL) - window->Viewport = main_viewport; - - // Mark window as allowed to protrude outside of its viewport and into the current monitor - if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) - { - // We need to take account of the possibility that mouse may become invalid. - // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. - ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; - bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow); - bool mouse_valid = IsMousePosValid(&mouse_ref); - if ((window->Appearing || (flags & ImGuiWindowFlags_Tooltip)) && (!use_mouse_ref || mouse_valid)) - window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); - else - window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; - } - else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow)) - { - // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. - const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; - if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) - { - // Steal/transfer ownership - //IMGUI_DEBUG_LOG("[%05d] Window '%s' steal Viewport %08X from Window '%s'\n", g.FrameCount, window->Name, window->Viewport->ID, window->Viewport->Window->Name); - window->Viewport->Window = window; - window->Viewport->ID = window->ID; - window->Viewport->LastNameHash = 0; - } - else if (!UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0])) // Merge? - { - // New viewport - window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); - } - } - // Regular (non-child, non-popup) windows by default are also allowed to protrude - // Child windows are kept contained within their parent. - else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) - window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; - - // Update flags - window->ViewportOwned = (window == window->Viewport->Window); - window->ViewportId = window->Viewport->ID; - - // If the OS window has a title bar, hide our imgui title bar - //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) - // window->Flags |= ImGuiWindowFlags_NoTitleBar; -} - -// Called by user at the end of the main loop, after EndFrame() -// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. -void ImGui::UpdatePlatformWindows() -{ - ImGuiContext& g = *GImGui; - IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?"); - IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount); - g.FrameCountPlatformEnded = g.FrameCount; - if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) - return; - - // Create/resize/destroy platform windows to match each active viewport. - // Skip the main viewport (index 0), which is always fully handled by the application! - for (int i = 1; i < g.Viewports.Size; i++) - { - ImGuiViewportP* viewport = g.Viewports[i]; - - // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window (the implicit/fallback Debug window will be registered its viewport then be disabled) - bool destroy_platform_window = false; - destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1); - destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)); - if (destroy_platform_window) - { - DestroyPlatformWindow(viewport); - continue; - } - - // New windows that appears directly in a new viewport won't always have a size on their first frame - if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0) - continue; - - // Create window - bool is_new_platform_window = (viewport->PlatformWindowCreated == false); - if (is_new_platform_window) - { - //IMGUI_DEBUG_LOG("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); - g.PlatformIO.Platform_CreateWindow(viewport); - if (g.PlatformIO.Renderer_CreateWindow != NULL) - g.PlatformIO.Renderer_CreateWindow(viewport); - viewport->LastNameHash = 0; - viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?) - viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it. - viewport->PlatformWindowCreated = true; - } - - // Apply Position and Size (from ImGui to Platform/Renderer back-ends) - if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove) - g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos); - if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize) - g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size); - if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize) - g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size); - viewport->LastPlatformPos = viewport->Pos; - viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size; - - // Update title bar (if it changed) - if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window)) - { - const char* title_begin = window_for_title->Name; - char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin); - const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin); - if (viewport->LastNameHash != title_hash) - { - char title_end_backup_c = *title_end; - *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain. - g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin); - *title_end = title_end_backup_c; - viewport->LastNameHash = title_hash; - } - } - - // Update alpha (if it changed) - if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha) - g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha); - viewport->LastAlpha = viewport->Alpha; - - // Optional, general purpose call to allow the back-end to perform general book-keeping even if things haven't changed. - if (g.PlatformIO.Platform_UpdateWindow) - g.PlatformIO.Platform_UpdateWindow(viewport); - - if (is_new_platform_window) - { - // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late) - if (g.FrameCount < 3) - viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing; - - // Show window - g.PlatformIO.Platform_ShowWindow(viewport); - - // Even without focus, we assume the window becomes front-most. - // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available. - if (viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount) - viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount; - } - - // Clear request flags - viewport->ClearRequestFlags(); - } - - // Update our implicit z-order knowledge of platform windows, which is used when the back-end cannot provide io.MouseHoveredViewport. - // When setting Platform_GetWindowFocus, it is expected that the platform back-end can handle calls without crashing if it doesn't have data stored. - if (g.PlatformIO.Platform_GetWindowFocus != NULL) - { - ImGuiViewportP* focused_viewport = NULL; - for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++) - { - ImGuiViewportP* viewport = g.Viewports[n]; - if (n == 0 || viewport->PlatformWindowCreated) - if (g.PlatformIO.Platform_GetWindowFocus(viewport)) - focused_viewport = viewport; - } - if (focused_viewport && g.PlatformLastFocusedViewport != focused_viewport->ID) - { - if (focused_viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount) - focused_viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount; - g.PlatformLastFocusedViewport = focused_viewport->ID; - } - } -} - // This is a default/basic function for performing the rendering/swap of multiple Platform Windows. // Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves. // The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself: @@ -10613,6 +10373,246 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const return viewport; } +// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. +static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImGuiWindowFlags flags = window->Flags; + window->ViewportAllowPlatformMonitorExtend = -1; + + // Restore main viewport if multi-viewport is not supported by the back-end + ImGuiViewportP* main_viewport = g.Viewports[0]; + if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + { + SetWindowViewport(window, main_viewport); + return; + } + window->ViewportOwned = false; + + // Appearing popups reset their viewport so they can inherit again + if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing) + { + window->Viewport = NULL; + window->ViewportId = 0; + } + + if (!g.NextWindowData.ViewportCond) + { + // By default inherit from parent window + if (window->Viewport == NULL && window->ParentWindow) + window->Viewport = window->ParentWindow->Viewport; + + // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file + if (window->Viewport == NULL && window->ViewportId != 0) + { + window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId); + if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX) + window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None); + } + } + + if (g.NextWindowData.ViewportCond) + { + // Code explicitly request a viewport + window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId); + window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet. + } + else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu)) + { + // Always inherit viewport from parent window + window->Viewport = window->ParentWindow->Viewport; + } + else if (flags & ImGuiWindowFlags_Tooltip) + { + window->Viewport = g.MouseViewport; + } + else if (GetWindowAlwaysWantOwnViewport(window)) + { + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + } + else if (g.MovingWindow && g.MovingWindow->RootWindow == window && IsMousePosValid()) + { + if (window->Viewport != NULL && window->Viewport->Window == window) + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + } + else + { + // Merge into host viewport? + // We cannot test window->ViewportOwned as it set lower in the function. + bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0); + if (try_to_merge_into_host_viewport) + UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); + } + + // Fallback to default viewport + if (window->Viewport == NULL) + window->Viewport = main_viewport; + + // Mark window as allowed to protrude outside of its viewport and into the current monitor + if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) + { + // We need to take account of the possibility that mouse may become invalid. + // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. + ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; + bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow); + bool mouse_valid = IsMousePosValid(&mouse_ref); + if ((window->Appearing || (flags & ImGuiWindowFlags_Tooltip)) && (!use_mouse_ref || mouse_valid)) + window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); + else + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; + } + else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow)) + { + // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. + const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; + if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) + { + // Steal/transfer ownership + //IMGUI_DEBUG_LOG("[%05d] Window '%s' steal Viewport %08X from Window '%s'\n", g.FrameCount, window->Name, window->Viewport->ID, window->Viewport->Window->Name); + window->Viewport->Window = window; + window->Viewport->ID = window->ID; + window->Viewport->LastNameHash = 0; + } + else if (!UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0])) // Merge? + { + // New viewport + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); + } + } + // Regular (non-child, non-popup) windows by default are also allowed to protrude + // Child windows are kept contained within their parent. + else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; + + // Update flags + window->ViewportOwned = (window == window->Viewport->Window); + window->ViewportId = window->Viewport->ID; + + // If the OS window has a title bar, hide our imgui title bar + //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) + // window->Flags |= ImGuiWindowFlags_NoTitleBar; +} + +// Called by user at the end of the main loop, after EndFrame() +// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. +void ImGui::UpdatePlatformWindows() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?"); + IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount); + g.FrameCountPlatformEnded = g.FrameCount; + if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + return; + + // Create/resize/destroy platform windows to match each active viewport. + // Skip the main viewport (index 0), which is always fully handled by the application! + for (int i = 1; i < g.Viewports.Size; i++) + { + ImGuiViewportP* viewport = g.Viewports[i]; + + // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window (the implicit/fallback Debug window will be registered its viewport then be disabled) + bool destroy_platform_window = false; + destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1); + destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)); + if (destroy_platform_window) + { + DestroyPlatformWindow(viewport); + continue; + } + + // New windows that appears directly in a new viewport won't always have a size on their first frame + if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0) + continue; + + // Create window + bool is_new_platform_window = (viewport->PlatformWindowCreated == false); + if (is_new_platform_window) + { + //IMGUI_DEBUG_LOG("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + g.PlatformIO.Platform_CreateWindow(viewport); + if (g.PlatformIO.Renderer_CreateWindow != NULL) + g.PlatformIO.Renderer_CreateWindow(viewport); + viewport->LastNameHash = 0; + viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?) + viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it. + viewport->PlatformWindowCreated = true; + } + + // Apply Position and Size (from ImGui to Platform/Renderer back-ends) + if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove) + g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos); + if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize) + g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size); + if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize) + g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size); + viewport->LastPlatformPos = viewport->Pos; + viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size; + + // Update title bar (if it changed) + if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window)) + { + const char* title_begin = window_for_title->Name; + char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin); + const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin); + if (viewport->LastNameHash != title_hash) + { + char title_end_backup_c = *title_end; + *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain. + g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin); + *title_end = title_end_backup_c; + viewport->LastNameHash = title_hash; + } + } + + // Update alpha (if it changed) + if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha) + g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha); + viewport->LastAlpha = viewport->Alpha; + + // Optional, general purpose call to allow the back-end to perform general book-keeping even if things haven't changed. + if (g.PlatformIO.Platform_UpdateWindow) + g.PlatformIO.Platform_UpdateWindow(viewport); + + if (is_new_platform_window) + { + // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late) + if (g.FrameCount < 3) + viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing; + + // Show window + g.PlatformIO.Platform_ShowWindow(viewport); + + // Even without focus, we assume the window becomes front-most. + // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available. + if (viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount) + viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount; + } + + // Clear request flags + viewport->ClearRequestFlags(); + } + + // Update our implicit z-order knowledge of platform windows, which is used when the back-end cannot provide io.MouseHoveredViewport. + // When setting Platform_GetWindowFocus, it is expected that the platform back-end can handle calls without crashing if it doesn't have data stored. + if (g.PlatformIO.Platform_GetWindowFocus != NULL) + { + ImGuiViewportP* focused_viewport = NULL; + for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++) + { + ImGuiViewportP* viewport = g.Viewports[n]; + if (n == 0 || viewport->PlatformWindowCreated) + if (g.PlatformIO.Platform_GetWindowFocus(viewport)) + focused_viewport = viewport; + } + if (focused_viewport && g.PlatformLastFocusedViewport != focused_viewport->ID) + { + if (focused_viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount) + focused_viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount; + g.PlatformLastFocusedViewport = focused_viewport->ID; + } + } +} + //----------------------------------------------------------------------------- // [SECTION] DOCKING From 5ce93bc0cc0ab18078b8c75d3862e33f2bb40d7a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 Mar 2019 18:39:31 +0100 Subject: [PATCH 142/566] Refactor: Move viewport code under other subsystem to simplify merging (4) (moving in multiple commits to make diff/patch behave nicely) --- imgui.cpp | 198 ++++++++++++++++++++++++++---------------------------- 1 file changed, 97 insertions(+), 101 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ca416971..5fba257d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7787,107 +7787,6 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) } -//----------------------------------------------------------------------------- -// [SECTION] VIEWPORTS, PLATFORM WINDOWS -//----------------------------------------------------------------------------- - -// This is a default/basic function for performing the rendering/swap of multiple Platform Windows. -// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves. -// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself: -// -// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); -// for (int i = 1; i < platform_io.Viewports.Size; i++) -// MyRenderFunction(platform_io.Viewports[i], my_args); -// for (int i = 1; i < platform_io.Viewports.Size; i++) -// MySwapBufferFunction(platform_io.Viewports[i], my_args); -// -void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg) -{ - // Skip the main viewport (index 0), which is always fully handled by the application! - ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - for (int i = 1; i < platform_io.Viewports.Size; i++) - { - ImGuiViewport* viewport = platform_io.Viewports[i]; - if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg); - if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg); - } - for (int i = 1; i < platform_io.Viewports.Size; i++) - { - ImGuiViewport* viewport = platform_io.Viewports[i]; - if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg); - if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg); - } -} - -static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos) -{ - ImGuiContext& g = *GImGui; - for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) - { - const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; - if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos)) - return monitor_n; - } - return -1; -} - -// Search for the monitor with the largest intersection area with the given rectangle -// We generally try to avoid searching loops but the monitor count should be very small here -static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) -{ - ImGuiContext& g = *GImGui; - - // Use a minimum threshold of 1.0f so a zero-sized rect will still find its monitor given its position. - // This is necessary for tooltips which always resize down to zero at first. - const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); - int best_monitor_n = -1; - float best_monitor_surface = 0.001f; - - for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++) - { - const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; - const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize); - if (monitor_rect.Contains(rect)) - return monitor_n; - ImRect overlapping_rect = rect; - overlapping_rect.ClipWithFull(monitor_rect); - float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight(); - if (overlapping_surface < best_monitor_surface) - continue; - best_monitor_surface = overlapping_surface; - best_monitor_n = monitor_n; - } - return best_monitor_n; -} - -void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport) -{ - ImGuiContext& g = *GImGui; - if (g.PlatformIO.Renderer_DestroyWindow) - g.PlatformIO.Renderer_DestroyWindow(viewport); - if (g.PlatformIO.Platform_DestroyWindow) - g.PlatformIO.Platform_DestroyWindow(viewport); - IM_ASSERT(viewport->RendererUserData == NULL); - IM_ASSERT(viewport->PlatformUserData == NULL); - viewport->PlatformHandle = NULL; - viewport->RendererUserData = viewport->PlatformHandle = NULL; - viewport->PlatformWindowCreated = false; - viewport->ClearRequestFlags(); -} - -void ImGui::DestroyPlatformWindows() -{ - // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the back-end - // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. - // It is convenient for the platform back-end code to store something in the main viewport, in order for e.g. the mouse handling - // code to operator a consistent manner. - // It is expected that the back-end can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without - // crashing if it doesn't have data stored. - ImGuiContext& g = *GImGui; - for (int i = 0; i < g.Viewports.Size; i++) - DestroyPlatformWindow(g.Viewports[i]); -} - //----------------------------------------------------------------------------- // [SECTION] KEYBOARD/GAMEPAD NAVIGATION //----------------------------------------------------------------------------- @@ -10613,6 +10512,103 @@ void ImGui::UpdatePlatformWindows() } } +// This is a default/basic function for performing the rendering/swap of multiple Platform Windows. +// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves. +// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself: +// +// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); +// for (int i = 1; i < platform_io.Viewports.Size; i++) +// MyRenderFunction(platform_io.Viewports[i], my_args); +// for (int i = 1; i < platform_io.Viewports.Size; i++) +// MySwapBufferFunction(platform_io.Viewports[i], my_args); +// +void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg) +{ + // Skip the main viewport (index 0), which is always fully handled by the application! + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + for (int i = 1; i < platform_io.Viewports.Size; i++) + { + ImGuiViewport* viewport = platform_io.Viewports[i]; + if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg); + if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg); + } + for (int i = 1; i < platform_io.Viewports.Size; i++) + { + ImGuiViewport* viewport = platform_io.Viewports[i]; + if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg); + if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg); + } +} + +static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos) +{ + ImGuiContext& g = *GImGui; + for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) + { + const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; + if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos)) + return monitor_n; + } + return -1; +} + +// Search for the monitor with the largest intersection area with the given rectangle +// We generally try to avoid searching loops but the monitor count should be very small here +static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) +{ + ImGuiContext& g = *GImGui; + + // Use a minimum threshold of 1.0f so a zero-sized rect will still find its monitor given its position. + // This is necessary for tooltips which always resize down to zero at first. + const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); + int best_monitor_n = -1; + float best_monitor_surface = 0.001f; + + for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++) + { + const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; + const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize); + if (monitor_rect.Contains(rect)) + return monitor_n; + ImRect overlapping_rect = rect; + overlapping_rect.ClipWithFull(monitor_rect); + float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight(); + if (overlapping_surface < best_monitor_surface) + continue; + best_monitor_surface = overlapping_surface; + best_monitor_n = monitor_n; + } + return best_monitor_n; +} + +void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport) +{ + ImGuiContext& g = *GImGui; + if (g.PlatformIO.Renderer_DestroyWindow) + g.PlatformIO.Renderer_DestroyWindow(viewport); + if (g.PlatformIO.Platform_DestroyWindow) + g.PlatformIO.Platform_DestroyWindow(viewport); + IM_ASSERT(viewport->RendererUserData == NULL); + IM_ASSERT(viewport->PlatformUserData == NULL); + viewport->PlatformHandle = NULL; + viewport->RendererUserData = viewport->PlatformHandle = NULL; + viewport->PlatformWindowCreated = false; + viewport->ClearRequestFlags(); +} + +void ImGui::DestroyPlatformWindows() +{ + // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the back-end + // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. + // It is convenient for the platform back-end code to store something in the main viewport, in order for e.g. the mouse handling + // code to operator a consistent manner. + // It is expected that the back-end can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without + // crashing if it doesn't have data stored. + ImGuiContext& g = *GImGui; + for (int i = 0; i < g.Viewports.Size; i++) + DestroyPlatformWindow(g.Viewports[i]); +} + //----------------------------------------------------------------------------- // [SECTION] DOCKING From 3b11505481c66a254b62d466deb9b4634efd7bd5 Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Fri, 8 Mar 2019 23:52:32 +0700 Subject: [PATCH 143/566] Fix typos. (#2411) --- imgui.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.h b/imgui.h index 9ee597bf..86cbf473 100644 --- a/imgui.h +++ b/imgui.h @@ -533,7 +533,7 @@ namespace ImGui // Tooltips IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items). IMGUI_API void EndTooltip(); - IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip(). + IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip(). IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); // Popups, Modals @@ -700,7 +700,7 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window - ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically) ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame @@ -710,7 +710,7 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state - ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) @@ -832,7 +832,7 @@ enum ImGuiTabItemFlags_ { ImGuiTabItemFlags_None = 0, ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. Also: tab is selected on closure and closure is deferred by one frame to allow code to undo it without flicker. - ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programatically make the tab selected when calling BeginTabItem() + ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() }; @@ -1325,7 +1325,7 @@ struct ImGuiIO bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations. bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63) bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) - bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be the a per-window ImGuiWindowFlags_ResizeFromAnySide flag) + bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) bool ConfigWindowsMoveFromTitleBarOnly; // = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected. //------------------------------------------------------------------ @@ -1547,7 +1547,7 @@ typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; // Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. struct ImNewDummy {}; inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } -inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symetrical new() +inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symmetrical new() #define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) #define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } @@ -1713,7 +1713,7 @@ struct ImGuiListClipper #define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black #define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000 -// Helper: ImColor() implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) +// Helper: ImColor() implicitly converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) // Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API. // **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE. // **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed. From 66936880ba87fa0d5e8e17b3954763038362b361 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 Mar 2019 17:33:44 +0100 Subject: [PATCH 144/566] Moved placeholder sections to match Docking branch. Comments. --- imgui.cpp | 25 +++++++++++++++---------- imgui.h | 5 +++-- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 35ba2d7e..3984a2b2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7158,11 +7158,6 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) return window->Pos; } -//----------------------------------------------------------------------------- -// [SECTION] VIEWPORTS, PLATFORM WINDOWS -//----------------------------------------------------------------------------- - -// (this section is filled in the 'viewport' and 'docking' branches) //----------------------------------------------------------------------------- // [SECTION] KEYBOARD/GAMEPAD NAVIGATION @@ -8829,11 +8824,6 @@ void ImGui::EndDragDropTarget() g.DragDropWithinSourceOrTarget = false; } -//----------------------------------------------------------------------------- -// [SECTION] DOCKING -//----------------------------------------------------------------------------- - -// (this section is filled in the 'docking' branch) //----------------------------------------------------------------------------- // [SECTION] LOGGING/CAPTURING @@ -9254,6 +9244,21 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSetting } } + +//----------------------------------------------------------------------------- +// [SECTION] VIEWPORTS, PLATFORM WINDOWS +//----------------------------------------------------------------------------- + +// (this section is filled in the 'docking' branch) + + +//----------------------------------------------------------------------------- +// [SECTION] DOCKING +//----------------------------------------------------------------------------- + +// (this section is filled in the 'docking' branch) + + //----------------------------------------------------------------------------- // [SECTION] PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 86cbf473..c8f265e4 100644 --- a/imgui.h +++ b/imgui.h @@ -464,7 +464,8 @@ namespace ImGui IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.) - // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can the pass the address of a first float element out of a contiguous structure, e.g. &myvector.x + // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. + // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); @@ -475,7 +476,7 @@ namespace ImGui // Widgets: Trees // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. IMGUI_API bool TreeNode(const char* label); - IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to completely decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); From 8e0e91827f3bf6e809716635128f7a3791dbec83 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 Mar 2019 17:46:04 +0100 Subject: [PATCH 145/566] ColorEdit: Fixed tooltip not honoring the ImGuiColorEditFlags_NoAlpha contract of never reading the 4th float in the array (value was read and discarded). (#2384) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7894556e..0c6d63b1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Other Changes: when manipulating the scrollbar of a multi-line input text. - ColorPicker: Fixed a bug/assertion when displaying a color picker in a collapsed window while dragging its title bar. (#2389) +- ColorEdit: Fixed tooltip not honoring the ImGuiColorEditFlags_NoAlpha contract of never + reading the 4th float in the array (value was read and discarded). (#2384) [@haldean] - MenuItem, Selectable: Fixed disabled widget interfering with navigation (fix c2db7f63 in 1.67). - TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f276b3f7..beb8b534 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4648,9 +4648,7 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags { ImGuiContext& g = *GImGui; - int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); BeginTooltipEx(0, true); - const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; if (text_end > text) { @@ -4659,7 +4657,9 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags } ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); - ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); + ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); + ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); SameLine(); if (flags & ImGuiColorEditFlags_NoAlpha) Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); From 79bb4ce128451a32c24c81178f50063bfb641bed Mon Sep 17 00:00:00 2001 From: Haldean Brown Date: Thu, 7 Mar 2019 15:31:29 +0100 Subject: [PATCH 146/566] Added ImGuiColorEditFlagsFlags_InputHSV. (#2383, #2384) --- docs/CHANGELOG.txt | 3 ++ imgui.h | 15 ++++-- imgui_demo.cpp | 10 ++++ imgui_widgets.cpp | 122 +++++++++++++++++++++++++++++++++++---------- 4 files changed, 118 insertions(+), 32 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0c6d63b1..ff2f387b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,9 @@ Other Changes: - InputText: Fixed various display corruption related to swapping the underlying buffer while a input widget is active (both for writable and read-only paths). Often they would manifest when manipulating the scrollbar of a multi-line input text. +- ColorEdit, ColorPicker, ColorButton: Added ImGuiColorEditFlags_InputHSV to manipulate color + values encoded as HSV (in order to avoid HSV<>RGB round trips and associated singularities). + (#2383, #2384) [@haldean] - ColorPicker: Fixed a bug/assertion when displaying a color picker in a collapsed window while dragging its title bar. (#2389) - ColorEdit: Fixed tooltip not honoring the ImGuiColorEditFlags_NoAlpha contract of never diff --git a/imgui.h b/imgui.h index c8f265e4..9a97374e 100644 --- a/imgui.h +++ b/imgui.h @@ -1117,8 +1117,7 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. - // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). - // The intent is that you probably don't want to override them in most of your calls, let the user choose via the option menu and/or call SetColorEditOptions() during startup. + // User Options (right-click on widget to change some of them). ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. @@ -1128,14 +1127,20 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_DisplayHex = 1 << 22, // [Display] // " ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. - ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value. - ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value. + ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value. + ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value. + ImGuiColorEditFlags_InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format. + ImGuiColorEditFlags_InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format. + + // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to + // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. + ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_PickerHueBar, // [Internal] Masks ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_DisplayHSV|ImGuiColorEditFlags_DisplayHex, ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, - ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() + ImGuiColorEditFlags__InputMask = ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_InputHSV // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 13757b29..767fcb06 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1171,6 +1171,16 @@ static void ShowDemoWindowWidgets() if (ImGui::Button("Default: Float + HDR + Hue Wheel")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); + // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) + static ImVec4 color_stored_as_hsv(0.23f, 1.0f, 1.0f, 1.0f); + ImGui::Spacing(); + ImGui::Text("HSV encoded colors"); + ImGui::SameLine(); HelpMarker("By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); + ImGui::Text("Color widget with InputHSV:"); + ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::DragFloat4("Raw HSV values", (float*)&color_stored_as_hsv, 0.01f, 0.0f, 1.0f); + ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index beb8b534..de0bf6b9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4000,7 +4000,11 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask); if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask); - flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask)); + if (!(flags & ImGuiColorEditFlags__InputMask)) + flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputMask); + flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask)); + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check that only 1 is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; @@ -4008,7 +4012,9 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // Convert to the formats we need float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; - if (flags & ImGuiColorEditFlags_DisplayHSV) + if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB)) + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV)) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; @@ -4113,8 +4119,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag TextEx(label, label_display_end); Spacing(); } - ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; - ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; + ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); PopItemWidth(); @@ -4134,8 +4140,10 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (!value_changed_as_float) for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; - if (flags & ImGuiColorEditFlags_DisplayHSV) + if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB)) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV)) + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); col[0] = f[0]; col[1] = f[1]; @@ -4151,16 +4159,21 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test. if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget()) { + bool accepted_drag_drop = false; if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) { memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512 - value_changed = true; + value_changed = accepted_drag_drop = true; } if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) { memcpy((float*)col, payload->Data, sizeof(float) * components); - value_changed = true; + value_changed = accepted_drag_drop = true; } + + // Drag-drop payloads are always RGB + if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV)) + ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]); EndDragDropTarget(); } @@ -4239,6 +4252,7 @@ static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 } // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. +// (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.) // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) { @@ -4264,7 +4278,10 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // Read stored options if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask; + if (!(flags & ImGuiColorEditFlags__InputMask)) + flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__InputMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__InputMask; IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check that only 1 is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected if (!(flags & ImGuiColorEditFlags_NoOptions)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar); @@ -4293,8 +4310,12 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point. ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point. - float H,S,V; - ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V); + float H = col[0], S = col[1], V = col[2]; + float R = col[0], G = col[1], B = col[2]; + if (flags & ImGuiColorEditFlags_InputRGB) + ColorConvertRGBtoHSV(R, G, B, H, S, V); + else if (flags & ImGuiColorEditFlags_InputHSV) + ColorConvertHSVtoRGB(H, S, V, R, G, B); bool value_changed = false, value_changed_h = false, value_changed_sv = false; @@ -4394,7 +4415,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl if ((flags & ImGuiColorEditFlags_NoLabel)) Text("Current"); - ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip; + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip; ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)); if (ref_col != NULL) { @@ -4412,14 +4433,25 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // Convert back color to RGB if (value_changed_h || value_changed_sv) - ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]); + { + if (flags & ImGuiColorEditFlags_InputRGB) + { + ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + col[0] = H; + col[1] = S; + col[2] = V; + } + } // R,G,B and H,S,V slider color editor bool value_changed_fix_hue_wrap = false; if ((flags & ImGuiColorEditFlags_NoInputs) == 0) { PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); - ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags__DisplayMask) == 0) if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB)) @@ -4437,7 +4469,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl } // Try to cancel hue wrap (after ColorEdit4 call), if any - if (value_changed_fix_hue_wrap) + if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB)) { float new_H, new_S, new_V; ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V); @@ -4450,9 +4482,27 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl } } + if (value_changed) + { + if (flags & ImGuiColorEditFlags_InputRGB) + { + R = col[0]; + G = col[1]; + B = col[2]; + ColorConvertRGBtoHSV(R, G, B, H, S, V); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + H = col[0]; + S = col[1]; + V = col[2]; + ColorConvertHSVtoRGB(H, S, V, R, G, B); + } + } + ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f); - ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f)); + ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, 1.0f)); const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) }; ImVec2 sv_cursor_pos; @@ -4552,6 +4602,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // A little colored square. Return true when clicked. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. +// Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set. bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size) { ImGuiWindow* window = GetCurrentWindow(); @@ -4576,22 +4627,26 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (flags & ImGuiColorEditFlags_NoAlpha) flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf); - ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f); + ImVec4 col_rgb = col; + if (flags & ImGuiColorEditFlags_InputHSV) + ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z); + + ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f); float grid_step = ImMin(size.x, size.y) / 2.99f; float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); ImRect bb_inner = bb; float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. bb_inner.Expand(off); - if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f) + if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) { float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f); - RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight); - window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft); + RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight); + window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft); } else { // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha - ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha; + ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha; if (col_source.w < 1.0f) RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); else @@ -4608,9 +4663,9 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource()) { if (flags & ImGuiColorEditFlags_NoAlpha) - SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col, sizeof(float) * 3, ImGuiCond_Once); + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once); else - SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once); + SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once); ColorButton(desc_id, col, flags); SameLine(); TextEx("Color"); @@ -4619,7 +4674,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl // Tooltip if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered) - ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); + ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); if (pressed) MarkItemEdited(id); @@ -4637,9 +4692,12 @@ void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask; if ((flags & ImGuiColorEditFlags__PickerMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask; + if ((flags & ImGuiColorEditFlags__InputMask) == 0) + flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputMask; IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DataTypeMask)); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check only 1 option is selected + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check only 1 option is selected g.ColorEditOptions = flags; } @@ -4659,12 +4717,22 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); - ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); + ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); SameLine(); - if (flags & ImGuiColorEditFlags_NoAlpha) - Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); - else - Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]); + if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags__InputMask)) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); + else + Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]); + } + else if (flags & ImGuiColorEditFlags_InputHSV) + { + if (flags & ImGuiColorEditFlags_NoAlpha) + Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]); + else + Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]); + } EndTooltip(); } From 17c567c3a9f43cbb7b82af4295b91cde3366cd38 Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Sat, 9 Mar 2019 00:05:20 +0700 Subject: [PATCH 147/566] Don't use const qualified parameters in declarations. This fixes warnings from clang-tidy like this: parameter 'v_max' is const-qualified in the function declaration; const-qualification of parameters only has an effect in function definitions Since values (rather than references or pointers) don't need to be const, they don't need to be marked that way in the function declaration. --- imgui.cpp | 2 +- imgui.h | 4 ++-- imgui_internal.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3984a2b2..f2516c1d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1025,7 +1025,7 @@ static void NavUpdateWindowingList(); static void NavUpdateMoveResult(); static float NavUpdatePageUpPageDown(int allowed_dir_flags); static inline void NavUpdateAnyRequestFlag(); -static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id); +static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id); static ImVec2 NavCalcPreferredRefPos(); static void NavSaveLastChildNavWindow(ImGuiWindow* nav_window); static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); diff --git a/imgui.h b/imgui.h index 9a97374e..2fbf4fc3 100644 --- a/imgui.h +++ b/imgui.h @@ -1867,8 +1867,8 @@ struct ImDrawList IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All); - IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness); - IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order. + IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, bool closed, float thickness); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order. IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); // Stateful path API, add points then finish with PathFillConvex() or PathStroke() diff --git a/imgui_internal.h b/imgui_internal.h index 576e3366..e76d10aa 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1539,8 +1539,8 @@ namespace ImGui // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " - template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, const T v_min, const T v_max, const char* format, float power, ImGuiDragFlags flags); - template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, const T v_min, const T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags); + template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); From b5d57a6615d7d547f1afd8b729a686fea46621b0 Mon Sep 17 00:00:00 2001 From: Bruce Mitchener Date: Sat, 9 Mar 2019 16:10:17 +0700 Subject: [PATCH 148/566] Fix typos. (#2413) --- docs/TODO.txt | 4 ++-- examples/imgui_impl_metal.mm | 2 +- examples/imgui_impl_win32.cpp | 2 +- imgui.cpp | 4 ++-- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 85696c1e..0ede3897 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -149,7 +149,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - knob: rotating knob widget (#942) - drag float: power/logarithmic slider and drags are weird. (#1316) - drag float: up/down axis - - drag float: power != 0.0f with current value being outside the the range keeps the value stuck. + - drag float: power != 0.0f with current value being outside the range keeps the value stuck. - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) - combo: use clipper: make it easier to disable clipper with a single flag. @@ -315,7 +315,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - remote: make a system like RemoteImGui first-class citizen/project (#75) - - demo: find a way to demonstrate textures in the examples application, as it such a a common issue for new users. + - demo: find a way to demonstrate textures in the examples application, as it such a common issue for new users. - demo: add vertical separator demo - demo: add virtual scrolling example? - demo: demonstrate Plot offset diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index a1ed7d74..95de91c6 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -283,7 +283,7 @@ void ImGui_ImplMetal_DestroyDeviceObjects() - (_Nullable id)renderPipelineStateForFrameAndDevice:(id)device { // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame - // Thie hit rate for this cache should be very near 100%. + // The hit rate for this cache should be very near 100%. id renderPipelineState = self.renderPipelineStateCache[self.framebufferDescriptor]; if (renderPipelineState == nil) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 4690f3e7..524923c3 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -247,7 +247,7 @@ void ImGui_ImplWin32_NewFrame() // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. -// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds. +// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag. IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { diff --git a/imgui.cpp b/imgui.cpp index f2516c1d..47dc7526 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -771,7 +771,7 @@ CODE Q: How can I use my own math types instead of ImVec2/ImVec4? A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions. - This way you'll be able to use your own types everywhere, e.g. passsing glm::vec2 to ImGui functions instead of ImVec2. + This way you'll be able to use your own types everywhere, e.g. passing glm::vec2 to ImGui functions instead of ImVec2. Q: How can I load a different font than the default? A: Use the font atlas to load the TTF/OTF file you want: @@ -958,7 +958,7 @@ CODE #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #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 "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. -#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#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 "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 25ce75fe..52175e29 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -55,7 +55,7 @@ Index of this file: #ifdef __clang__ #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #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 it. +#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 // #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 diff --git a/imgui_internal.h b/imgui_internal.h index e76d10aa..1ff750c5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -643,7 +643,7 @@ struct ImGuiPopupRef ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() ImGuiWindow* ParentWindow; // Set on OpenPopup() int OpenFrameCount; // Set on OpenPopup() - ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differenciate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) + ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup }; From ecf7666624cbfa2dad4dba82cd9e8b98c3a1020e Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 10 Mar 2019 22:19:18 +0100 Subject: [PATCH 149/566] Docking: Fixed an issue where removing the last window from a dockspace node that is not a central node without remove the node. (#2414, #2109) --- imgui.cpp | 4 ++-- imgui_internal.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 830ff4ff..90386dcc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11432,7 +11432,7 @@ static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window } } - if (node->Windows.Size == 0 && !node->IsCentralNode && window->DockId != node->ID) + if (node->Windows.Size == 0 && !node->IsCentralNode && !node->IsDockSpace() && window->DockId != node->ID) { // Automatic dock node delete themselves if they are not holding at least one tab DockContextRemoveNode(&g, node, true); @@ -11631,7 +11631,7 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node) { // Update visibility flag - bool is_visible = (node->ParentNode == 0) ? node->IsDockSpace() : node->IsCentralNode; + bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode; is_visible |= (node->Windows.Size > 0); is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible); is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible); diff --git a/imgui_internal.h b/imgui_internal.h index 40c8cc1a..6fdc30bc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1670,7 +1670,7 @@ namespace ImGui IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id); IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id); // Warning: DO NOT HOLD ON ImGuiDockNode* pointer, will be invalided by any split/merge/remove operation. inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; } - IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags = 0); + IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags = 0); // Use (flags == ImGuiDockNodeFlags_Dockspace) to create a dockspace, otherwise it'll create a floating node. IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_persistent_docking_references = true); IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the root. From 3eedb542a640f5cb71983b388dd81f8cc395b788 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Mar 2019 11:07:23 +0100 Subject: [PATCH 150/566] Viewports: Renamed ConfigViewportsNoParent to ConfigViewportsNoDefaultParent. Fix outdated comments in examples. --- examples/example_glfw_opengl2/main.cpp | 4 ++-- examples/example_glfw_opengl3/main.cpp | 4 ++-- examples/example_glfw_vulkan/main.cpp | 4 ++-- examples/example_sdl_opengl2/main.cpp | 4 ++-- examples/example_sdl_opengl3/main.cpp | 4 ++-- examples/example_win32_directx10/main.cpp | 5 +++-- examples/example_win32_directx11/main.cpp | 12 +++++++----- examples/example_win32_directx12/main.cpp | 5 +++-- examples/example_win32_directx9/main.cpp | 5 +++-- imgui.cpp | 4 ++-- imgui.h | 2 +- imgui_demo.cpp | 4 ++-- 12 files changed, 31 insertions(+), 26 deletions(-) diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index ff4ffdbf..619e6bf7 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -47,8 +47,8 @@ int main(int, char**) //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index bb2b1525..3785d779 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -90,8 +90,8 @@ int main(int, char**) //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index b2e902e3..74edf5d9 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -358,8 +358,8 @@ int main(int, char**) //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index bb3eaca8..1d3c2603 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -43,8 +43,8 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 44fa4025..332685c4 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -83,8 +83,8 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 8ef6c7c8..bb92c0d0 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -117,10 +117,11 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 5d3efef7..d981c039 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -133,16 +133,18 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; - io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleFonts; // FIXME-DPI: THIS CURRENTLY DOESN'T WORK AS EXPECTED. DON'T USE IN USER APP! - io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleViewports; // FIXME-DPI //io.ConfigViewportsNoAutoMerge = true; - //io.ConfigViewportsNoTaskBarIcon = false; + //io.ConfigViewportsNoTaskBarIcon = true; + //io.ConfigViewportsNoDefaultParent = true; //io.ConfigDockingTabBarOnSingleWindows = true; //io.ConfigDockingTransparentPayload = true; +#if 1 + io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleFonts; // FIXME-DPI: THIS CURRENTLY DOESN'T WORK AS EXPECTED. DON'T USE IN USER APP! + io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleViewports; // FIXME-DPI +#endif // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 54bc7524..14af4c21 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -291,10 +291,11 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking //io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows (FIXME: Currently broken in DX12 back-end, need some work!) - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 9833ca93..37187454 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -115,10 +115,11 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoTaskBarIcons; - //io.ConfigFlags |= ImGuiConfigFlags_ViewportsNoMerge; + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/imgui.cpp b/imgui.cpp index 90386dcc..bf571aa8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1207,7 +1207,7 @@ ImGuiIO::ImGuiIO() ConfigViewportsNoAutoMerge = false; ConfigViewportsNoTaskBarIcon = false; ConfigViewportsNoDecoration = true; - ConfigViewportsNoParent = false; + ConfigViewportsNoDefaultParent = false; // Miscellaneous options MouseDrawCursor = false; @@ -5605,7 +5605,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (window->WindowClass.ParentViewportId) window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId; else - window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; + window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; if (window->WindowClass.ViewportFlagsOverrideMask) viewport_flags = (viewport_flags & ~window->WindowClass.ViewportFlagsOverrideMask) | (window->WindowClass.ViewportFlagsOverrideValue & window->WindowClass.ViewportFlagsOverrideMask); diff --git a/imgui.h b/imgui.h index b385bb02..ee74ded6 100644 --- a/imgui.h +++ b/imgui.h @@ -1400,7 +1400,7 @@ struct ImGuiIO bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. bool ConfigViewportsNoDecoration; // = true // [BETA] Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). - bool ConfigViewportsNoParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform back-end to setup a parent/child relationship between the OS windows (some back-end may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. + bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform back-end to setup a parent/child relationship between the OS windows (some back-end may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. // Miscellaneous options bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2e55052a..709e86ee 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -373,7 +373,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform back-ends won't refresh the task bar icon state right away)."); ImGui::Checkbox("io.ConfigViewportsNoDecoration", &io.ConfigViewportsNoDecoration); ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform back-ends won't refresh the decoration right away)."); - ImGui::Checkbox("io.ConfigViewportsNoParent", &io.ConfigViewportsNoParent); + ImGui::Checkbox("io.ConfigViewportsNoDefaultParent", &io.ConfigViewportsNoDefaultParent); ImGui::SameLine(); HelpMarker("Toggling this at runtime is normally unsupported (most platform back-ends won't refresh the parenting right away)."); ImGui::Unindent(); } @@ -2802,7 +2802,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.ConfigViewportsNoAutoMerge) ImGui::Text("io.ConfigViewportsNoAutoMerge"); if (io.ConfigViewportsNoTaskBarIcon) ImGui::Text("io.ConfigViewportsNoTaskBarIcon"); if (io.ConfigViewportsNoDecoration) ImGui::Text("io.ConfigViewportsNoDecoration"); - if (io.ConfigViewportsNoParent) ImGui::Text("io.ConfigViewportsNoParent"); + if (io.ConfigViewportsNoDefaultParent) ImGui::Text("io.ConfigViewportsNoDefaultParent"); if (io.ConfigDockingNoSplit) ImGui::Text("io.ConfigDockingNoSplit"); if (io.ConfigDockingWithShift) ImGui::Text("io.ConfigDockingWithShift"); if (io.ConfigDockingTabBarOnSingleWindows) ImGui::Text("io.ConfigDockingTabBarOnSingleWindows"); From cf4fcc473550c8c024a84f480aebe5d4e6aafedc Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Mar 2019 13:10:41 +0100 Subject: [PATCH 151/566] Viewports: Fixed delayed window pos->viewport pos sync leading to monitor not being updated at the time of clamping window position in Begin. (#2415, #1542) --- imgui.cpp | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bf571aa8..d457f726 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1061,6 +1061,7 @@ static void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window); static int FindPlatformMonitorForPos(const ImVec2& pos); static int FindPlatformMonitorForRect(const ImRect& r); +static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport); } @@ -5581,13 +5582,31 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetCurrentWindow(window); } + bool viewport_rect_changed = false; if (window->ViewportOwned) { + // Synchronize window --> viewport in most situations // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM if (window->Viewport->PlatformRequestMove) window->Pos = window->Viewport->Pos; + else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0) + { + viewport_rect_changed = true; + window->Viewport->Pos = window->Pos; + } + if (window->Viewport->PlatformRequestResize) window->Size = window->SizeFull = window->Viewport->Size; + else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0) + { + viewport_rect_changed = true; + window->Viewport->Size = window->Size; + } + + // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame() + // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect. + if (viewport_rect_changed) + UpdateViewportPlatformMonitor(window->Viewport); // Update common viewport flags ImGuiViewportFlags viewport_flags = (window->Viewport->Flags) & ~(ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration); @@ -5669,7 +5688,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); window->ResizeBorderHeld = (signed char)border_held; - // Synchronize window --> viewport + // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either) if (window->ViewportOwned) { if (!window->Viewport->PlatformRequestMove) @@ -10115,8 +10134,7 @@ static void ImGui::UpdateViewportsNewFrame() viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); } - // Update monitor (we'll use this info to clamp windows and save windows lost in a removed monitor) - viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect()); + UpdateViewportPlatformMonitor(viewport); } // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. @@ -10261,7 +10279,7 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const viewport->Idx = g.Viewports.Size; viewport->Pos = viewport->LastPos = pos; viewport->Size = size; - viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect()); + UpdateViewportPlatformMonitor(viewport); g.Viewports.push_back(viewport); //IMGUI_DEBUG_LOG("Add Viewport %08X (%s)\n", id, window->Name); @@ -10569,11 +10587,12 @@ static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos) // Search for the monitor with the largest intersection area with the given rectangle // We generally try to avoid searching loops but the monitor count should be very small here +// FIXME-OPT: We could test the last monitor used for that viewport first.. static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) { ImGuiContext& g = *GImGui; - // Use a minimum threshold of 1.0f so a zero-sized rect will still find its monitor given its position. + // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position. // This is necessary for tooltips which always resize down to zero at first. const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); int best_monitor_n = -1; @@ -10596,6 +10615,12 @@ static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) return best_monitor_n; } +// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) +static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport) +{ + viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect()); +} + void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport) { ImGuiContext& g = *GImGui; From 6767b0a1b0c1175b701b0371c3def26abd69ee5b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Mar 2019 16:00:18 +0100 Subject: [PATCH 152/566] Examples: Win32+DirectX: moved helper functions below main. --- examples/example_win32_directx10/main.cpp | 185 ++++---- examples/example_win32_directx11/main.cpp | 190 +++++---- examples/example_win32_directx12/main.cpp | 490 +++++++++++----------- examples/example_win32_directx9/main.cpp | 154 +++---- 4 files changed, 532 insertions(+), 487 deletions(-) diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 7e3dd922..c3fc03af 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -15,100 +15,32 @@ static ID3D10Device* g_pd3dDevice = NULL; static IDXGISwapChain* g_pSwapChain = NULL; static ID3D10RenderTargetView* g_mainRenderTargetView = NULL; -void CreateRenderTarget() -{ - ID3D10Texture2D* pBackBuffer; - g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); - g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); - pBackBuffer->Release(); -} - -void CleanupRenderTarget() -{ - if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } -} - -HRESULT CreateDeviceD3D(HWND hWnd) -{ - // Setup swap chain - DXGI_SWAP_CHAIN_DESC sd; - ZeroMemory(&sd, sizeof(sd)); - sd.BufferCount = 2; - sd.BufferDesc.Width = 0; - sd.BufferDesc.Height = 0; - sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - sd.BufferDesc.RefreshRate.Numerator = 60; - sd.BufferDesc.RefreshRate.Denominator = 1; - sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; - sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - sd.OutputWindow = hWnd; - sd.SampleDesc.Count = 1; - sd.SampleDesc.Quality = 0; - sd.Windowed = TRUE; - sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; - - UINT createDeviceFlags = 0; - //createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; - if (D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice) != S_OK) - return E_FAIL; - - CreateRenderTarget(); - - return S_OK; -} - -void CleanupDeviceD3D() -{ - CleanupRenderTarget(); - if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } -} - -extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) - return true; - - switch (msg) - { - case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) - { - CleanupRenderTarget(); - g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); - CreateRenderTarget(); - } - return 0; - case WM_SYSCOMMAND: - if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu - return 0; - break; - case WM_DESTROY: - PostQuitMessage(0); - return 0; - } - return DefWindowProc(hWnd, msg, wParam, lParam); -} - +// Forward declarations of helper functions +bool CreateDeviceD3D(HWND hWnd); +void CleanupDeviceD3D(); +void CreateRenderTarget(); +void CleanupRenderTarget(); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Main code int main(int, char**) { // Create application window WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - RegisterClassEx(&wc); - HWND hwnd = CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX10 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + ::RegisterClassEx(&wc); + HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX10 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D - if (CreateDeviceD3D(hwnd) < 0) + if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); return 1; } // Show the window - ShowWindow(hwnd, SW_SHOWDEFAULT); - UpdateWindow(hwnd); + ::ShowWindow(hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(hwnd); // Setup Dear ImGui context IMGUI_CHECKVERSION(); @@ -139,6 +71,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); @@ -153,10 +86,10 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. - if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); continue; } @@ -217,8 +150,86 @@ int main(int, char**) ImGui::DestroyContext(); CleanupDeviceD3D(); - DestroyWindow(hwnd); - UnregisterClass(wc.lpszClassName, wc.hInstance); + ::DestroyWindow(hwnd); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); return 0; } + +// Helper functions + +bool CreateDeviceD3D(HWND hWnd) +{ + // Setup swap chain + DXGI_SWAP_CHAIN_DESC sd; + ZeroMemory(&sd, sizeof(sd)); + sd.BufferCount = 2; + sd.BufferDesc.Width = 0; + sd.BufferDesc.Height = 0; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.RefreshRate.Numerator = 60; + sd.BufferDesc.RefreshRate.Denominator = 1; + sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.OutputWindow = hWnd; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.Windowed = TRUE; + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + UINT createDeviceFlags = 0; + //createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; + if (D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice) != S_OK) + return false; + + CreateRenderTarget(); + return true; +} + +void CleanupDeviceD3D() +{ + CleanupRenderTarget(); + if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } +} + +void CreateRenderTarget() +{ + ID3D10Texture2D* pBackBuffer; + g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); + pBackBuffer->Release(); +} + +void CleanupRenderTarget() +{ + if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } +} + +// Win32 message handler +extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) + { + CleanupRenderTarget(); + g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); + CreateRenderTarget(); + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProc(hWnd, msg, wParam, lParam); +} diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index a08c8cb4..3eff1d96 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -15,103 +15,32 @@ static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; static IDXGISwapChain* g_pSwapChain = NULL; static ID3D11RenderTargetView* g_mainRenderTargetView = NULL; -void CreateRenderTarget() -{ - ID3D11Texture2D* pBackBuffer; - g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); - g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); - pBackBuffer->Release(); -} - -void CleanupRenderTarget() -{ - if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } -} - -HRESULT CreateDeviceD3D(HWND hWnd) -{ - // Setup swap chain - DXGI_SWAP_CHAIN_DESC sd; - ZeroMemory(&sd, sizeof(sd)); - sd.BufferCount = 2; - sd.BufferDesc.Width = 0; - sd.BufferDesc.Height = 0; - sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - sd.BufferDesc.RefreshRate.Numerator = 60; - sd.BufferDesc.RefreshRate.Denominator = 1; - sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; - sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - sd.OutputWindow = hWnd; - sd.SampleDesc.Count = 1; - sd.SampleDesc.Quality = 0; - sd.Windowed = TRUE; - sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; - - UINT createDeviceFlags = 0; - //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; - D3D_FEATURE_LEVEL featureLevel; - const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; - if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) - return E_FAIL; - - CreateRenderTarget(); - - return S_OK; -} - -void CleanupDeviceD3D() -{ - CleanupRenderTarget(); - if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } - if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } -} - -extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) - return true; - - switch (msg) - { - case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) - { - CleanupRenderTarget(); - g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); - CreateRenderTarget(); - } - return 0; - case WM_SYSCOMMAND: - if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu - return 0; - break; - case WM_DESTROY: - PostQuitMessage(0); - return 0; - } - return DefWindowProc(hWnd, msg, wParam, lParam); -} - +// Forward declarations of helper functions +bool CreateDeviceD3D(HWND hWnd); +void CleanupDeviceD3D(); +void CreateRenderTarget(); +void CleanupRenderTarget(); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Main code int main(int, char**) { // Create application window WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - RegisterClassEx(&wc); - HWND hwnd = CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + ::RegisterClassEx(&wc); + HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D - if (CreateDeviceD3D(hwnd) < 0) + if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); return 1; } // Show the window - ShowWindow(hwnd, SW_SHOWDEFAULT); - UpdateWindow(hwnd); + ::ShowWindow(hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(hwnd); // Setup Dear ImGui context IMGUI_CHECKVERSION(); @@ -157,10 +86,10 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. - if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); continue; } @@ -221,8 +150,89 @@ int main(int, char**) ImGui::DestroyContext(); CleanupDeviceD3D(); - DestroyWindow(hwnd); - UnregisterClass(wc.lpszClassName, wc.hInstance); + ::DestroyWindow(hwnd); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); return 0; } + +// Helper functions + +bool CreateDeviceD3D(HWND hWnd) +{ + // Setup swap chain + DXGI_SWAP_CHAIN_DESC sd; + ZeroMemory(&sd, sizeof(sd)); + sd.BufferCount = 2; + sd.BufferDesc.Width = 0; + sd.BufferDesc.Height = 0; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.RefreshRate.Numerator = 60; + sd.BufferDesc.RefreshRate.Denominator = 1; + sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.OutputWindow = hWnd; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.Windowed = TRUE; + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + UINT createDeviceFlags = 0; + //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + D3D_FEATURE_LEVEL featureLevel; + const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; + if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) + return false; + + CreateRenderTarget(); + return true; +} + +void CleanupDeviceD3D() +{ + CleanupRenderTarget(); + if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } + if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } +} + +void CreateRenderTarget() +{ + ID3D11Texture2D* pBackBuffer; + g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); + pBackBuffer->Release(); +} + +void CleanupRenderTarget() +{ + if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } +} + +// Win32 message handler +extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) + { + CleanupRenderTarget(); + g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); + CreateRenderTarget(); + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProc(hWnd, msg, wParam, lParam); +} diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index c650d193..6f306660 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -36,90 +36,183 @@ static HANDLE g_hSwapChainWaitableObject = NULL; static ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {}; static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {}; -void CreateRenderTarget() +// Forward declarations of helper functions +bool CreateDeviceD3D(HWND hWnd); +void CleanupDeviceD3D(); +void CreateRenderTarget(); +void CleanupRenderTarget(); +void WaitForLastSubmittedFrame(); +FrameContext* WaitForNextFrameResources(); +void ResizeSwapChain(HWND hWnd, int width, int height); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Main code +int main(int, char**) { - ID3D12Resource* pBackBuffer; - for (UINT i = 0; i < NUM_BACK_BUFFERS; i++) + // Create application window + WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; + ::RegisterClassEx(&wc); + HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + + // Initialize Direct3D + if (!CreateDeviceD3D(hwnd)) { - g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer)); - g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, g_mainRenderTargetDescriptor[i]); - g_mainRenderTargetResource[i] = pBackBuffer; + CleanupDeviceD3D(); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); + return 1; } -} -void WaitForLastSubmittedFrame() -{ - FrameContext* frameCtxt = &g_frameContext[g_frameIndex % NUM_FRAMES_IN_FLIGHT]; + // Show the window + ::ShowWindow(hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(hwnd); - UINT64 fenceValue = frameCtxt->FenceValue; - if (fenceValue == 0) - return; // No fence was signaled + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - frameCtxt->FenceValue = 0; - if (g_fence->GetCompletedValue() >= fenceValue) - return; + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); - g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent); - WaitForSingleObject(g_fenceEvent, INFINITE); -} + // Setup Platform/Renderer bindings + ImGui_ImplWin32_Init(hwnd); + ImGui_ImplDX12_Init(g_pd3dDevice, NUM_FRAMES_IN_FLIGHT, + DXGI_FORMAT_R8G8B8A8_UNORM, + g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(), + g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart()); -FrameContext* WaitForNextFrameResources() -{ - UINT nextFrameIndex = g_frameIndex + 1; - g_frameIndex = nextFrameIndex; + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Read 'misc/fonts/README.txt' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != NULL); - HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, NULL }; - DWORD numWaitableObjects = 1; + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); - FrameContext* frameCtxt = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT]; - UINT64 fenceValue = frameCtxt->FenceValue; - if (fenceValue != 0) // means no fence was signaled + // Main loop + MSG msg; + ZeroMemory(&msg, sizeof(msg)); + while (msg.message != WM_QUIT) { - frameCtxt->FenceValue = 0; - g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent); - waitableObjects[1] = g_fenceEvent; - numWaitableObjects = 2; - } + // Poll and handle messages (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + continue; + } - WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE); + // Start the Dear ImGui frame + ImGui_ImplDX12_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); - return frameCtxt; -} + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); -void ResizeSwapChain(HWND hWnd, int width, int height) -{ - DXGI_SWAP_CHAIN_DESC1 sd; - g_pSwapChain->GetDesc1(&sd); - sd.Width = width; - sd.Height = height; + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + { + static float f = 0.0f; + static int counter = 0; - IDXGIFactory4* dxgiFactory = NULL; - g_pSwapChain->GetParent(IID_PPV_ARGS(&dxgiFactory)); + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. - g_pSwapChain->Release(); - CloseHandle(g_hSwapChainWaitableObject); + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); - IDXGISwapChain1* swapChain1 = NULL; - dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1); - swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)); - swapChain1->Release(); - dxgiFactory->Release(); + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color - g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS); + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); - g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject(); - assert(g_hSwapChainWaitableObject != NULL); -} + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + FrameContext* frameCtxt = WaitForNextFrameResources(); + UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex(); + frameCtxt->CommandAllocator->Reset(); + + D3D12_RESOURCE_BARRIER barrier = {}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; + barrier.Transition.pResource = g_mainRenderTargetResource[backBufferIdx]; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; + + g_pd3dCommandList->Reset(frameCtxt->CommandAllocator, NULL); + g_pd3dCommandList->ResourceBarrier(1, &barrier); + g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], (float*)&clear_color, 0, NULL); + g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, NULL); + g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap); + ImGui::Render(); + ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), g_pd3dCommandList); + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; + g_pd3dCommandList->ResourceBarrier(1, &barrier); + g_pd3dCommandList->Close(); + + g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList); + + g_pSwapChain->Present(1, 0); // Present with vsync + //g_pSwapChain->Present(0, 0); // Present without vsync + + UINT64 fenceValue = g_fenceLastSignaledValue + 1; + g_pd3dCommandQueue->Signal(g_fence, fenceValue); + g_fenceLastSignaledValue = fenceValue; + frameCtxt->FenceValue = fenceValue; + } -void CleanupRenderTarget() -{ WaitForLastSubmittedFrame(); + ImGui_ImplDX12_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); - for (UINT i = 0; i < NUM_BACK_BUFFERS; i++) - if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = NULL; } + CleanupDeviceD3D(); + ::DestroyWindow(hwnd); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); + + return 0; } -HRESULT CreateDeviceD3D(HWND hWnd) +// Helper functions + +bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain DXGI_SWAP_CHAIN_DESC1 sd; @@ -151,16 +244,16 @@ HRESULT CreateDeviceD3D(HWND hWnd) D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; if (D3D12CreateDevice(NULL, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK) - return E_FAIL; + return false; { D3D12_DESCRIPTOR_HEAP_DESC desc = {}; - desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; desc.NumDescriptors = NUM_BACK_BUFFERS; - desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; - desc.NodeMask = 1; + desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + desc.NodeMask = 1; if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK) - return E_FAIL; + return false; SIZE_T rtvDescriptorSize = g_pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pd3dRtvDescHeap->GetCPUDescriptorHandleForHeapStart(); @@ -177,32 +270,32 @@ HRESULT CreateDeviceD3D(HWND hWnd) desc.NumDescriptors = 1; desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dSrvDescHeap)) != S_OK) - return E_FAIL; + return false; } { D3D12_COMMAND_QUEUE_DESC desc = {}; - desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; desc.NodeMask = 1; if (g_pd3dDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(&g_pd3dCommandQueue)) != S_OK) - return E_FAIL; + return false; } for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++) if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK) - return E_FAIL; + return false; if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, NULL, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK || g_pd3dCommandList->Close() != S_OK) - return E_FAIL; + return false; if (g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_fence)) != S_OK) - return E_FAIL; + return false; g_fenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (g_fenceEvent == NULL) - return E_FAIL; + return false; { IDXGIFactory4* dxgiFactory = NULL; @@ -210,7 +303,7 @@ HRESULT CreateDeviceD3D(HWND hWnd) if (CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) != S_OK || dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1) != S_OK || swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)) != S_OK) - return E_FAIL; + return false; swapChain1->Release(); dxgiFactory->Release(); g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS); @@ -218,8 +311,7 @@ HRESULT CreateDeviceD3D(HWND hWnd) } CreateRenderTarget(); - - return S_OK; + return true; } void CleanupDeviceD3D() @@ -238,193 +330,115 @@ void CleanupDeviceD3D() if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } } -extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +void CreateRenderTarget() { - if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) - return true; - - switch (msg) + ID3D12Resource* pBackBuffer; + for (UINT i = 0; i < NUM_BACK_BUFFERS; i++) { - case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) - { - ImGui_ImplDX12_InvalidateDeviceObjects(); - CleanupRenderTarget(); - ResizeSwapChain(hWnd, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam)); - CreateRenderTarget(); - ImGui_ImplDX12_CreateDeviceObjects(); - } - return 0; - case WM_SYSCOMMAND: - if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu - return 0; - break; - case WM_DESTROY: - PostQuitMessage(0); - return 0; + g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer)); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, g_mainRenderTargetDescriptor[i]); + g_mainRenderTargetResource[i] = pBackBuffer; } - return DefWindowProc(hWnd, msg, wParam, lParam); } -int main(int, char**) +void CleanupRenderTarget() { - // Create application window - WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - RegisterClassEx(&wc); - HWND hwnd = CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + WaitForLastSubmittedFrame(); - // Initialize Direct3D - if (CreateDeviceD3D(hwnd) < 0) - { - CleanupDeviceD3D(); - UnregisterClass(wc.lpszClassName, wc.hInstance); - return 1; - } + for (UINT i = 0; i < NUM_BACK_BUFFERS; i++) + if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = NULL; } +} - // Show the window - ShowWindow(hwnd, SW_SHOWDEFAULT); - UpdateWindow(hwnd); +void WaitForLastSubmittedFrame() +{ + FrameContext* frameCtxt = &g_frameContext[g_frameIndex % NUM_FRAMES_IN_FLIGHT]; - // Setup Dear ImGui context - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + UINT64 fenceValue = frameCtxt->FenceValue; + if (fenceValue == 0) + return; // No fence was signaled - // Setup Dear ImGui style - ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + frameCtxt->FenceValue = 0; + if (g_fence->GetCompletedValue() >= fenceValue) + return; - // Setup Platform/Renderer bindings - ImGui_ImplWin32_Init(hwnd); - ImGui_ImplDX12_Init(g_pd3dDevice, NUM_FRAMES_IN_FLIGHT, - DXGI_FORMAT_R8G8B8A8_UNORM, - g_pd3dSrvDescHeap->GetCPUDescriptorHandleForHeapStart(), - g_pd3dSrvDescHeap->GetGPUDescriptorHandleForHeapStart()); + g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent); + WaitForSingleObject(g_fenceEvent, INFINITE); +} - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'misc/fonts/README.txt' for more instructions and details. - // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); +FrameContext* WaitForNextFrameResources() +{ + UINT nextFrameIndex = g_frameIndex + 1; + g_frameIndex = nextFrameIndex; - bool show_demo_window = true; - bool show_another_window = false; - ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, NULL }; + DWORD numWaitableObjects = 1; - // Main loop - MSG msg; - ZeroMemory(&msg, sizeof(msg)); - while (msg.message != WM_QUIT) + FrameContext* frameCtxt = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT]; + UINT64 fenceValue = frameCtxt->FenceValue; + if (fenceValue != 0) // means no fence was signaled { - // Poll and handle messages (inputs, window resize, etc.) - // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. - // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. - // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. - // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. - if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - continue; - } + frameCtxt->FenceValue = 0; + g_fence->SetEventOnCompletion(fenceValue, g_fenceEvent); + waitableObjects[1] = g_fenceEvent; + numWaitableObjects = 2; + } - // Start the Dear ImGui frame - ImGui_ImplDX12_NewFrame(); - ImGui_ImplWin32_NewFrame(); - ImGui::NewFrame(); + WaitForMultipleObjects(numWaitableObjects, waitableObjects, TRUE, INFINITE); - // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). - if (show_demo_window) - ImGui::ShowDemoWindow(&show_demo_window); + return frameCtxt; +} - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. - { - static float f = 0.0f; - static int counter = 0; +void ResizeSwapChain(HWND hWnd, int width, int height) +{ + DXGI_SWAP_CHAIN_DESC1 sd; + g_pSwapChain->GetDesc1(&sd); + sd.Width = width; + sd.Height = height; - ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + IDXGIFactory4* dxgiFactory = NULL; + g_pSwapChain->GetParent(IID_PPV_ARGS(&dxgiFactory)); - ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) - ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state - ImGui::Checkbox("Another Window", &show_another_window); + g_pSwapChain->Release(); + CloseHandle(g_hSwapChainWaitableObject); - ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + IDXGISwapChain1* swapChain1 = NULL; + dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1); + swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)); + swapChain1->Release(); + dxgiFactory->Release(); - if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) - counter++; - ImGui::SameLine(); - ImGui::Text("counter = %d", counter); + g_pSwapChain->SetMaximumFrameLatency(NUM_BACK_BUFFERS); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); - ImGui::End(); - } + g_hSwapChainWaitableObject = g_pSwapChain->GetFrameLatencyWaitableObject(); + assert(g_hSwapChainWaitableObject != NULL); +} - // 3. Show another simple window. - if (show_another_window) +// Win32 message handler +extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { - ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) - ImGui::Text("Hello from another window!"); - if (ImGui::Button("Close Me")) - show_another_window = false; - ImGui::End(); + ImGui_ImplDX12_InvalidateDeviceObjects(); + CleanupRenderTarget(); + ResizeSwapChain(hWnd, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam)); + CreateRenderTarget(); + ImGui_ImplDX12_CreateDeviceObjects(); } - - // Rendering - FrameContext* frameCtxt = WaitForNextFrameResources(); - UINT backBufferIdx = g_pSwapChain->GetCurrentBackBufferIndex(); - frameCtxt->CommandAllocator->Reset(); - - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrier.Transition.pResource = g_mainRenderTargetResource[backBufferIdx]; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - - g_pd3dCommandList->Reset(frameCtxt->CommandAllocator, NULL); - g_pd3dCommandList->ResourceBarrier(1, &barrier); - g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], (float*)&clear_color, 0, NULL); - g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, NULL); - g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap); - ImGui::Render(); - ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), g_pd3dCommandList); - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; - g_pd3dCommandList->ResourceBarrier(1, &barrier); - g_pd3dCommandList->Close(); - - g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList); - - g_pSwapChain->Present(1, 0); // Present with vsync - //g_pSwapChain->Present(0, 0); // Present without vsync - - UINT64 fenceValue = g_fenceLastSignaledValue + 1; - g_pd3dCommandQueue->Signal(g_fence, fenceValue); - g_fenceLastSignaledValue = fenceValue; - frameCtxt->FenceValue = fenceValue; + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; } - - WaitForLastSubmittedFrame(); - ImGui_ImplDX12_Shutdown(); - ImGui_ImplWin32_Shutdown(); - ImGui::DestroyContext(); - - CleanupDeviceD3D(); - DestroyWindow(hwnd); - UnregisterClass(wc.lpszClassName, wc.hInstance); - - return 0; + return ::DefWindowProc(hWnd, msg, wParam, lParam); } diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index eee800e0..57ceadbf 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -14,86 +14,31 @@ static LPDIRECT3D9 g_pD3D = NULL; static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static D3DPRESENT_PARAMETERS g_d3dpp = {}; -HRESULT CreateDeviceD3D(HWND hWnd) -{ - if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) - return E_FAIL; - - // Create the D3DDevice - ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); - g_d3dpp.Windowed = TRUE; - g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; - g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; - g_d3dpp.EnableAutoDepthStencil = TRUE; - g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; - g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync - //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate - if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) - return E_FAIL; - - return S_OK; -} - -void CleanupDeviceD3D() -{ - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } - if (g_pD3D) { g_pD3D->Release(); g_pD3D = NULL; } -} - -void ResetDevice() -{ - ImGui_ImplDX9_InvalidateDeviceObjects(); - HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); - if (hr == D3DERR_INVALIDCALL) - IM_ASSERT(0); - ImGui_ImplDX9_CreateDeviceObjects(); -} - -extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) - return true; - - switch (msg) - { - case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) - { - g_d3dpp.BackBufferWidth = LOWORD(lParam); - g_d3dpp.BackBufferHeight = HIWORD(lParam); - ResetDevice(); - } - return 0; - case WM_SYSCOMMAND: - if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu - return 0; - break; - case WM_DESTROY: - PostQuitMessage(0); - return 0; - } - return DefWindowProc(hWnd, msg, wParam, lParam); -} +// Forward declarations of helper functions +bool CreateDeviceD3D(HWND hWnd); +void CleanupDeviceD3D(); +void ResetDevice(); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +// Main code int main(int, char**) { // Create application window WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - RegisterClassEx(&wc); - HWND hwnd = CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + ::RegisterClassEx(&wc); + HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D - if (CreateDeviceD3D(hwnd) < 0) + if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); return 1; } // Show the window - ShowWindow(hwnd, SW_SHOWDEFAULT); - UpdateWindow(hwnd); + ::ShowWindow(hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(hwnd); // Setup Dear ImGui context IMGUI_CHECKVERSION(); @@ -139,10 +84,10 @@ int main(int, char**) // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. - if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); continue; } @@ -213,8 +158,73 @@ int main(int, char**) ImGui::DestroyContext(); CleanupDeviceD3D(); - DestroyWindow(hwnd); - UnregisterClass(wc.lpszClassName, wc.hInstance); + ::DestroyWindow(hwnd); + ::UnregisterClass(wc.lpszClassName, wc.hInstance); return 0; } + +// Helper functions + +bool CreateDeviceD3D(HWND hWnd) +{ + if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) + return false; + + // Create the D3DDevice + ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); + g_d3dpp.Windowed = TRUE; + g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; + g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; + g_d3dpp.EnableAutoDepthStencil = TRUE; + g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; + g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync + //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate + if (g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) + return false; + + return true; +} + +void CleanupDeviceD3D() +{ + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } + if (g_pD3D) { g_pD3D->Release(); g_pD3D = NULL; } +} + +void ResetDevice() +{ + ImGui_ImplDX9_InvalidateDeviceObjects(); + HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); + if (hr == D3DERR_INVALIDCALL) + IM_ASSERT(0); + ImGui_ImplDX9_CreateDeviceObjects(); +} + +// Win32 message handler +extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) + { + g_d3dpp.BackBufferWidth = LOWORD(lParam); + g_d3dpp.BackBufferHeight = HIWORD(lParam); + ResetDevice(); + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProc(hWnd, msg, wParam, lParam); +} From 3ead9820f7dc43d9ccafc51849aab441bd5e17c0 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Mar 2019 16:51:46 +0100 Subject: [PATCH 153/566] Viewport: Popups and Tooltips viewports are correctly parented to the parent window's viewport. (#2409, #1542) --- imgui.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index aa858b9a..48591b2a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5623,6 +5623,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // We don't default to the main viewport because. if (window->WindowClass.ParentViewportId) window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId; + else if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack) + window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID; else window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; if (window->WindowClass.ViewportFlagsOverrideMask) From e1acb0b1faaacb0f3b96bfa11b3f992bb51ab06d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Mar 2019 19:46:37 +0100 Subject: [PATCH 154/566] Docking: Fixed node merging altering window position incorrectly in a way that would make SizeContents incorrect for the next frame (making scrollbar flicker). (#2414, #2109) --- imgui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 48591b2a..53316f2c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11536,8 +11536,8 @@ static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node) { for (int n = 0; n < node->Windows.Size; n++) { - node->Windows[n]->Pos = node->Pos; - node->Windows[n]->SizeFull = node->Size; + SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame + SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always); } } From 65c2220049b876dbb083b9e2ec1d391d9c8e7817 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Mar 2019 20:14:56 +0100 Subject: [PATCH 155/566] Internal: Removed unused fields from ImGuiMenuColumns. --- imgui_internal.h | 3 +-- imgui_widgets.cpp | 11 +++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 1ff750c5..9132551a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -568,10 +568,9 @@ struct ImGuiGroupData // Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. struct IMGUI_API ImGuiMenuColumns { - int Count; float Spacing; float Width, NextWidth; - float Pos[4], NextWidths[4]; + float Pos[3], NextWidths[3]; ImGuiMenuColumns(); void Update(int count, float spacing, bool clear); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index de0bf6b9..2f150387 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5674,7 +5674,6 @@ void ImGui::Value(const char* prefix, float v, const char* float_format) // Helpers for internal use ImGuiMenuColumns::ImGuiMenuColumns() { - Count = 0; Spacing = Width = NextWidth = 0.0f; memset(Pos, 0, sizeof(Pos)); memset(NextWidths, 0, sizeof(NextWidths)); @@ -5682,12 +5681,12 @@ ImGuiMenuColumns::ImGuiMenuColumns() void ImGuiMenuColumns::Update(int count, float spacing, bool clear) { - IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); - Count = count; + IM_ASSERT(count == IM_ARRAYSIZE(Pos)); Width = NextWidth = 0.0f; Spacing = spacing; - if (clear) memset(NextWidths, 0, sizeof(NextWidths)); - for (int i = 0; i < Count; i++) + if (clear) + memset(NextWidths, 0, sizeof(NextWidths)); + for (int i = 0; i < IM_ARRAYSIZE(Pos); i++) { if (i > 0 && NextWidths[i] > 0.0f) Width += Spacing; @@ -5703,7 +5702,7 @@ float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using v NextWidths[0] = ImMax(NextWidths[0], w0); NextWidths[1] = ImMax(NextWidths[1], w1); NextWidths[2] = ImMax(NextWidths[2], w2); - for (int i = 0; i < 3; i++) + for (int i = 0; i < IM_ARRAYSIZE(Pos); i++) NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); return ImMax(Width, NextWidth); } From a92c587c75c42334f064476c5ac25a450dfd6bf6 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 Mar 2019 22:02:59 +0100 Subject: [PATCH 156/566] Added GetGlyphRangesVietnamese() helper. (#2403) --- docs/CHANGELOG.txt | 1 + imgui.h | 1 + imgui_draw.cpp | 17 +++++++++++++++++ 3 files changed, 19 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ff2f387b..423844ff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,7 @@ Other Changes: - Log/Capture: Fixed LogXXX functions 'auto_open_depth' parameter being treated as an absolute tree depth instead of a relative one. - Log/Capture: Fixed CollapsingHeader trailing ascii representation being "#" instead of "##". +- ImFont: Added GetGlyphRangesVietnamese() helper. (#2403) - Misc: Asserting in NewFrame() if style.WindowMinSize is zero or smaller than (1.0f,1.0f). - Demo: Using GetBackgroundDrawList() and GetForegroundDrawList() in "Custom Rendering" demo. - Examples: OpenGL: Fix to be able to run on ES 2.0 / WebGL 1.0. [@rmitton, @gabrielcuvillier] diff --git a/imgui.h b/imgui.h index 2fbf4fc3..6616ace3 100644 --- a/imgui.h +++ b/imgui.h @@ -2047,6 +2047,7 @@ struct ImFontAtlas IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietname characters //------------------------------------------- // Custom Rectangles/Glyphs API diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 52175e29..203b6f7b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2346,6 +2346,23 @@ const ImWchar* ImFontAtlas::GetGlyphRangesThai() return &ranges[0]; } +const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + 0x0102, 0x0103, + 0x0110, 0x0111, + 0x0128, 0x0129, + 0x0168, 0x0169, + 0x01A0, 0x01A1, + 0x01AF, 0x01B0, + 0x1EA0, 0x1EF9, + 0, + }; + return &ranges[0]; +} + //----------------------------------------------------------------------------- // [SECTION] ImFontGlyphRangesBuilder //----------------------------------------------------------------------------- From 897badec7a96ddbe727bd25e9fac3575591d1198 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Mar 2019 11:24:49 +0100 Subject: [PATCH 157/566] Demo: InputText: Demonstrating use of ImGuiInputTextFlags_CallbackResize. (#2006, #1443, #1008). --- docs/CHANGELOG.txt | 1 + imgui_demo.cpp | 119 ++++++++++++++++++++++++++++-------------- misc/fonts/README.txt | 3 ++ 3 files changed, 84 insertions(+), 39 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 423844ff..f91d4b29 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -88,6 +88,7 @@ Other Changes: - ImFont: Added GetGlyphRangesVietnamese() helper. (#2403) - Misc: Asserting in NewFrame() if style.WindowMinSize is zero or smaller than (1.0f,1.0f). - Demo: Using GetBackgroundDrawList() and GetForegroundDrawList() in "Custom Rendering" demo. +- Demo: InputText: Demonstrating use of ImGuiInputTextFlags_CallbackResize. (#2006, #1443, #1008). - Examples: OpenGL: Fix to be able to run on ES 2.0 / WebGL 1.0. [@rmitton, @gabrielcuvillier] - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 767fcb06..40a674dd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -921,48 +921,89 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } - if (ImGui::TreeNode("Filtered Text Input")) + if (ImGui::TreeNode("Text Input")) { - static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); - static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); - static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); - static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); - struct TextFilters { static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; - static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); - - ImGui::Text("Password input"); - static char bufpass[64] = "password123"; - ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); - ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); - ImGui::InputTextWithHint("password (w/ hint)", "", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); - ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); + if (ImGui::TreeNode("Multi-line Text Input")) + { + // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize + // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings. + static char text[1024 * 16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; + HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp)"); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput); + ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), flags); + ImGui::TreePop(); + } - ImGui::TreePop(); - } + if (ImGui::TreeNode("Filtered Text Input")) + { + static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); + static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); + static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); + struct TextFilters { static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; + static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + + ImGui::Text("Password input"); + static char bufpass[64] = "password123"; + ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); + ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputTextWithHint("password (w/ hint)", "", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); + ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Resize Callback")) + { + // If you have a custom string type you would typically create a ImGui::InputText() wrapper than takes your type as input. + // See misc/cpp/imgui_stdlib.h and .cpp for an implementation of this using std::string. + HelpMarker("Demonstrate using ImGuiInputTextFlags_CallbackResize to wire your resizable string type to InputText().\n\nSee misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); + struct Funcs + { + static int MyResizeCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) + { + ImVector* my_str = (ImVector*)data->UserData; + IM_ASSERT(my_str->begin() == data->Buf); + my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 + data->Buf = my_str->begin(); + } + return 0; + } + + // Tip: Because ImGui:: is a namespace you can add your own function into the namespace from your own source files. + static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) + { + IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); + return ImGui::InputTextMultiline(label, my_str->begin(), my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str); + } + }; + + // For this demo we are using ImVector as a string container. + // Note that because we need to store a terminating zero character, our size/capacity are 1 more than usually reported by a typical string class. + static ImVector my_str; + if (my_str.empty()) + my_str.push_back(0); + Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16)); + ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", my_str.begin(), my_str.size(), my_str.capacity()); + ImGui::TreePop(); + } - if (ImGui::TreeNode("Multi-line Text Input")) - { - // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize - // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings. - static char text[1024*16] = - "/*\n" - " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" - " the hexadecimal encoding of one offending instruction,\n" - " more formally, the invalid operand with locked CMPXCHG8B\n" - " instruction bug, is a design flaw in the majority of\n" - " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" - " processors (all in the P5 microarchitecture).\n" - "*/\n\n" - "label:\n" - "\tlock cmpxchg8b eax\n"; - - static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; - HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp)"); - ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly); - ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput); - ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine); - ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), flags); ImGui::TreePop(); } diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index a69bc19f..37a095a9 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -294,6 +294,9 @@ MONOSPACE FONTS https://github.com/kmar/Sweet16Font Also include .inl file to use directly in dear imgui. + Google Noto Mono Fonts + https://www.google.com/get/noto/ + Typefaces for source code beautification https://github.com/chrissimpkins/codeface From f25416833523a64a1797a0fe450605d091dd9045 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Mar 2019 11:56:40 +0100 Subject: [PATCH 158/566] InputText: Fixed c779fbb leading to display of the wrong buffer when resizing a buffer. (#2400, #2006, #1443, #1008). --- imgui_widgets.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2f150387..9ea1a6ef 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3366,14 +3366,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ bool enter_pressed = false; // Select the buffer to render. - const char* buf_display = ((render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid) ? state->TextA.Data : buf; - const char* buf_display_end = NULL; // We have specialized paths below for setting the length - const bool is_displaying_hint = (hint != NULL && buf_display[0] == 0); - if (is_displaying_hint) - { - buf_display = hint; - buf_display_end = hint + strlen(hint); - } + const bool buf_display_from_state = ((render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid); + const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); // Password pushes a temporary font with only a fallback glyph if (is_password && !is_displaying_hint) @@ -3740,6 +3734,13 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. const int buf_display_max_length = 2 * 1024 * 1024; + const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; + const char* buf_display_end = NULL; // We have specialized paths below for setting the length + if (is_displaying_hint) + { + buf_display = hint; + buf_display_end = hint + strlen(hint); + } // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. From 495065f79068a67c3a32bb8dbdc43b872376ac30 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Mar 2019 12:08:51 +0100 Subject: [PATCH 159/566] Fixed Clang and PVS warnings. --- imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 40a674dd..c3e2d1a8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -990,7 +990,7 @@ static void ShowDemoWindowWidgets() static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) { IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); - return ImGui::InputTextMultiline(label, my_str->begin(), my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str); + return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str); } }; @@ -1000,7 +1000,7 @@ static void ShowDemoWindowWidgets() if (my_str.empty()) my_str.push_back(0); Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16)); - ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", my_str.begin(), my_str.size(), my_str.capacity()); + ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity()); ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9ea1a6ef..3bf10af2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3366,7 +3366,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ bool enter_pressed = false; // Select the buffer to render. - const bool buf_display_from_state = ((render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid); + const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid; const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); // Password pushes a temporary font with only a fallback glyph @@ -3734,7 +3734,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. const int buf_display_max_length = 2 * 1024 * 1024; - const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; + const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595 const char* buf_display_end = NULL; // We have specialized paths below for setting the length if (is_displaying_hint) { From cfa8f672f6ece16e8e574a61fb406294777b720b Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Mar 2019 18:27:14 +0100 Subject: [PATCH 160/566] Examples: GLFW, SDL: Preserve DisplayFramebufferScale when main viewport is minimized. (This is particularly useful for the viewport branch because we are not supporting per-viewport frame-buffer scale. It fixes windows not refreshing when main viewport is minimized.) (#2416) --- docs/CHANGELOG.txt | 3 +++ examples/imgui_impl_glfw.cpp | 4 +++- examples/imgui_impl_sdl.cpp | 4 +++- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f91d4b29..b4568ec3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -89,6 +89,9 @@ Other Changes: - Misc: Asserting in NewFrame() if style.WindowMinSize is zero or smaller than (1.0f,1.0f). - Demo: Using GetBackgroundDrawList() and GetForegroundDrawList() in "Custom Rendering" demo. - Demo: InputText: Demonstrating use of ImGuiInputTextFlags_CallbackResize. (#2006, #1443, #1008). +- Examples: GLFW, SDL: Preserve DisplayFramebufferScale when main viewport is minimized. + (This is particularly useful for the viewport branch because we are not supporting per-viewport + frame-buffer scale. It fixes windows not refreshing when main viewport is minimized.) (#2416) - Examples: OpenGL: Fix to be able to run on ES 2.0 / WebGL 1.0. [@rmitton, @gabrielcuvillier] - Examples: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if the OpenGL headers/loader happens to define the value. (#2366, #2186) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index d5c0b13b..0ed40cde 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them. // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls. @@ -313,7 +314,8 @@ void ImGui_ImplGlfw_NewFrame() glfwGetWindowSize(g_Window, &w, &h); glfwGetFramebufferSize(g_Window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); - io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); + if (w > 0 && h > 0) + io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); // Setup time step double current_time = glfwGetTime(); diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index c1188dba..528dbba3 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'. @@ -279,7 +280,8 @@ void ImGui_ImplSDL2_NewFrame(SDL_Window* window) SDL_GetWindowSize(window, &w, &h); SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); - io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); + if (w > 0 && h > 0) + io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) static Uint64 frequency = SDL_GetPerformanceFrequency(); From 99d84251730549fd50fd5b45c9a623c56edcc1c1 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Mar 2019 18:56:19 +0100 Subject: [PATCH 161/566] TabBar: Fixed Tab tooltip code making drag and drop tooltip disappear during the frame where the drag payload activate a tab. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b4568ec3..6ecd1eb7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -75,6 +75,8 @@ Other Changes: hard crashes any more, facilitating integration with scripting languages. (#1651) - TabBar: Fixed ImGuiTabItemFlags_SetSelected being ignored if the tab is not visible (with scrolling policy enabled) or if is currently appearing. +- TabBar: Fixed Tab tooltip code making drag and drop tooltip disappear during the frame where + the drag payload activate a tab. - Text: Fixed large Text/TextUnformatted call not declaring its size when starting below the lower point of the current clipping rectangle. Somehow this bug has been there since v1.0! It was hardly noticeable but would affect the scrolling range, which in turn would affect diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3bf10af2..6d2ccc9c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6779,7 +6779,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, window->DC.CursorPos = backup_main_cursor_pos; // Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer) - if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f) + // We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores) + if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered()) if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip)) SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); From 53e0c13be20c9986d52b385fd07f35504350a6de Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Mar 2019 20:57:02 +0100 Subject: [PATCH 162/566] TabBar: Reworked scrolling policy (when ImGuiTabBarFlags_FittingPolicyScroll is set) to teleport the view when aiming at a tab far away the visible section, and otherwise accelerate the scrolling speed to cap the scrolling time to 0.3 seconds. --- docs/CHANGELOG.txt | 3 +++ imgui_internal.h | 2 ++ imgui_widgets.cpp | 25 +++++++++++++++++++++---- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ecd1eb7..31af0bfa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,9 @@ Other Changes: scrolling policy enabled) or if is currently appearing. - TabBar: Fixed Tab tooltip code making drag and drop tooltip disappear during the frame where the drag payload activate a tab. +- TabBar: Reworked scrolling policy (when ImGuiTabBarFlags_FittingPolicyScroll is set) to + teleport the view when aiming at a tab far away the visible section, and otherwise accelerate + the scrolling speed to cap the scrolling time to 0.3 seconds. - Text: Fixed large Text/TextUnformatted call not declaring its size when starting below the lower point of the current clipping rectangle. Somehow this bug has been there since v1.0! It was hardly noticeable but would affect the scrolling range, which in turn would affect diff --git a/imgui_internal.h b/imgui_internal.h index 9132551a..089ca2e1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1340,6 +1340,8 @@ struct ImGuiTabBar float OffsetNextTab; // Distance from BarRect.Min.x, incremented with each BeginTabItem() call, not used if ImGuiTabBarFlags_Reorderable if set. float ScrollingAnim; float ScrollingTarget; + float ScrollingTargetDistToVisibility; + float ScrollingSpeed; ImGuiTabBarFlags Flags; ImGuiID ReorderRequestTabId; int ReorderRequestDir; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6d2ccc9c..6ff81177 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6064,7 +6064,7 @@ ImGuiTabBar::ImGuiTabBar() CurrFrameVisible = PrevFrameVisible = -1; ContentsHeight = 0.0f; OffsetMax = OffsetNextTab = 0.0f; - ScrollingAnim = ScrollingTarget = 0.0f; + ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; ReorderRequestDir = 0; @@ -6358,9 +6358,19 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) TabBarScrollToTab(tab_bar, scroll_track_selected_tab); tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim); tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget); - const float scrolling_speed = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) ? FLT_MAX : (g.IO.DeltaTime * g.FontSize * 70.0f); if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget) - tab_bar->ScrollingAnim = ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, scrolling_speed); + { + // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds. + // Teleport if we are aiming far off the visible line + tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize); + tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f); + const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize); + tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed); + } + else + { + tab_bar->ScrollingSpeed = 0.0f; + } // Clear name buffers if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) @@ -6438,10 +6448,17 @@ static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) int order = tab_bar->GetTabOrder(tab); float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f); float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); + tab_bar->ScrollingTargetDistToVisibility = 0.0f; if (tab_bar->ScrollingTarget > tab_x1) + { + tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f); tab_bar->ScrollingTarget = tab_x1; - if (tab_bar->ScrollingTarget + tab_bar->BarRect.GetWidth() < tab_x2) + } + else if (tab_bar->ScrollingTarget < tab_x2 - tab_bar->BarRect.GetWidth()) + { + tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - tab_bar->BarRect.GetWidth()) - tab_bar->ScrollingAnim, 0.0f); tab_bar->ScrollingTarget = tab_x2 - tab_bar->BarRect.GetWidth(); + } } void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir) From a26085ed53d07603a9fde0e164ad69773d119642 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 Mar 2019 22:23:56 +0100 Subject: [PATCH 163/566] Internals: Fixed Navigation from reaching ImGuiItemFlags_Disabled items (#211) + Examples comments --- examples/example_win32_directx10/main.cpp | 1 + examples/example_win32_directx11/main.cpp | 1 + examples/example_win32_directx12/main.cpp | 1 + examples/example_win32_directx9/main.cpp | 1 + imgui.cpp | 2 +- imgui_widgets.cpp | 2 +- 6 files changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index c3fc03af..7b4a598e 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -47,6 +47,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 3eff1d96..9c338529 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -47,6 +47,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 6f306660..82f1e547 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -71,6 +71,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 57ceadbf..74a19d09 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -45,6 +45,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/imgui.cpp b/imgui.cpp index 47dc7526..0db2fec9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7353,7 +7353,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con // Process Move Request (scoring for navigation) // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy) - if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_NoNav)) + if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav))) { ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; #if IMGUI_DEBUG_NAV_SCORING diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6ff81177..b84e2c5d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5276,7 +5276,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (flags & ImGuiSelectableFlags_Disabled) { ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; - window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus; + window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus; item_add = ItemAdd(bb, id); window->DC.ItemFlags = backup_item_flags; } From e7dca4fec2c4b55731103b7a7a3b2dcb7617a444 Mon Sep 17 00:00:00 2001 From: David Maas Date: Wed, 13 Mar 2019 00:57:15 -0500 Subject: [PATCH 164/566] Fixed main viewport not being marked as created, which broke updating the IME input position for the main viewport. This change also removes the logic scattered about that compensated for PlatformWindowCreated being wrong for the main viewport. --- imgui.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 53316f2c..4b1b9f77 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3790,6 +3790,7 @@ void ImGui::Initialize(ImGuiContext* context) ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)(); viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID; viewport->Idx = 0; + viewport->PlatformWindowCreated = true; g.Viewports.push_back(viewport); g.PlatformIO.MainViewport = g.Viewports[0]; // Make it accessible in public-facing GetPlatformIO() immediately (before the first call to EndFrame) g.PlatformIO.Viewports.push_back(g.Viewports[0]); @@ -10078,7 +10079,7 @@ static void ImGui::UpdateViewportsNewFrame() for (int n = 0; n < g.Viewports.Size; n++) { ImGuiViewportP* viewport = g.Viewports[n]; - const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated); + const bool platform_funcs_available = viewport->PlatformWindowCreated; if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) viewport->PlatformWindowMinimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); @@ -10124,7 +10125,7 @@ static void ImGui::UpdateViewportsNewFrame() continue; } - const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated); + const bool platform_funcs_available = viewport->PlatformWindowCreated; if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) { // Update Position and Size (from Platform Window to ImGui) if requested. @@ -10535,7 +10536,7 @@ void ImGui::UpdatePlatformWindows() for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++) { ImGuiViewportP* viewport = g.Viewports[n]; - if (n == 0 || viewport->PlatformWindowCreated) + if (viewport->PlatformWindowCreated) if (g.PlatformIO.Platform_GetWindowFocus(viewport)) focused_viewport = viewport; } From c3f20f6b81cd2fd3be2b9073cba089d7c3093740 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Mar 2019 11:27:30 +0100 Subject: [PATCH 165/566] Viewport: DestroyPlatformWindow() skips calling user function if PlatformWindowCreated is set. + Clarified comment about implicit Debug viewport which may be hogging a viewport. --- imgui.cpp | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4b1b9f77..89b55356 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10446,7 +10446,8 @@ void ImGui::UpdatePlatformWindows() { ImGuiViewportP* viewport = g.Viewports[i]; - // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window (the implicit/fallback Debug window will be registered its viewport then be disabled) + // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window + // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame) bool destroy_platform_window = false; destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1); destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)); @@ -10628,15 +10629,20 @@ static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport) void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport) { ImGuiContext& g = *GImGui; - if (g.PlatformIO.Renderer_DestroyWindow) - g.PlatformIO.Renderer_DestroyWindow(viewport); - if (g.PlatformIO.Platform_DestroyWindow) - g.PlatformIO.Platform_DestroyWindow(viewport); - IM_ASSERT(viewport->RendererUserData == NULL); - IM_ASSERT(viewport->PlatformUserData == NULL); - viewport->PlatformHandle = NULL; - viewport->RendererUserData = viewport->PlatformHandle = NULL; - viewport->PlatformWindowCreated = false; + if (viewport->PlatformWindowCreated) + { + if (g.PlatformIO.Renderer_DestroyWindow) + g.PlatformIO.Renderer_DestroyWindow(viewport); + if (g.PlatformIO.Platform_DestroyWindow) + g.PlatformIO.Platform_DestroyWindow(viewport); + IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL); + viewport->PlatformWindowCreated = false; + } + else + { + IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL); + } + viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL; viewport->ClearRequestFlags(); } From 55c02099c5b4f3d6317a56ada0bca94d77dee0d4 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Mar 2019 11:35:34 +0100 Subject: [PATCH 166/566] Version 1.69, comments, typos --- docs/CHANGELOG.txt | 23 ++++++++++++----------- docs/README.md | 4 ++-- docs/TODO.txt | 2 ++ examples/README.txt | 4 +++- examples/example_allegro5/README.md | 16 +++++++++++++--- examples/imgui_impl_opengl3.cpp | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 11 ++++++++--- 13 files changed, 49 insertions(+), 29 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 31af0bfa..14a18843 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -30,21 +30,22 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.69 (In Progress) + VERSION 1.69 (Released 2019-03-13) ----------------------------------------------------------------------- Breaking Changes: - Renamed ColorEdit/ColorPicker's ImGuiColorEditFlags_RGB/_HSV/_HEX flags to respectively - ImGuiColorEditFlags_DisplayRGB/_DisplayHSV/_DisplayHex. This is anticipation of adding new - flags to ColorEdit/ColorPicker functions which would make those ambiguous. (#2384) [@haldean] + ImGuiColorEditFlags_DisplayRGB/_DisplayHSV/_DisplayHex. This is because the addition of + new flag ImGuiColorEditFlags_InputHSV makes the earlier one ambiguous. + Keep redirection enum values (will obsolete). (#2384) [@haldean] - Renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). (#2391) Other Changes: - Added GetBackgroundDrawList() helper to quickly get access to a ImDrawList that will be rendered - behind every other windows. (#2391) -- DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types. + behind every other windows. (#2391, #545) +- DragScalar, InputScalar, SliderScalar: Added support for u8/s8/u16/s16 data types (ImGuiDataType_S8, etc.) We are reusing function instances of larger types to reduce code size. (#643, #320, #708, #1011) - Added InputTextWithHint() to display a description/hint in the text box when no text has been entered. (#2400) [@Organic-Code, @ocornut] @@ -70,7 +71,7 @@ Other Changes: - ColorEdit: Fixed tooltip not honoring the ImGuiColorEditFlags_NoAlpha contract of never reading the 4th float in the array (value was read and discarded). (#2384) [@haldean] - MenuItem, Selectable: Fixed disabled widget interfering with navigation (fix c2db7f63 in 1.67). -- TabBar: Fixed a crash when using BeginTabBar() recursively (didn't affect docking). (#2371) +- TabBar: Fixed a crash when using many BeginTabBar() recursively (didn't affect docking). (#2371) - TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) - TabBar: Fixed ImGuiTabItemFlags_SetSelected being ignored if the tab is not visible (with @@ -80,12 +81,12 @@ Other Changes: - TabBar: Reworked scrolling policy (when ImGuiTabBarFlags_FittingPolicyScroll is set) to teleport the view when aiming at a tab far away the visible section, and otherwise accelerate the scrolling speed to cap the scrolling time to 0.3 seconds. -- Text: Fixed large Text/TextUnformatted call not declaring its size when starting below the - lower point of the current clipping rectangle. Somehow this bug has been there since v1.0! +- Text: Fixed large Text/TextUnformatted calls not feeding their size into layout when starting + below the lower point of the current clipping rectangle. This bug has been there since v1.0! It was hardly noticeable but would affect the scrolling range, which in turn would affect - some scrolling request functions when called during the opening frame of a window. + some scrolling request functions when called during the appearing frame of a window. - Plot: Fixed divide-by-zero in PlotLines() when passing a count of 1. (#2387) [@Lectem] -- Log/Capture: Fixed extraneous leading carriage return. +- Log/Capture: Fixed LogXXX functions emitting extraneous leading carriage return. - Log/Capture: Fixed an issue when empty string on a new line would not emit a carriage return. - Log/Capture: Fixed LogXXX functions 'auto_open_depth' parameter being treated as an absolute tree depth instead of a relative one. @@ -572,7 +573,7 @@ Other Changes: - InputFloat,InputFloat2,InputFloat3,InputFloat4: Added variations taking a more flexible and consistent optional "const char* format" parameter instead of "int decimal_precision". This allow using custom formats to display values in scientific notation, and is generally more consistent with other API. - Obsoleted functions using the optional "int decimal_precision" parameter. (#648) + Obsoleted functions using the optional "int decimal_precision" parameter. (#648, #712) - DragFloat, DragInt: Cancel mouse tweak when current value is initially past the min/max boundaries and mouse is pushing in the same direction (keyboard/gamepad version already did this). - DragFloat, DragInt: Honor natural type limits (e.g. INT_MAX, FLT_MAX) instead of wrapping around. (#708, #320) diff --git a/docs/README.md b/docs/README.md index 96d3e6d8..88f562db 100644 --- a/docs/README.md +++ b/docs/README.md @@ -305,10 +305,10 @@ Ongoing dear imgui development is financially supported by users and private spo - Media Molecule, Mobigame, Aras Pranckevičius, Greggman, DotEmu, Nadeo, Supercell, Runner, Aiden Koss, Kylotonn. **Salty caramel supporters** -- Recognition Robotics, ikrima, Geoffrey Evans, Mercury Labs, Singularity Demo Group, Lionel Landwerlin, Ron Gilbert, Brandon Townsend, Nikhil Deshpande, Cort Stratton, drudru, Harfang 3D, Jeff Roberts, Rainway inc, Ondra Voves, Mesh Consultants. +- Recognition Robotics, ikrima, Geoffrey Evans, Mercury Labs, Singularity Demo Group, Lionel Landwerlin, Ron Gilbert, Brandon Townsend, Nikhil Deshpande, Cort Stratton, drudru, Harfang 3D, Jeff Roberts, Rainway inc, Ondra Voves, Mesh Consultants, Unit 2 Games. **Caramel supporters** -- Jerome Lanquetot, Daniel Collin, Ctrl Alt Ninja, Neil Henning, Neil Blakey-Milner, Aleksei, NeiloGD, Eric, Game Atelier, Vincent Hamm, Colin Riley, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, Josh Faust, Martin Donlon, Codecat, Doug McNabb, Emmanuel Julien, Guillaume Chereau, Jeffrey Slutter, Jeremiah Deckard, r-lyeh, Nekith, Joshua Fisher, Malte Hoffmann, Mustafa Karaalioglu, Merlyn Morgan-Graham, Per Vognsen, Fabian Giesen, Jan Staubach, Matt Hargett, John Shearer, Jesse Chounard, kingcoopa, Jonas Bernemann, Johan Andersson, Michael Labbe, Tomasz Golebiowski, Louis Schnellbach, Jimmy Andrews, Bojan Endrovski, Robin Berg Pettersen, Rachel Crawford, Andrew Johnson, Sean Hunter, Jordan Mellow, Nefarius Software Solutions, Laura Wieme, Robert Nix, Mick Honey, Steven Kah Hien Wong, Bartosz Bielecki, Oscar Penas, A M, Liam Moynihan, Artometa, Mark Lee, Dimitri Diakopoulos, Pete Goodwin. +- Jerome Lanquetot, Daniel Collin, Ctrl Alt Ninja, Neil Henning, Neil Blakey-Milner, Aleksei, NeiloGD, Eric, Game Atelier, Vincent Hamm, Colin Riley, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, Josh Faust, Martin Donlon, Codecat, Doug McNabb, Emmanuel Julien, Guillaume Chereau, Jeffrey Slutter, Jeremiah Deckard, r-lyeh, Nekith, Joshua Fisher, Malte Hoffmann, Mustafa Karaalioglu, Merlyn Morgan-Graham, Per Vognsen, Fabian Giesen, Jan Staubach, Matt Hargett, John Shearer, Jesse Chounard, kingcoopa, Jonas Bernemann, Johan Andersson, Michael Labbe, Tomasz Golebiowski, Louis Schnellbach, Jimmy Andrews, Bojan Endrovski, Robin Berg Pettersen, Rachel Crawford, Andrew Johnson, Sean Hunter, Jordan Mellow, Nefarius Software Solutions, Laura Wieme, Robert Nix, Mick Honey, Steven Kah Hien Wong, Bartosz Bielecki, Oscar Penas, A M, Liam Moynihan, Artometa, Mark Lee, Dimitri Diakopoulos, Pete Goodwin, Johnathan Roatch, nyu lea, Oswald Hurlem. And all other past and present supporters; THANK YOU! (Please contact me if you would like to be added or removed from this list) diff --git a/docs/TODO.txt b/docs/TODO.txt index 0ede3897..2a25172d 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -59,6 +59,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: alignment options in style (e.g. center Selectable, Right-Align within Button, etc.) #1260 - widgets: activate by identifier (trigger button, focus given id) - widgets: a way to represent "mixed" values, so e.g. all values replaced with **, including check-boxes, colors, etc. with support for multi-components widgets (e.g. SliderFloat3, make only "Y" mixed) + - widgets: selectable: generic BeginSelectable()/EndSelectable() mechanism. + - widgets: selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) diff --git a/examples/README.txt b/examples/README.txt index a058601b..c55dc09b 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,3 +1,5 @@ +----------------------------------------------------------------------- + dear imgui, v1.69 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) @@ -26,7 +28,7 @@ This folder contains two things: They are the in the XXXX_example/ sub-folders. You can find binaries of some of those example applications at: - http://www.miracleworld.net/imgui/binaries + http://www.dearimgui.org/binaries --------------------------------------- diff --git a/examples/example_allegro5/README.md b/examples/example_allegro5/README.md index 1a83fe89..fb58fdbe 100644 --- a/examples/example_allegro5/README.md +++ b/examples/example_allegro5/README.md @@ -1,7 +1,7 @@ # Configuration -Dear ImGui outputs 16-bit vertex indices by default. +Dear ImGui outputs 16-bit vertex indices by default. Allegro doesn't support them natively, so we have two solutions: convert the indices manually in imgui_impl_allegro5.cpp, or compile imgui with 32-bit indices. You can either modify imconfig.h that comes with Dear ImGui (easier), or set a C++ preprocessor option IMGUI_USER_CONFIG to find to a filename. We are providing `imconfig_allegro5.h` that enables 32-bit indices. @@ -9,14 +9,24 @@ Note that the back-end supports _BOTH_ 16-bit and 32-bit indices, but 32-bit ind # How to Build -- On Ubuntu 14.04+ +### On Ubuntu 14.04+ ```bash g++ -DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" -I .. -I ../.. main.cpp ../imgui_impl_allegro5.cpp ../../imgui*.cpp -lallegro -lallegro_primitives -o allegro5_example ``` -- On Windows with Visual Studio's CLI +### On Windows with Visual Studio's CLI +You may install Allegro using vcpkg: +``` +git clone https://github.com/Microsoft/vcpkg +cd vcpkg +.\bootstrap-vcpkg.bat +.\vcpkg install allegro5 +.\vcpkg integrate install ; optional, automatically register include/libs in Visual Studio +``` + +Build: ``` set ALLEGRODIR=path_to_your_allegro5_folder cl /Zi /MD /I %ALLEGRODIR%\include /DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" /I .. /I ..\.. main.cpp ..\imgui_impl_allegro5.cpp ..\..\imgui*.cpp /link /LIBPATH:%ALLEGRODIR%\lib allegro-5.0.10-monolith-md.lib user32.lib diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 01cfa398..84b87775 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -41,7 +41,7 @@ // version version string //---------------------------------------- // 2.0 110 "#version 110" -// 2.1 110 "#version 120" +// 2.1 120 "#version 120" // 3.0 130 "#version 130" // 3.1 140 "#version 140" // 3.2 150 "#version 150" diff --git a/imgui.cpp b/imgui.cpp index 0db2fec9..a1020234 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 WIP +// dear imgui, v1.69 // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index 6616ace3..fdbbb89e 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.69 WIP +// dear imgui, v1.69 // (headers) // See imgui.cpp file for documentation. @@ -45,8 +45,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.69 WIP" -#define IMGUI_VERSION_NUM 16899 +#define IMGUI_VERSION "1.69" +#define IMGUI_VERSION_NUM 16900 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c3e2d1a8..0473d608 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 WIP +// dear imgui, v1.69 // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 203b6f7b..be1604f8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 WIP +// dear imgui, v1.69 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 089ca2e1..9cd39490 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.69 WIP +// dear imgui, v1.69 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b84e2c5d..23411258 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 WIP +// dear imgui, v1.69 // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index 37a095a9..7122e3ad 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,3 +1,7 @@ +dear imgui, v1.69 +(Font Readme) + +--------------------------------------- The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), a 13 pixels high, pixel-perfect font used by default. @@ -5,7 +9,6 @@ We embed it font in source code so you can use Dear ImGui without any file syste You may also load external .TTF/.OTF files. The files in this folder are suggested fonts, provided as a convenience. -(Note: .OTF support in imstb_truetype.h currently doesn't appear to load every font) Fonts are rasterized in a single texture at the time of calling either of io.Fonts->GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build(). Also read dear imgui FAQ in imgui.cpp! @@ -32,7 +35,8 @@ If you have other loading/merging/adding fonts, you can post on the Dear ImGui " README FIRST / FAQ --------------------------------------- -- You can use the style editor ImGui::ShowStyleEditor() to browse your fonts and understand what's going on if you have an issue. +- You can use the style editor ImGui::ShowStyleEditor() in the "Fonts" section to browse your fonts + and understand what's going on if you have an issue. - Make sure your font ranges data are persistent (available during the call to GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build(). - Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.: u8"hello" @@ -201,7 +205,8 @@ For example: for a game where your script is known, if you can feed your entire Compile and use 'binary_to_compressed_c.cpp' to create a compressed C style array that you can embed in source code. See the documentation in binary_to_compressed_c.cpp for instruction on how to use the tool. You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see README). -The tool optionally used Base85 encoding to reduce the size of _source code_ but the read-only arrays will be about 20% bigger. +The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the +actual binary will be about 20% bigger. Then load the font with: ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); From ebe79bbed00a13fd4455f04131b63d49c28ebd5d Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 Mar 2019 15:44:23 +0100 Subject: [PATCH 167/566] Demo: Custom rendering: Minor sizing issue fix. --- imgui_demo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0473d608..b54475db 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4072,7 +4072,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col32); x += spacing + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col32); x += sz; // Pixel (faster than AddLine) 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)); - ImGui::Dummy(ImVec2((sz + spacing) * 8, (sz + spacing) * 3)); + ImGui::Dummy(ImVec2((sz + spacing) * 9.5f, (sz + spacing) * 3)); ImGui::EndTabItem(); } From cf2c52282d4b3dc2e7397aed6e116ddceab20274 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 15 Mar 2019 13:07:30 +0100 Subject: [PATCH 168/566] Version 1.70 WIP --- docs/CHANGELOG.txt | 9 +++++++++ examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 9 files changed, 19 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 14a18843..69de4fd0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -29,6 +29,15 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.70 WIP (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.69 (Released 2019-03-13) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index c55dc09b..97787f47 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.69 + dear imgui, v1.70 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index a1020234..1e4a9d04 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 +// dear imgui, v1.70 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index fdbbb89e..d1d82694 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.69 +// dear imgui, v1.70 WIP // (headers) // See imgui.cpp file for documentation. @@ -45,8 +45,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.69" -#define IMGUI_VERSION_NUM 16900 +#define IMGUI_VERSION "1.70 WIP" +#define IMGUI_VERSION_NUM 16990 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b54475db..ce99dde7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 +// dear imgui, v1.70 WIP // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index be1604f8..a030834a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 +// dear imgui, v1.70 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 9cd39490..c2b546a4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.69 +// dear imgui, v1.70 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 23411258..5949d84d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.69 +// dear imgui, v1.70 WIP // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index 7122e3ad..a9f61cdb 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.69 +dear imgui, v1.70 WIP (Font Readme) --------------------------------------- From ff03ae503bcb694c6adcfdffaa1ece06c200e269 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 15 Mar 2019 13:09:07 +0100 Subject: [PATCH 169/566] Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_opengl3.cpp | 13 ++++++++++--- imgui_demo.cpp | 6 +++--- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 69de4fd0..13dd38ed 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,8 @@ HOW TO UPDATE? Breaking Changes: Other Changes: +- Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized + GL function loaders early, and help users understand what they are missing. (#2421) ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 84b87775..98904363 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-15: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). // 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. @@ -89,11 +90,11 @@ // Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad). // You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. #if defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) -#include +#include // Needs to be initialized with gl3wInit() in user's code #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) -#include +#include // Needs to be initialized with glewInit() in user's code #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) -#include +#include // Needs to be initialized with gladLoadGL() in user's code #else #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM #endif @@ -128,6 +129,12 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) strcpy(g_GlslVersionString, glsl_version); strcat(g_GlslVersionString, "\n"); + // Make a dummy GL call (we don't actually need the result) + // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code. + // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above. + GLint current_texture; + glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤t_texture); + return true; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ce99dde7..c937da48 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2565,9 +2565,9 @@ static void ShowDemoWindowMisc() ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); - ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); } - ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } - ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (0x%X) (%.02f secs)", i, i, io.KeysDownDuration[i]); } + ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } + ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); } From 857381b9ca8e93d3af7627922e776c51eb482763 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 15 Mar 2019 15:03:37 +0100 Subject: [PATCH 170/566] GetMouseDragDelta(): also returns the delta on the mouse button released frame. Verify that mouse positions are valid otherwise returns zero. Removed obsolete comment. Tweaked demo. (#2419) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 7 ++++--- imgui.h | 2 +- imgui_demo.cpp | 23 +++++++++-------------- 4 files changed, 16 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 13dd38ed..f87ae2f3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,8 @@ HOW TO UPDATE? Breaking Changes: Other Changes: +- GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) +- GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) diff --git a/imgui.cpp b/imgui.cpp index 1e4a9d04..98873385 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4206,7 +4206,7 @@ bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID; } -// Return the delta from the initial clicking position. +// Return the delta from the initial clicking position while the mouse button is clicked or was just released. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once. // NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) @@ -4215,9 +4215,10 @@ ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; - if (g.IO.MouseDown[button]) + if (g.IO.MouseDown[button] || g.IO.MouseReleased[button]) if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) - return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). + if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button])) + return g.IO.MousePos - g.IO.MouseClickedPos[button]; return ImVec2(0.0f, 0.0f); } diff --git a/imgui.h b/imgui.h index d1d82694..0e9ebd90 100644 --- a/imgui.h +++ b/imgui.h @@ -662,7 +662,7 @@ namespace ImGui IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse position at the time of opening popup we have BeginPopup() into - IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position. This is locked and return 0.0f until the mouse moves past a distance threshold at least once. If lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once. If lock_threshold < -1.0f uses io.MouseDraggingThreshold. IMGUI_API void ResetMouseDragDelta(int button = 0); // IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c937da48..e698afd4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2646,22 +2646,17 @@ static void ShowDemoWindowMisc() for (int button = 0; button < 3; button++) ImGui::Text("IsMouseDragging(%d):\n w/ default threshold: %d,\n w/ zero threshold: %d\n w/ large threshold: %d", button, ImGui::IsMouseDragging(button), ImGui::IsMouseDragging(button, 0.0f), ImGui::IsMouseDragging(button, 20.0f)); + ImGui::Button("Drag Me"); if (ImGui::IsItemActive()) - { - // Draw a line between the button and the mouse cursor - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - draw_list->PushClipRectFullScreen(); - draw_list->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); - draw_list->PopClipRect(); - - // Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold) - // You can request a lower or higher threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta() - ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); - ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); - ImVec2 mouse_delta = io.MouseDelta; - ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y); - } + ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor + + // Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold) + // You can request a lower or higher threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta() + ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + ImVec2 mouse_delta = io.MouseDelta; + ImGui::Text("GetMouseDragDelta(0):\n w/ default threshold: (%.1f, %.1f),\n w/ zero threshold: (%.1f, %.1f)\nMouseDelta: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y, value_raw.x, value_raw.y, mouse_delta.x, mouse_delta.y); ImGui::TreePop(); } From 7ba774a44025f4a2fcc2513296adc8afaf4cb031 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 15 Mar 2019 15:35:46 +0100 Subject: [PATCH 171/566] Viewports: Fixed being unable to refocus windows when ConfigViewportsNoTaskBarIcon + ConfigViewportsNoDecoration are enabled. (#2420, #1542) [@PathogenDavid] + comments. --- imgui.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4bbb4f4d..3c7ba83d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5611,13 +5611,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update common viewport flags ImGuiViewportFlags viewport_flags = (window->Viewport->Flags) & ~(ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration); + const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; if (flags & ImGuiWindowFlags_Tooltip) viewport_flags |= ImGuiViewportFlags_TopMost; - if (g.IO.ConfigViewportsNoTaskBarIcon || (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0) + if (g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon; - if (g.IO.ConfigViewportsNoDecoration || (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0) + if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window) viewport_flags |= ImGuiViewportFlags_NoDecoration; - if ((viewport_flags & ImGuiViewportFlags_NoDecoration) && (viewport_flags & ImGuiViewportFlags_NoTaskBarIcon)) + + // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them + // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). + // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, + // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere. + if (is_short_lived_floating_window) viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick; // We can overwrite viewport flags using ImGuiWindowClass (advanced users) From 221bf93a557c3ae6f36272fd818c3f0786a49b87 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 Mar 2019 15:48:21 +0100 Subject: [PATCH 172/566] Comments, todo list, remove trailing spaces. --- docs/TODO.txt | 8 +++++++- examples/imgui_impl_freeglut.cpp | 2 ++ examples/imgui_impl_freeglut.h | 2 ++ imgui.cpp | 28 ++++++++++++++-------------- imgui.h | 10 +++++----- imgui_demo.cpp | 2 +- imgui_draw.cpp | 8 ++++---- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 14 +++++++------- 9 files changed, 45 insertions(+), 35 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 2a25172d..801447c9 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -25,7 +25,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window: using SetWindowPos() inside Begin() and moving the window with the mouse reacts a very ugly glitch. We should just defer the SetWindowPos() call. - window: GetWindowSize() returns (0,0) when not calculated? (#1045) - window: investigate better auto-positioning for new windows. - - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. + - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - window/child: the first draw command of a child window could be moved into the current draw command of the parent window (unless child+tooltip?). - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - scrolling: while holding down a scrollbar, try to keep the same contents visible (at least while not moving mouse) @@ -44,6 +44,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - drawlist: callback: add an extra void* in ImDrawCallback to allow passing render-local data to the callback (would break API). - drawlist/opt: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. (#1962) - drawlist/opt: AddRect() axis aligned pixel aligned (no-aa) could use 8 triangles instead of 16 and no normal calculation. + - drawlist/opt: thick AA line could be doable in same number of triangles as 1.0 AA line by storing gradient+full color in atlas. - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. - main: find a way to preserve relative orders of multiple reappearing windows (so an app toggling between "modes" e.g. fullscreen vs all tools) won't lose relative ordering. @@ -306,10 +307,13 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - misc: idle: expose "woken up" boolean (set by inputs) and/or animation time (for cursor blink) for back-end to be able stop refreshing easily. - misc: idle: if cursor blink if the _only_ visible animation, core imgui could rewrite vertex alpha to avoid CPU pass on ImGui:: calls. + - misc: idle: if cursor blink if the _only_ visible animation, could even expose a dirty rectangle that optionally can be leverage by some app to render in a smaller viewport, getting rid of much pixel shading cost. - misc: make the ImGuiCond values linear (non-power-of-two). internal storage for ImGuiWindow can use integers to combine into flags (Why?) - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) - misc: PushItemFlag(): add a flag to disable keyboard capture when used with mouse? (#1682) - misc: use more size_t in public api? + - misc: possible compile-time support for string view/range instead of char* would e.g. facilitate usage with Rust (#683) + - misc: possible compile-time support for wchar_t instead of char*? - backend: bgfx? https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - web/emscriptem: refactor some examples to facilitate integration with emscripten main loop system. (#1713, #336) @@ -325,6 +329,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: provide a zero frame-rate/idle example. - examples: apple: example_apple should be using modern GL3. - examples: glfw: could go idle when minimized? if (glfwGetWindowAttrib(window, GLFW_ICONIFIED)) { glfwWaitEvents(); continue; } // issue: DeltaTime will be super high on resume, perhaps provide a way to let impl know (#440) + - examples: opengl: rename imgui_impl_opengl2 to impl_opengl_legacy and imgui_impl_opengl3 to imgui_impl_opengl? (#1900) + - examples: opengl: could use a single vertex buffer and glBufferSubData for uploads? - optimization: replace vsnprintf with stb_printf? or enable the defines/infrastructure to allow it (#1038) - optimization: add clipping for multi-component widgets (SliderFloatX, ColorEditX, etc.). one problem is that nav branch can't easily clip parent group when there is a move request. - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) diff --git a/examples/imgui_impl_freeglut.cpp b/examples/imgui_impl_freeglut.cpp index 42d56417..a85bc44f 100644 --- a/examples/imgui_impl_freeglut.cpp +++ b/examples/imgui_impl_freeglut.cpp @@ -1,8 +1,10 @@ // dear imgui: Platform Binding for FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) +// GLUT IS OBSOLETE SOFTWARE. AVOID USING GLUT IN 2019. // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I +// [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. diff --git a/examples/imgui_impl_freeglut.h b/examples/imgui_impl_freeglut.h index 909f0725..4adad49f 100644 --- a/examples/imgui_impl_freeglut.h +++ b/examples/imgui_impl_freeglut.h @@ -1,8 +1,10 @@ // dear imgui: Platform Binding for FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) +// GLUT IS OBSOLETE SOFTWARE. AVOID USING GLUT IN 2019. // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I +// [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. diff --git a/imgui.cpp b/imgui.cpp index 98873385..434dda47 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -637,8 +637,8 @@ CODE // Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it: ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height)); - C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTexture / void*, and vice-versa. - Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTexture / void*. + C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa. + Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*. Examples: GLuint my_tex = XXX; @@ -875,7 +875,7 @@ CODE A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags. (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse) Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - - You can call ImGui::GetBackgroundDrawList() or ImGui::GetForegroundDrawList() and use those draw list to display + - You can call ImGui::GetBackgroundDrawList() or ImGui::GetForegroundDrawList() and use those draw list to display contents behind or over every other imgui windows. - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data. @@ -1297,7 +1297,7 @@ int ImStrnicmp(const char* str1, const char* str2, size_t count) void ImStrncpy(char* dst, const char* src, size_t count) { - if (count < 1) + if (count < 1) return; if (count > 1) strncpy(dst, src, count - 1); @@ -1443,7 +1443,7 @@ int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) // CRC32 needs a 1KB lookup table (not cache friendly) // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily: // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe. -static const ImU32 GCrc32LookupTable[256] = +static const ImU32 GCrc32LookupTable[256] = { 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91, 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5, @@ -2850,7 +2850,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) return false; - // Special handling for the dummy item after Begin() which represent the title bar or tab. + // Special handling for the dummy item after Begin() which represent the title bar or tab. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed) return false; @@ -4093,7 +4093,7 @@ int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_ int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate) { ImGuiContext& g = *GImGui; - if (key_index < 0) + if (key_index < 0) return 0; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[key_index]; @@ -4103,7 +4103,7 @@ int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_r bool ImGui::IsKeyPressed(int user_key_index, bool repeat) { ImGuiContext& g = *GImGui; - if (user_key_index < 0) + if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[user_key_index]; @@ -4800,7 +4800,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held) { g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; - if (held) + if (held) *border_held = border_n; } if (held) @@ -7009,7 +7009,7 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla void ImGui::EndPopup() { - ImGuiContext& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls IM_ASSERT(g.BeginPopupStack.Size > 0); @@ -7876,7 +7876,7 @@ static void ImGui::NavUpdate() if (g.NavWindow) { ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow); - if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] + if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } } #endif @@ -8829,7 +8829,7 @@ void ImGui::EndDragDropTarget() //----------------------------------------------------------------------------- // [SECTION] LOGGING/CAPTURING //----------------------------------------------------------------------------- -// All text output from the interface can be captured into tty/file/clipboard. +// All text output from the interface can be captured into tty/file/clipboard. // By default, tree nodes are automatically opened during logging. //----------------------------------------------------------------------------- @@ -8884,7 +8884,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start); else if (g.LogLineFirstItem) LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start); - else + else LogText(" %.*s", char_count, line_start); g.LogLineFirstItem = false; } @@ -8933,7 +8933,7 @@ void ImGui::LogToFile(int auto_open_depth, const char* filename) if (g.LogEnabled) return; - // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still + // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. // By opening the file in binary mode "ab" we have consistent output everywhere. if (!filename) diff --git a/imgui.h b/imgui.h index 0e9ebd90..04a4c0e3 100644 --- a/imgui.h +++ b/imgui.h @@ -363,7 +363,7 @@ namespace ImGui // whereas "str_id" denote a string that is only used as an ID and not normally displayed. IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string). IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). - IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). + IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer). IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer). IMGUI_API void PopID(); // pop from the ID stack. IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself @@ -464,7 +464,7 @@ namespace ImGui IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.) - // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. + // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); @@ -678,7 +678,7 @@ namespace ImGui // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. - IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). + IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. // Memory Allocators @@ -1117,7 +1117,7 @@ enum ImGuiColorEditFlags_ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. - // User Options (right-click on widget to change some of them). + // User Options (right-click on widget to change some of them). ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. @@ -1942,7 +1942,7 @@ struct ImFontConfig int FontNo; // 0 // Index of font within TTF/OTF file float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. - int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. + int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e698afd4..e9e8265b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2646,7 +2646,7 @@ static void ShowDemoWindowMisc() for (int button = 0; button < 3; button++) ImGui::Text("IsMouseDragging(%d):\n w/ default threshold: %d,\n w/ zero threshold: %d\n w/ large threshold: %d", button, ImGui::IsMouseDragging(button), ImGui::IsMouseDragging(button, 0.0f), ImGui::IsMouseDragging(button, 20.0f)); - + ImGui::Button("Drag Me"); if (ImGui::IsItemActive()) ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a030834a..06340c07 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1287,8 +1287,8 @@ void ImDrawData::DeIndexAllBuffers() } } -// Helper to scale the ClipRect field of each ImDrawCmd. -// Use if your final output buffer is at a different scale than draw_data->DisplaySize, +// Helper to scale the ClipRect field of each ImDrawCmd. +// Use if your final output buffer is at a different scale than draw_data->DisplaySize, // or if there is a difference between your window resolution and framebuffer resolution. void ImDrawData::ScaleClipRects(const ImVec2& fb_scale) { @@ -1594,9 +1594,9 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) font_cfg.OversampleH = font_cfg.OversampleV = 1; font_cfg.PixelSnapH = true; } - if (font_cfg.SizePixels <= 0.0f) + if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f * 1.0f; - if (font_cfg.Name[0] == '\0') + if (font_cfg.Name[0] == '\0') ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); diff --git a/imgui_internal.h b/imgui_internal.h index c2b546a4..cf0c7cd6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1349,13 +1349,13 @@ struct ImGuiTabBar bool VisibleTabWasSubmitted; short LastTabItemIdx; // For BeginTabItem()/EndTabItem() ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() - ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. + ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); int GetTabOrder(const ImGuiTabItem* tab) const { return Tabs.index_from_ptr(tab); } - const char* GetTabName(const ImGuiTabItem* tab) const + const char* GetTabName(const ImGuiTabItem* tab) const { - IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size); + IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size); return TabsNames.Buf.Data + tab->NameOffset; } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5949d84d..f457f827 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1611,7 +1611,7 @@ static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; } return; case ImGuiDataType_Double: - if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; } + if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; } if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; } return; case ImGuiDataType_COUNT: break; @@ -3485,9 +3485,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { if (!state->HasSelection()) { - if (is_wordmove_key_down) + if (is_wordmove_key_down) state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); - else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) + else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); } state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); @@ -3791,9 +3791,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; } } line_count++; - if (searches_result_line_no[0] == -1) + if (searches_result_line_no[0] == -1) searches_result_line_no[0] = line_count; - if (searches_result_line_no[1] == -1) + if (searches_result_line_no[1] == -1) searches_result_line_no[1] = line_count; // Calculate 2d position by finding the beginning of the line and measuring distance @@ -5283,7 +5283,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl else { item_add = ItemAdd(bb, id); - } + } if (!item_add) { if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) @@ -5685,7 +5685,7 @@ void ImGuiMenuColumns::Update(int count, float spacing, bool clear) IM_ASSERT(count == IM_ARRAYSIZE(Pos)); Width = NextWidth = 0.0f; Spacing = spacing; - if (clear) + if (clear) memset(NextWidths, 0, sizeof(NextWidths)); for (int i = 0; i < IM_ARRAYSIZE(Pos); i++) { From c7619d4a6afafd38bc0e603c1f883e15522b85cf Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 Mar 2019 16:19:09 +0100 Subject: [PATCH 173/566] Docking: Preserve existing docked nodes when setting the ImGuiDockNodeFlags_NoDockingInCentralNode flag. (#2423, #2109) --- imgui.cpp | 11 +++++++---- imgui.h | 6 +++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3c7ba83d..6ed50ed6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12873,7 +12873,7 @@ void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond) // Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. // The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. -void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class) +void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class) { ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; @@ -12881,18 +12881,19 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags doc if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; + IM_ASSERT((flags & ImGuiDockNodeFlags_Dockspace) == 0); ImGuiDockNode* node = DockContextFindNodeByID(ctx, id); if (!node) { node = DockContextAddNode(ctx, id); node->IsCentralNode = true; } - node->Flags = dockspace_flags; + node->Flags = flags; node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); // When a Dockspace transitioned form implicit to explicit this may be called a second time // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. - if (node->LastFrameActive == g.FrameCount && !(dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly)) + if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly)) { IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID"); node->Flags |= ImGuiDockNodeFlags_Dockspace; @@ -12901,7 +12902,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags doc node->Flags |= ImGuiDockNodeFlags_Dockspace; // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible - if (dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly) + if (flags & ImGuiDockNodeFlags_KeepAliveOnly) { node->LastFrameAlive = g.FrameCount; return; @@ -13421,12 +13422,14 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) g.NextWindowData.PosUndock = false; } +#if 0 // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode)) { DockContextProcessUndockWindow(ctx, window); return; } +#endif // Undock if our dockspace node disappeared // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly. diff --git a/imgui.h b/imgui.h index 95b4a1fc..57cddcb6 100644 --- a/imgui.h +++ b/imgui.h @@ -594,7 +594,7 @@ namespace ImGui // To dock windows: hold SHIFT anywhere while moving windows (if io.ConfigDockingWithShift == true) or drag windows from their title bar (if io.ConfigDockingWithShift = false) // Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details. IMGUI_API void DockSpace(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); - IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags dockspace_flags = 0, const ImGuiWindowClass* window_class = NULL); + IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id (FIXME-DOCK) IMGUI_API void SetNextWindowClass(const ImGuiWindowClass* window_class); // set next window class (rare/advanced uses: provide hints to the platform back-end via altered viewport flags and parent/child info) IMGUI_API ImGuiID GetWindowDockID(); @@ -882,9 +882,9 @@ enum ImGuiDockNodeFlags_ { ImGuiDockNodeFlags_None = 0, ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. - ImGuiDockNodeFlags_NoSplit = 1 << 1, // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion) + ImGuiDockNodeFlags_NoSplit = 1 << 1, // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. //ImGuiDockNodeFlags_NoCentralNode = 1 << 2, // Disable Central Node (the node which can stay empty) - ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 3, // Disable docking inside the Central Node, which will be always kept empty. + ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 3, // Disable docking inside the Central Node, which will be always kept empty. Note: when turned off, existing docked nodes will be preserved. //ImGuiDockNodeFlags_NoLayoutChanges = 1 << 4, // Disable adding/removing nodes interactively. Useful with programatically setup dockspaces. ImGuiDockNodeFlags_NoResize = 1 << 5, // Disable resizing child nodes using the splitter/separators. Useful with programatically setup dockspaces. ImGuiDockNodeFlags_PassthruDockspace = 1 << 6, // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. From 7a5196601e96ccc880ea00e5aed0ef3a786edad2 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 Mar 2019 18:13:24 +0100 Subject: [PATCH 174/566] Docking: BeginDocked() doesn't need to rely on tab bar data (will allow removing tab bar). --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 6ed50ed6..d928b6a7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13475,7 +13475,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) return; // When the window is selected we mark it as visible. - if (node->TabBar && node->TabBar->VisibleTabId == window->ID) + if (node->VisibleWindow == window) window->DockTabIsVisible = true; // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesForResize. From a53c57152b83491a4bcd7fceca9d6cbc887c0c54 Mon Sep 17 00:00:00 2001 From: Gnimuc Date: Sun, 24 Mar 2019 10:32:19 +0800 Subject: [PATCH 175/566] Mention Julia binding in README (#2446) Thank you! --- docs/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/README.md b/docs/README.md index 88f562db..1a70ebf3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -122,6 +122,7 @@ Languages: (third-party bindings) - Haxe/hxcpp: [linc_imgui](https://github.com/Aidan63/linc_imgui) - Java: [jimgui](https://github.com/ice1000/jimgui) - JavaScript: [imgui-js](https://github.com/flyover/imgui-js) +- Julia: [CImGui.jl](https://github.com/Gnimuc/CImGui.jl) - Lua: [LuaJIT-ImGui](https://github.com/sonoro1234/LuaJIT-ImGui), [imgui_lua_bindings](https://github.com/patrickriordan/imgui_lua_bindings) or [lua-ffi-bindings](https://github.com/thenumbernine/lua-ffi-bindings) - Odin: [odin-dear_imgui](https://github.com/ThisDrunkDane/odin-dear_imgui) - Pascal: [imgui-pas](https://github.com/dpethes/imgui-pas) From d9f6ba30351cbbff54db2d0169a46bb603611587 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 25 Mar 2019 15:39:11 +0100 Subject: [PATCH 176/566] IsWindowHovered() made change which should have no effect in master but fix result of IsWindowHovered(ImGuiHoveredFlags_ChildWindows) over multiple viewport in docking branch. (#2432) --- imgui.cpp | 2 +- imgui_demo.cpp | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 434dda47..41c56936 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6016,7 +6016,7 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) } } - if (!IsWindowContentHoverable(g.HoveredRootWindow, flags)) + if (!IsWindowContentHoverable(g.HoveredWindow, flags)) return false; if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e9e8265b..37eacfa3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1594,6 +1594,7 @@ static void ShowDemoWindowWidgets() "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" "IsWindowHovered(_ChildWindows) = %d\n" "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n" + "IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n" "IsWindowHovered(_RootWindow) = %d\n" "IsWindowHovered(_AnyWindow) = %d\n", ImGui::IsWindowHovered(), @@ -1601,6 +1602,7 @@ static void ShowDemoWindowWidgets() ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem), ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows), ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow), + ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup), ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow), ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)); From abb7d7b18a9c9f722e941c84f5c6ed9456b44a9d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 25 Mar 2019 15:50:23 +0100 Subject: [PATCH 177/566] InputText: Simplify read-only code path. --- imgui_widgets.cpp | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f457f827..1f51e07a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3343,28 +3343,24 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560 clear_active_id = true; - // When read-only we always use the live data passed to the function - // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :( - if (is_readonly && state != NULL) - { - const bool will_render_cursor = (g.ActiveId == id) || (user_scroll_active); - const bool will_render_selection = state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || will_render_cursor); - if (will_render_cursor || will_render_selection) - { - const char* buf_end = NULL; - state->TextW.resize(buf_size + 1); - state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); - state->CurLenA = (int)(buf_end - buf); - state->CursorClamp(); - } - } - // Lock the decision of whether we are going to take the path displaying the cursor or selection const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active); - const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); + bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); bool value_changed = false; bool enter_pressed = false; + // When read-only we always use the live data passed to the function + // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :( + if (is_readonly && state != NULL && (render_cursor || render_selection)) + { + const char* buf_end = NULL; + state->TextW.resize(buf_size + 1); + state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); + state->CurLenA = (int)(buf_end - buf); + state->CursorClamp(); + render_selection &= state->HasSelection(); + } + // Select the buffer to render. const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid; const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); From 3d8ea352d1f11e9ae2dc6fe4ff457106bb1f224c Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 25 Mar 2019 16:06:30 +0100 Subject: [PATCH 178/566] InputText: Fixed selection background starts rendering one frame after the cursor movement when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 3 +++ 2 files changed, 5 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f87ae2f3..f1c556a6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,8 @@ HOW TO UPDATE? Breaking Changes: Other Changes: +- InputText: Fixed selection background starts rendering one frame after the cursor movement + when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1f51e07a..f151e119 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3570,6 +3570,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ MemFree(clipboard_filtered); } } + + // Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame. + render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); } // Process callbacks and apply result back to user's buffer. From 1963cc59bedf47f43872f8cc80a9aa5fc8ba40a6 Mon Sep 17 00:00:00 2001 From: Luca Rood Date: Sat, 16 Mar 2019 19:55:42 +0100 Subject: [PATCH 179/566] Implement horizontal scrolling with Shift+Scroll This is standard scrolling behaviour in most applications. --- imgui.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 41c56936..54e6125b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3296,6 +3296,13 @@ void ImGui::UpdateMouseWheel() window->Size *= scale; window->SizeFull *= scale; } + else if (!g.IO.KeyCtrl && g.IO.KeyShift && scroll_allowed) + { + // Mouse wheel horizontal scrolling + float scroll_amount = 5 * scroll_window->CalcFontSize(); + scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetWidth() + scroll_window->WindowPadding.x * 2.0f) * 0.67f); + SetWindowScrollX(scroll_window, scroll_window->Scroll.x - g.IO.MouseWheel * scroll_amount); + } else if (!g.IO.KeyCtrl && scroll_allowed) { // Mouse wheel vertical scrolling From cf1b02e54e9a69a4441308e6a6e541eb3c8f5c87 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 25 Mar 2019 19:40:19 +0100 Subject: [PATCH 180/566] Rearrange code in UpdateMouseWheel(). (#2424, #1463) + Fix old io.FontAllowUserScaling feature (probably should be made obsolete, but until then best fixed) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 68 ++++++++++++++++++++++++---------------------- 2 files changed, 37 insertions(+), 32 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f1c556a6..1f5c1e75 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,7 @@ Other Changes: when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. +- Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) diff --git a/imgui.cpp b/imgui.cpp index 54e6125b..835eda8a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3274,48 +3274,52 @@ void ImGui::UpdateMouseWheel() return; if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f) return; - - // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set). ImGuiWindow* window = g.HoveredWindow; - ImGuiWindow* scroll_window = window; - while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs) && scroll_window->ParentWindow) - scroll_window = scroll_window->ParentWindow; - const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs); - if (g.IO.MouseWheel != 0.0f) + // Zoom / Scale window + // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. + if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) { - if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling) + const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); + const float scale = new_font_scale / window->FontWindowScale; + window->FontWindowScale = new_font_scale; + if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) { - // Zoom / Scale window - const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); - const float scale = new_font_scale / window->FontWindowScale; - window->FontWindowScale = new_font_scale; - const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; - window->Pos += offset; - window->Size *= scale; - window->SizeFull *= scale; + window->Pos = ImFloor(window->Pos + offset); + window->Size = ImFloor(window->Size * scale); + window->SizeFull = ImFloor(window->SizeFull * scale); } - else if (!g.IO.KeyCtrl && g.IO.KeyShift && scroll_allowed) + return; + } + + // Mouse wheel scrolling + // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set). + while ((window->Flags & ImGuiWindowFlags_ChildWindow) && (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs) && window->ParentWindow) + window = window->ParentWindow; + const bool scroll_allowed = !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs); + if (scroll_allowed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f) && !g.IO.KeyCtrl) + { + ImVec2 max_step = (window->ContentsRegionRect.GetSize() + window->WindowPadding * 2.0f) * 0.67f; + + // Vertical Mouse Wheel Scrolling (hold Shift to scroll horizontally) + if (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) { - // Mouse wheel horizontal scrolling - float scroll_amount = 5 * scroll_window->CalcFontSize(); - scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetWidth() + scroll_window->WindowPadding.x * 2.0f) * 0.67f); - SetWindowScrollX(scroll_window, scroll_window->Scroll.x - g.IO.MouseWheel * scroll_amount); + float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step.y)); + SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * scroll_step); } - else if (!g.IO.KeyCtrl && scroll_allowed) + else if (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) { - // Mouse wheel vertical scrolling - float scroll_amount = 5 * scroll_window->CalcFontSize(); - scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f); - SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount); + float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x)); + SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheel * scroll_step); + } + + // Horizontal Mouse Wheel Scrolling (for hardware that supports it) + if (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) + { + float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x)); + SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_step); } - } - if (g.IO.MouseWheelH != 0.0f && scroll_allowed && !g.IO.KeyCtrl) - { - // Mouse wheel horizontal scrolling (for hardware that supports it) - float scroll_amount = scroll_window->CalcFontSize(); - SetWindowScrollX(scroll_window, scroll_window->Scroll.x - g.IO.MouseWheelH * scroll_amount); } } From 20188b19d60e83f7823e57804400817d06edbd46 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Mar 2019 12:14:17 +0100 Subject: [PATCH 181/566] Comments (#2441) + Freeglut fixes (#2430) --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 6 ++---- examples/example_freeglut_opengl2/main.cpp | 4 +++- examples/imgui_impl_freeglut.cpp | 10 ++++++++-- examples/imgui_impl_freeglut.h | 4 +++- imgui.h | 8 ++++---- 6 files changed, 21 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1f5c1e75..e1911d3e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,7 @@ Other Changes: - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) +- Examples: FreeGLUT: Made io.DeltaTime always > 0. (#2430) ----------------------------------------------------------------------- diff --git a/docs/TODO.txt b/docs/TODO.txt index 801447c9..f1774f8c 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -42,11 +42,11 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - drawlist: would be good to be able to deep copy of ImDrawData (we have a deep copy of ImDrawList now). - drawlist: rendering: provide a way for imgui to output to a single/global vertex buffer, re-order indices only at the end of the frame (ref: https://gist.github.com/floooh/10388a0afbe08fce9e617d8aefa7d302) - drawlist: callback: add an extra void* in ImDrawCallback to allow passing render-local data to the callback (would break API). + - drawlist: AddRect vs AddLine position confusing (#2441) - drawlist/opt: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. (#1962) - drawlist/opt: AddRect() axis aligned pixel aligned (no-aa) could use 8 triangles instead of 16 and no normal calculation. - drawlist/opt: thick AA line could be doable in same number of triangles as 1.0 AA line by storing gradient+full color in atlas. - - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. - main: find a way to preserve relative orders of multiple reappearing windows (so an app toggling between "modes" e.g. fullscreen vs all tools) won't lose relative ordering. - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? @@ -55,7 +55,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. (#395) - widgets: clean up widgets internal toward exposing everything and stabilizing imgui_internals.h. - widgets: add visuals for Disabled/ReadOnly mode and expose publicly (#211) - - widgets: add always-allow-overlap mode. + - widgets: add always-allow-overlap mode. This should perhaps be the default. - widgets: start exposing PushItemFlag() and ImGuiItemFlags - widgets: alignment options in style (e.g. center Selectable, Right-Align within Button, etc.) #1260 - widgets: activate by identifier (trigger button, focus given id) @@ -135,8 +135,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tabs: make EndTabBar fail if users doesn't respect BeginTabBar return value, for consistency/future-proofing. - tabs: persistent order/focus in BeginTabBar() api (#261, #351) - - ext: stl-ish friendly extension (imgui_stl.h) that has wrapper for std::string, std::vector etc. - - button: provide a button that looks framed. (?) - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? diff --git a/examples/example_freeglut_opengl2/main.cpp b/examples/example_freeglut_opengl2/main.cpp index 26d548e8..c52dfe2a 100644 --- a/examples/example_freeglut_opengl2/main.cpp +++ b/examples/example_freeglut_opengl2/main.cpp @@ -1,6 +1,8 @@ // dear imgui: standalone example application for FreeGLUT + OpenGL2, using legacy fixed pipeline // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. -// (Using GLUT or FreeGLUT is not recommended unless you really miss the 90's) + +// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! +// !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! #include "imgui.h" #include "../imgui_impl_freeglut.h" diff --git a/examples/imgui_impl_freeglut.cpp b/examples/imgui_impl_freeglut.cpp index a85bc44f..32671a6d 100644 --- a/examples/imgui_impl_freeglut.cpp +++ b/examples/imgui_impl_freeglut.cpp @@ -1,6 +1,8 @@ // dear imgui: Platform Binding for FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) -// GLUT IS OBSOLETE SOFTWARE. AVOID USING GLUT IN 2019. + +// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! +// !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I @@ -13,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-25: Misc: Made io.DeltaTime always above zero. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-03-22: Added FreeGLUT Platform binding. @@ -81,7 +84,10 @@ void ImGui_ImplFreeGLUT_NewFrame() // Setup time step ImGuiIO& io = ImGui::GetIO(); int current_time = glutGet(GLUT_ELAPSED_TIME); - io.DeltaTime = (current_time - g_Time) / 1000.0f; + int delta_time_ms = (current_time - g_Time); + if (delta_time_ms <= 0) + delta_time_ms = 1; + io.DeltaTime = delta_time_ms / 1000.0f; g_Time = current_time; // Start the frame diff --git a/examples/imgui_impl_freeglut.h b/examples/imgui_impl_freeglut.h index 4adad49f..6d565ec6 100644 --- a/examples/imgui_impl_freeglut.h +++ b/examples/imgui_impl_freeglut.h @@ -1,6 +1,8 @@ // dear imgui: Platform Binding for FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) -// GLUT IS OBSOLETE SOFTWARE. AVOID USING GLUT IN 2019. + +// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! +// !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I diff --git a/imgui.h b/imgui.h index 04a4c0e3..4c8ab81d 100644 --- a/imgui.h +++ b/imgui.h @@ -1853,8 +1853,8 @@ struct ImDrawList // Primitives IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round - IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4-bits corresponding to which corner to round + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); @@ -1864,8 +1864,8 @@ struct ImDrawList IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(const 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 AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); - IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = IM_COL32_WHITE); IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All); IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, bool closed, float thickness); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order. From f208fd7ebb55adc0b21c46c3d60309eb47cad95e Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Mar 2019 12:33:58 +0100 Subject: [PATCH 182/566] Docking: Fixed crash with ImGuiDockNodeFlags_AutoHideTabBar flag. (#2423, #2109) --- imgui.cpp | 8 ++++---- imgui_demo.cpp | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8ee79ed4..1abffcc4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11915,17 +11915,17 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) if (host_window && node->Windows.Size > 0) { DockNodeUpdateTabBar(node, host_window); - if (node->TabBar->SelectedTabId) - node->SelectedTabID = node->TabBar->SelectedTabId; } else { node->WantCloseAll = false; node->WantCloseTabID = 0; node->IsFocused = false; - if (node->Windows.Size > 0) - node->SelectedTabID = node->Windows[0]->ID; } + if (node->TabBar && node->TabBar->SelectedTabId) + node->SelectedTabID = node->TabBar->SelectedTabId; + else if (node->Windows.Size > 0) + node->SelectedTabID = node->Windows[0]->ID; // Draw payload drop target if (host_window && node->IsVisible) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ca02f0a3..3de9826f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4241,8 +4241,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) void ShowExampleAppDockSpace(bool* p_open) { static bool opt_fullscreen_persistant = true; - static ImGuiDockNodeFlags opt_flags = ImGuiDockNodeFlags_None; bool opt_fullscreen = opt_fullscreen_persistant; + static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. @@ -4260,7 +4260,7 @@ void ShowExampleAppDockSpace(bool* p_open) } // When using ImGuiDockNodeFlags_PassthruDockspace, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background. - if (opt_flags & ImGuiDockNodeFlags_PassthruDockspace) + if (dockspace_flags & ImGuiDockNodeFlags_PassthruDockspace) window_flags |= ImGuiWindowFlags_NoBackground; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); @@ -4275,7 +4275,7 @@ void ShowExampleAppDockSpace(bool* p_open) if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); - ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), opt_flags); + ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } else { @@ -4290,11 +4290,11 @@ void ShowExampleAppDockSpace(bool* p_open) // which we can't undo at the moment without finer window depth/z control. //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant); - if (ImGui::MenuItem("Flag: NoSplit", "", (opt_flags & ImGuiDockNodeFlags_NoSplit) != 0)) opt_flags ^= ImGuiDockNodeFlags_NoSplit; - if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (opt_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) opt_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; - if (ImGui::MenuItem("Flag: NoResize", "", (opt_flags & ImGuiDockNodeFlags_NoResize) != 0)) opt_flags ^= ImGuiDockNodeFlags_NoResize; - if (ImGui::MenuItem("Flag: PassthruDockspace", "", (opt_flags & ImGuiDockNodeFlags_PassthruDockspace) != 0)) opt_flags ^= ImGuiDockNodeFlags_PassthruDockspace; - if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (opt_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) opt_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; + if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; + if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; + if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoResize; + if (ImGui::MenuItem("Flag: PassthruDockspace", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruDockspace) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_PassthruDockspace; + if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; ImGui::Separator(); if (ImGui::MenuItem("Close DockSpace", NULL, false, p_open != NULL)) *p_open = false; From 26646f2450f32b00fb438e38d027dbc98b5dcc07 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Mar 2019 12:41:50 +0100 Subject: [PATCH 183/566] Docking: Wrapping tab bar creation/destroy to make it easier to debug them. --- imgui.cpp | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1abffcc4..404b91ce 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10791,6 +10791,8 @@ namespace ImGui static void DockNodeUpdate(ImGuiDockNode* node); static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node); static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window); + static void DockNodeAddTabBar(ImGuiDockNode* node); + static void DockNodeRemoveTabBar(ImGuiDockNode* node); static ImGuiID DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar); static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node); static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window); @@ -11231,7 +11233,7 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) if (target_node->Windows.Size > 0 && target_node->TabBar == NULL) { - target_node->TabBar = IM_NEW(ImGuiTabBar)(); + DockNodeAddTabBar(target_node); for (int n = 0; n < target_node->Windows.Size; n++) TabBarAddTab(target_node->TabBar, ImGuiTabItemFlags_None, target_node->Windows[n]); } @@ -11418,7 +11420,7 @@ static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, b { if (node->TabBar == NULL) { - node->TabBar = IM_NEW(ImGuiTabBar)(); + DockNodeAddTabBar(node); node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabID; // Add existing windows @@ -11468,10 +11470,7 @@ static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window TabBarRemoveTab(node->TabBar, window->ID); const int tab_count_threshold_for_tab_bar = node->IsCentralNode ? 1 : 2; if (node->Windows.Size < tab_count_threshold_for_tab_bar) - { - IM_DELETE(node->TabBar); - node->TabBar = NULL; - } + DockNodeRemoveTabBar(node); } if (node->Windows.Size == 0 && !node->IsCentralNode && !node->IsDockSpace() && window->DockId != node->ID) @@ -11541,8 +11540,7 @@ static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* s { if (dst_node->TabBar) dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId; - IM_DELETE(src_node->TabBar); - src_node->TabBar = NULL; + DockNodeRemoveTabBar(src_node); } } @@ -11571,10 +11569,7 @@ static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node) } if (node->TabBar) - { - IM_DELETE(node->TabBar); - node->TabBar = NULL; - } + DockNodeRemoveTabBar(node); } struct ImGuiDockNodeUpdateScanResults @@ -12042,7 +12037,10 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w ImGuiTabBar* tab_bar = node->TabBar; bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden if (tab_bar == NULL) - tab_bar = node->TabBar = IM_NEW(ImGuiTabBar)(); + { + DockNodeAddTabBar(node); + tab_bar = node->TabBar; + } ImGuiID focus_tab_id = 0; node->IsFocused = is_focused; @@ -12209,6 +12207,20 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w } } +static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node) +{ + IM_ASSERT(node->TabBar == NULL); + node->TabBar = IM_NEW(ImGuiTabBar); +} + +static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node) +{ + if (node->TabBar == NULL) + return; + IM_DELETE(node->TabBar); + node->TabBar = NULL; +} + static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window) { if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext) From f20725eada0adbedc5c137cc22a54ce8e11fc929 Mon Sep 17 00:00:00 2001 From: Tom Watson Date: Wed, 13 Mar 2019 10:02:04 -0700 Subject: [PATCH 184/566] Docking: Fixed an issue where windows docked into a node that's part of their dockspace wouldn't recover their order correctly after init. (#2109) (It only worked on floating dock node for the accidental reason that BeginDocked would generally early out on the first frame) --- imgui.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 404b91ce..93f229c3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13507,8 +13507,9 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) else window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! - // Save new dock order only if the tab bar is active - if (node->TabBar) + // Save new dock order only if the tab bar has been visible once. + // This allows multiple windows to be created in the same frame and have their respective dock orders preserved. + if (node->TabBar && node->TabBar->CurrFrameVisible != -1) window->DockOrder = (short)DockNodeGetTabOrder(window); if ((node->WantCloseAll || node->WantCloseTabID == window->ID) && p_open != NULL) From 87883abd864567614b2c8ceb8fac3ea065d5a7b1 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 26 Mar 2019 14:15:56 +0100 Subject: [PATCH 185/566] Docking: Tweak and silencing PVS studio static analyzer (back to zero warnings among our selected ones). --- imgui.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 93f229c3..d3c91537 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11937,14 +11937,14 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) if (node->ChildNodes[1]) DockNodeUpdate(node->ChildNodes[1]); - // End host window - if (beginned_into_host_window) - End(); + // Render outer borders last (after the tab bar) + if (node->IsRootNode()) + RenderOuterBorders(host_window); } - // Render outer borders last (after the tab bar) - if (node->IsRootNode() && host_window) - RenderOuterBorders(host_window); + // End host window + if (beginned_into_host_window) //-V1020 + End(); } // Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. From 04a9ce3a1818aa2b9cf1bb068ef33debbba8f15b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Mar 2019 15:34:02 +0100 Subject: [PATCH 186/566] Docking: Renamed ImGuiDockNodeFlags_PassthruDockspace to ImGuiDockNodeFlags_PassthruCentralNode. + Comments, shallow tweaks. (#2109) --- docs/TODO.txt | 1 - imgui.cpp | 28 ++++++++++++++++------------ imgui.h | 16 ++++++++-------- imgui_demo.cpp | 14 +++++++++----- imgui_internal.h | 12 ++++++------ 5 files changed, 39 insertions(+), 32 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 83795ef3..d227a92a 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -133,7 +133,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - dock: A~ Unreal style document system (requires low-level controls of dockspace serialization fork/copy/delete). this is mostly working but the DockBuilderXXX api are not exposed/finished. - dock: B: when docking outer, perform size locking on neighbors nodes the same way we do it with splitters, so other nodes are not resized. - dock: B~ central node resizing behavior incorrect. - - dock: B~ central node ID retrieval API? - dock: B: changing title font/style per-window is not supported as dock nodes are created in NewFrame. - dock: B- dock node inside its own viewports creates 1 temporary viewport per window on startup before ditching them (doesn't affect the user nor request platform windows to be created, but unnecessary) - dock: B- resize sibling locking behavior may be less desirable if we merged same-axis sibling in a same node level? diff --git a/imgui.cpp b/imgui.cpp index d3c91537..a9fed610 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2605,7 +2605,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) DockNode = DockNodeAsHost = NULL; DockId = 0; - DockTabItemStatusFlags = 0; + DockTabItemStatusFlags = ImGuiItemStatusFlags_None; DockOrder = -1; DockIsActive = DockTabIsVisible = DockTabWantClose = false; } @@ -11343,7 +11343,7 @@ void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) ImGuiDockNode::ImGuiDockNode(ImGuiID id) { ID = id; - Flags = 0; + Flags = ImGuiDockNodeFlags_None; ParentNode = ChildNodes[0] = ChildNodes[1] = NULL; TabBar = NULL; SplitAxis = ImGuiAxis_None; @@ -11613,7 +11613,7 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); // Inherit most flags - ImGuiDockNodeFlags flags_to_inherit = ~0 & ~ImGuiDockNodeFlags_Dockspace; + ImGuiDockNodeFlags flags_to_inherit = ~ImGuiDockNodeFlags_Dockspace; if (node->ParentNode) node->Flags = node->ParentNode->Flags & flags_to_inherit; @@ -11854,9 +11854,9 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) if (g.NavWindow && g.NavWindow->RootWindowDockStop->DockNode && g.NavWindow->RootWindowDockStop->ParentWindow == host_window) node->LastFocusedNodeID = g.NavWindow->RootWindowDockStop->DockNode->ID; - // We need to draw a background if requested by ImGuiDockNodeFlags_PassthruDockspace, but we will only know the correct pos/size after + // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size after // processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! - const bool render_dockspace_bg = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruDockspace) != 0; + const bool render_dockspace_bg = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; if (render_dockspace_bg) { host_window->DrawList->ChannelsSplit(2); @@ -11865,7 +11865,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace const ImGuiDockNode* central_node = node->CentralNode; - const bool central_node_hole = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruDockspace) != 0 && central_node != NULL && central_node->IsEmpty(); + const bool central_node_hole = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty(); bool central_node_hole_register_hit_test_hole = central_node_hole; if (central_node_hole) if (const ImGuiPayload* payload = ImGui::GetDragDropPayload()) @@ -11892,10 +11892,10 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) } // Draw empty node background (currently can only be the Central Node) - if (host_window && node->IsEmpty() && node->IsVisible && !(node->Flags & ImGuiDockNodeFlags_PassthruDockspace)) + if (host_window && node->IsEmpty() && node->IsVisible && !(node->Flags & ImGuiDockNodeFlags_PassthruCentralNode)) host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_DockingEmptyBg)); - // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruDockspace if set. + // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set. if (render_dockspace_bg && node->IsVisible) { host_window->DrawList->ChannelsSetCurrent(0); @@ -12566,6 +12566,7 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node); DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size); + // Flags transfer child_inheritor->IsCentralNode = parent_node->IsCentralNode; child_inheritor->IsHiddenTabBar = parent_node->IsHiddenTabBar; parent_node->IsCentralNode = false; @@ -12599,9 +12600,11 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG DockNodeApplyPosSizeToWindows(parent_node); parent_node->AutorityForPos = parent_node->AutorityForSize = parent_node->AutorityForViewport = ImGuiDataAutority_Auto; parent_node->VisibleWindow = merge_lead_child->VisibleWindow; + parent_node->SizeRef = backup_last_explicit_size; + + // Flags transfer parent_node->IsCentralNode = (child_0 && child_0->IsCentralNode) || (child_1 && child_1->IsCentralNode); parent_node->IsHiddenTabBar = merge_lead_child->IsHiddenTabBar; - parent_node->SizeRef = backup_last_explicit_size; if (child_0) { @@ -12961,7 +12964,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla End(); } -// Tips: Use with ImGuiDockNodeFlags_PassthruDockspace! +// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode! // The limitation with this call is that your window won't have a menu bar. // Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. // So if you want a menu bar you need to repeat this code manually ourselves. As with advanced other Docking API, we may change this function signature. @@ -12977,7 +12980,7 @@ ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags ImGuiWindowFlags host_window_flags = 0; host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; - if (dockspace_flags & ImGuiDockNodeFlags_PassthruDockspace) + if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) host_window_flags |= ImGuiWindowFlags_NoBackground; char label[32]; @@ -14186,6 +14189,7 @@ void ImGui::ShowDockingDebug() { static void NodeDockNode(ImGuiDockNode* node, const char* label) { + ImGuiContext& g = *GImGui; ImGui::SetNextTreeNodeOpen(true, ImGuiCond_Once); bool open; if (node->Windows.Size > 0) @@ -14203,7 +14207,7 @@ void ImGui::ShowDockingDebug() ImGui::BulletText("LastFocusedNodeID: 0x%08X", node->LastFocusedNodeID); ImGui::BulletText("Flags 0x%02X%s%s%s%s", node->Flags, node->IsDockSpace() ? ", IsDockSpace" : "", node->IsCentralNode ? ", IsCentralNode" : "", - (GImGui->FrameCount - node->LastFrameAlive < 2) ? ", IsAlive" : "", (GImGui->FrameCount - node->LastFrameActive < 2) ? ", IsActive" : ""); + (g.FrameCount - node->LastFrameAlive < 2) ? ", IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? ", IsActive" : ""); if (node->ChildNodes[0]) NodeDockNode(node->ChildNodes[0], "Child[0]"); if (node->ChildNodes[1]) diff --git a/imgui.h b/imgui.h index a7aff0ba..123d395d 100644 --- a/imgui.h +++ b/imgui.h @@ -591,7 +591,8 @@ namespace ImGui // Docking // [BETA API] Enable with io.ConfigFlags |= ImGuiConfigFlags_DockingEnable. // Note: you DO NOT need to call DockSpace() to use most Docking facilities! - // To dock windows: hold SHIFT anywhere while moving windows (if io.ConfigDockingWithShift == true) or drag windows from their title bar (if io.ConfigDockingWithShift = false) + // To dock windows: if io.ConfigDockingWithShift == false: drag window from their title bar. + // To dock windows: if io.ConfigDockingWithShift == true: hold SHIFT anywhere while moving windows. // Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details. IMGUI_API void DockSpace(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); @@ -882,13 +883,12 @@ enum ImGuiDockNodeFlags_ { ImGuiDockNodeFlags_None = 0, ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. - ImGuiDockNodeFlags_NoSplit = 1 << 1, // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. - //ImGuiDockNodeFlags_NoCentralNode = 1 << 2, // Disable Central Node (the node which can stay empty) - ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 3, // Disable docking inside the Central Node, which will be always kept empty. Note: when turned off, existing docked nodes will be preserved. - //ImGuiDockNodeFlags_NoLayoutChanges = 1 << 4, // Disable adding/removing nodes interactively. Useful with programatically setup dockspaces. - ImGuiDockNodeFlags_NoResize = 1 << 5, // Disable resizing child nodes using the splitter/separators. Useful with programatically setup dockspaces. - ImGuiDockNodeFlags_PassthruDockspace = 1 << 6, // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. - ImGuiDockNodeFlags_AutoHideTabBar = 1 << 7 // Tab bar will automatically hide when there is a single window in the dock node. + //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Disable Central Node (the node which can stay empty) + ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Disable docking inside the Central Node, which will be always kept empty. Note: when turned off, existing docked nodes will be preserved. + ImGuiDockNodeFlags_NoSplit = 1 << 3, // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. + ImGuiDockNodeFlags_NoResize = 1 << 4, // Disable resizing child nodes using the splitter/separators. Useful with programatically setup dockspaces. + ImGuiDockNodeFlags_PassthruCentralNode = 1 << 5, // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Tab bar will automatically hide when there is a single window in the dock node. }; // Flags for ImGui::IsWindowFocused() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3de9826f..130d6d52 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4259,8 +4259,8 @@ void ShowExampleAppDockSpace(bool* p_open) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } - // When using ImGuiDockNodeFlags_PassthruDockspace, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background. - if (dockspace_flags & ImGuiDockNodeFlags_PassthruDockspace) + // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background and handle the pass-thru hole, so we ask Begin() to not render a background. + if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) window_flags |= ImGuiWindowFlags_NoBackground; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); @@ -4291,9 +4291,9 @@ void ShowExampleAppDockSpace(bool* p_open) //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant); if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; - if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoResize; - if (ImGui::MenuItem("Flag: PassthruDockspace", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruDockspace) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_PassthruDockspace; + if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; + if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; ImGui::Separator(); if (ImGui::MenuItem("Close DockSpace", NULL, false, p_open != NULL)) @@ -4301,7 +4301,11 @@ void ShowExampleAppDockSpace(bool* p_open) ImGui::EndMenu(); } HelpMarker( - "You can _always_ dock _any_ window into another by holding the SHIFT key while moving a window. Try it now!" "\n" + "When docking is enabled, you can ALWAYS dock MOST window into another! Try it now!" "\n\n" + " > if io.ConfigDockingWithShift==false (default):" "\n" + " drag windows from title bar to dock" "\n" + " > if io.ConfigDockingWithShift==true:" "\n" + " drag windows from anywhere and hold Shift to dock" "\n\n" "This demo app has nothing to do with it!" "\n\n" "This demo app only demonstrate the use of ImGui::DockSpace() which allows you to manually create a docking node _within_ another window. This is useful so you can decorate your main application window (e.g. with a menu bar)." "\n\n" "ImGui::DockSpace() comes with one hard constraint: it needs to be submitted _before_ any window which may be docked into it. Therefore, if you use a dock spot as the central point of your application, you'll probably want it to be part of the very first window you are submitting to imgui every frame." "\n\n" diff --git a/imgui_internal.h b/imgui_internal.h index 19128ad5..3c2d8797 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -903,12 +903,12 @@ struct ImGuiDockNode ImGuiDockNode(ImGuiID id); ~ImGuiDockNode(); - bool IsRootNode() const { return ParentNode == NULL; } - bool IsDockSpace() const { return (Flags & ImGuiDockNodeFlags_Dockspace) != 0; } - bool IsSplitNode() const { return ChildNodes[0] != NULL; } - bool IsLeafNode() const { return ChildNodes[0] == NULL; } - bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } - ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } + bool IsRootNode() const { return ParentNode == NULL; } + bool IsDockSpace() const { return (Flags & ImGuiDockNodeFlags_Dockspace) != 0; } + bool IsSplitNode() const { return ChildNodes[0] != NULL; } + bool IsLeafNode() const { return ChildNodes[0] == NULL; } + bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } }; //----------------------------------------------------------------------------- From 8d4b5fef1d2efa88812d79515dd5b1c799379188 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Mar 2019 17:25:39 +0100 Subject: [PATCH 187/566] Renamed ImGuiDockNodeFlags_Dockspace to ImGuiDockNodeFlags_DockSpace for consistency. DockBuilderCopyDockspace() to DockBuilderCopyDockSpace(). Made casing consistent elsewhere. (#2109) --- imgui.cpp | 20 ++++++++++---------- imgui_demo.cpp | 17 +++++++---------- imgui_internal.h | 8 ++++---- 3 files changed, 21 insertions(+), 24 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a9fed610..7c30b218 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11097,7 +11097,7 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc node->SelectedTabID = settings->SelectedTabID; node->SplitAxis = settings->SplitAxis; if (settings->IsDockSpace) - node->Flags |= ImGuiDockNodeFlags_Dockspace; + node->Flags |= ImGuiDockNodeFlags_DockSpace; node->IsCentralNode = settings->IsCentralNode != 0; node->IsHiddenTabBar = settings->IsHiddenTabBar != 0; @@ -11613,7 +11613,7 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); // Inherit most flags - ImGuiDockNodeFlags flags_to_inherit = ~ImGuiDockNodeFlags_Dockspace; + ImGuiDockNodeFlags flags_to_inherit = ~ImGuiDockNodeFlags_DockSpace; if (node->ParentNode) node->Flags = node->ParentNode->Flags & flags_to_inherit; @@ -12897,7 +12897,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; - IM_ASSERT((flags & ImGuiDockNodeFlags_Dockspace) == 0); + IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); ImGuiDockNode* node = DockContextFindNodeByID(ctx, id); if (!node) { @@ -12907,15 +12907,15 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla node->Flags = flags; node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); - // When a Dockspace transitioned form implicit to explicit this may be called a second time + // When a DockSpace transitioned form implicit to explicit this may be called a second time // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly)) { IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID"); - node->Flags |= ImGuiDockNodeFlags_Dockspace; + node->Flags |= ImGuiDockNodeFlags_DockSpace; return; } - node->Flags |= ImGuiDockNodeFlags_Dockspace; + node->Flags |= ImGuiDockNodeFlags_DockSpace; // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible if (flags & ImGuiDockNodeFlags_KeepAliveOnly) @@ -12984,7 +12984,7 @@ ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags host_window_flags |= ImGuiWindowFlags_NoBackground; char label[32]; - ImFormatString(label, IM_ARRAYSIZE(label), "DockspaceViewport_%08X", viewport->ID); + ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); @@ -12992,7 +12992,7 @@ ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags Begin(label, NULL, host_window_flags); PopStyleVar(3); - ImGuiID dockspace_id = GetID("Dockspace"); + ImGuiID dockspace_id = GetID("DockSpace"); DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class); End(); @@ -13059,7 +13059,7 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) { ImGuiContext* ctx = GImGui; ImGuiDockNode* node = NULL; - if (flags & ImGuiDockNodeFlags_Dockspace) + if (flags & ImGuiDockNodeFlags_DockSpace) { DockSpace(id, ImVec2(0, 0), flags | ImGuiDockNodeFlags_KeepAliveOnly); node = DockContextFindNodeByID(ctx, id); @@ -13294,7 +13294,7 @@ void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_ } // FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. -void ImGui::DockBuilderCopyDockspace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs) +void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs) { IM_ASSERT(src_dockspace_id != 0); IM_ASSERT(dst_dockspace_id != 0); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 130d6d52..d2498b73 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4270,11 +4270,11 @@ void ShowExampleAppDockSpace(bool* p_open) if (opt_fullscreen) ImGui::PopStyleVar(2); - // Dockspace + // DockSpace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { - ImGuiID dockspace_id = ImGui::GetID("MyDockspace"); + ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } else @@ -4420,13 +4420,13 @@ void ShowExampleAppDocuments(bool* p_open) { Target_None, Target_Tab, // Create documents as local tab into a local tab bar - Target_DockspaceAndWindow // Create documents as regular windows, and create an embedded dockspace + Target_DockSpaceAndWindow // Create documents as regular windows, and create an embedded dockspace }; static Target opt_target = Target_Tab; static bool opt_reorderable = true; static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_; - // When (opt_target == Target_DockspaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") + // When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") // that we emit gets docked into the same spot as the parent window ("Example: Documents"). // This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab // not visible, which in turn would stop submitting the "Eggplant" window. @@ -4434,7 +4434,7 @@ void ShowExampleAppDocuments(bool* p_open) // Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags_NoDocking. bool window_contents_visible = ImGui::Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar); - if (!window_contents_visible && opt_target != Target_DockspaceAndWindow) + if (!window_contents_visible && opt_target != Target_DockSpaceAndWindow) { ImGui::End(); return; @@ -4486,7 +4486,7 @@ void ShowExampleAppDocuments(bool* p_open) ImGui::PopItemWidth(); bool redock_all = false; if (opt_target == Target_Tab) { ImGui::SameLine(); ImGui::Checkbox("Reorderable Tabs", &opt_reorderable); } - if (opt_target == Target_DockspaceAndWindow) { ImGui::SameLine(); redock_all = ImGui::Button("Redock all"); } + if (opt_target == Target_DockSpaceAndWindow) { ImGui::SameLine(); redock_all = ImGui::Button("Redock all"); } ImGui::Separator(); @@ -4531,7 +4531,7 @@ void ShowExampleAppDocuments(bool* p_open) ImGui::EndTabBar(); } } - else if (opt_target == Target_DockspaceAndWindow) + else if (opt_target == Target_DockSpaceAndWindow) { if (ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_DockingEnable) { @@ -4548,9 +4548,6 @@ void ShowExampleAppDocuments(bool* p_open) if (!doc->Open) continue; - // FIXME-DOCK: SetNextWindowDock() - //ImGuiID default_dock_id = GetDockspaceRootDocumentDockID(); - //ImGuiID default_dock_id = GetDockspacePreferedDocumentDockID(); ImGui::SetNextWindowDockID(dockspace_id, redock_all ? ImGuiCond_Always : ImGuiCond_FirstUseEver); ImGuiWindowFlags window_flags = (doc->Dirty ? ImGuiWindowFlags_UnsavedDocument : 0); bool visible = ImGui::Begin(doc->Name, &doc->Open, window_flags); diff --git a/imgui_internal.h b/imgui_internal.h index 3c2d8797..1bf90ec5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -851,7 +851,7 @@ struct ImGuiTabBarRef enum ImGuiDockNodeFlagsPrivate_ { - ImGuiDockNodeFlags_Dockspace = 1 << 10 + ImGuiDockNodeFlags_DockSpace = 1 << 10 }; enum ImGuiDataAutority_ @@ -904,7 +904,7 @@ struct ImGuiDockNode ImGuiDockNode(ImGuiID id); ~ImGuiDockNode(); bool IsRootNode() const { return ParentNode == NULL; } - bool IsDockSpace() const { return (Flags & ImGuiDockNodeFlags_Dockspace) != 0; } + bool IsDockSpace() const { return (Flags & ImGuiDockNodeFlags_DockSpace) != 0; } bool IsSplitNode() const { return ChildNodes[0] != NULL; } bool IsLeafNode() const { return ChildNodes[0] == NULL; } bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } @@ -1671,14 +1671,14 @@ namespace ImGui IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id); IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id); // Warning: DO NOT HOLD ON ImGuiDockNode* pointer, will be invalided by any split/merge/remove operation. inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; } - IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags = 0); // Use (flags == ImGuiDockNodeFlags_Dockspace) to create a dockspace, otherwise it'll create a floating node. + IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags = 0); // Use (flags == ImGuiDockNodeFlags_DockSpace) to create a dockspace, otherwise it'll create a floating node. IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_persistent_docking_references = true); IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the root. IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_dir, ImGuiID* out_id_other); - IMGUI_API void DockBuilderCopyDockspace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs); + IMGUI_API void DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs); IMGUI_API void DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs); IMGUI_API void DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name); IMGUI_API void DockBuilderFinish(ImGuiID node_id); From 75e3793f4db622b9a75d4973d05d0b69d035cb55 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Mar 2019 17:30:32 +0100 Subject: [PATCH 188/566] Docking: Fix DockBuilderAddNode() not storing flags when creating floating node. --- imgui.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui.cpp b/imgui.cpp index 7c30b218..a149cc49 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13070,6 +13070,7 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) node = DockContextFindNodeByID(ctx, id); if (!node) node = DockContextAddNode(ctx, id); + node->Flags = flags; } node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame. return node->ID; From fd5859ed0453ace718cb210ccd26439c2723dfa6 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Mar 2019 18:48:07 +0100 Subject: [PATCH 189/566] Docking: Separating SharedFlags vs LocalFlags in dock node so settings can be applied to individual nodes. Made _NoResize logic on single node applies as expected. (#2423, #2109) --- imgui.cpp | 63 +++++++++++++++++++++++++++++------------------- imgui.h | 17 +++++++------ imgui_internal.h | 10 +++++--- 3 files changed, 54 insertions(+), 36 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a149cc49..58d91dba 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11097,7 +11097,7 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc node->SelectedTabID = settings->SelectedTabID; node->SplitAxis = settings->SplitAxis; if (settings->IsDockSpace) - node->Flags |= ImGuiDockNodeFlags_DockSpace; + node->LocalFlags |= ImGuiDockNodeFlags_DockSpace; node->IsCentralNode = settings->IsCentralNode != 0; node->IsHiddenTabBar = settings->IsHiddenTabBar != 0; @@ -11343,7 +11343,7 @@ void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) ImGuiDockNode::ImGuiDockNode(ImGuiID id) { ID = id; - Flags = ImGuiDockNodeFlags_None; + SharedFlags = LocalFlags = ImGuiDockNodeFlags_None; ParentNode = ChildNodes[0] = ChildNodes[1] = NULL; TabBar = NULL; SplitAxis = ImGuiAxis_None; @@ -11613,9 +11613,8 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); // Inherit most flags - ImGuiDockNodeFlags flags_to_inherit = ~ImGuiDockNodeFlags_DockSpace; if (node->ParentNode) - node->Flags = node->ParentNode->Flags & flags_to_inherit; + node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; // Recurse into children // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. @@ -11651,7 +11650,8 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod } // Auto-hide tab bar option - if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node->Flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar) + ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); + if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar) node->WantHiddenTabBarToggle = true; node->WantHiddenTabBarUpdate = false; @@ -11856,7 +11856,8 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size after // processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! - const bool render_dockspace_bg = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; + const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); + const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; if (render_dockspace_bg) { host_window->DrawList->ChannelsSplit(2); @@ -11865,7 +11866,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace const ImGuiDockNode* central_node = node->CentralNode; - const bool central_node_hole = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty(); + const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty(); bool central_node_hole_register_hit_test_hole = central_node_hole; if (central_node_hole) if (const ImGuiPayload* payload = ImGui::GetDragDropPayload()) @@ -11892,7 +11893,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) } // Draw empty node background (currently can only be the Central Node) - if (host_window && node->IsEmpty() && node->IsVisible && !(node->Flags & ImGuiDockNodeFlags_PassthruCentralNode)) + if (host_window && node->IsEmpty() && node->IsVisible && !(node_flags & ImGuiDockNodeFlags_PassthruCentralNode)) host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_DockingEmptyBg)); // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set. @@ -12369,15 +12370,16 @@ static bool ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNo data->FutureNode.Size = host_node ? ref_node_for_rect->Size : host_window->Size; // Figure out here we are allowed to dock + ImGuiDockNodeFlags host_node_flags = host_node ? host_node->GetMergedFlags() : 0; const bool src_is_visibly_splitted = root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode() && (root_payload->DockNodeAsHost->OnlyNodeWithWindows == NULL); data->IsCenterAvailable = !is_outer_docking; if (src_is_visibly_splitted && (!host_node || !host_node->IsEmpty())) data->IsCenterAvailable = false; - if (host_node && (host_node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode) + if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode) data->IsCenterAvailable = false; data->IsSidesAvailable = true; - if ((host_node && (host_node->Flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) + if ((host_node && (host_node_flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) data->IsSidesAvailable = false; if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode) data->IsSidesAvailable = false; @@ -12528,7 +12530,7 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock } // Stop after ImGuiDir_None - if ((host_node && (host_node->Flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) + if ((host_node && (host_node->GetMergedFlags() & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) return; } } @@ -12567,8 +12569,12 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size); // Flags transfer + child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; + child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_; child_inheritor->IsCentralNode = parent_node->IsCentralNode; child_inheritor->IsHiddenTabBar = parent_node->IsHiddenTabBar; + parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; parent_node->IsCentralNode = false; } @@ -12603,6 +12609,7 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG parent_node->SizeRef = backup_last_explicit_size; // Flags transfer + parent_node->LocalFlags = ((child_0 ? child_0->LocalFlags : 0) | (child_1 ? child_1->LocalFlags : 0)) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; parent_node->IsCentralNode = (child_0 && child_0->IsCentralNode) || (child_1 && child_1->IsCentralNode); parent_node->IsHiddenTabBar = merge_lead_child->IsHiddenTabBar; @@ -12719,7 +12726,7 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) bb.Max[axis ^ 1] += child_1->Size[axis ^ 1]; //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)); - if (node->Flags & ImGuiDockNodeFlags_NoResize) + if ((child_0->GetMergedFlags() | child_1->GetMergedFlags()) & ImGuiDockNodeFlags_NoResize) { ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding); @@ -12904,7 +12911,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla node = DockContextAddNode(ctx, id); node->IsCentralNode = true; } - node->Flags = flags; + node->SharedFlags = flags; node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); // When a DockSpace transitioned form implicit to explicit this may be called a second time @@ -12912,10 +12919,10 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly)) { IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID"); - node->Flags |= ImGuiDockNodeFlags_DockSpace; + node->LocalFlags |= ImGuiDockNodeFlags_DockSpace; return; } - node->Flags |= ImGuiDockNodeFlags_DockSpace; + node->LocalFlags |= ImGuiDockNodeFlags_DockSpace; // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible if (flags & ImGuiDockNodeFlags_KeepAliveOnly) @@ -13061,7 +13068,7 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) ImGuiDockNode* node = NULL; if (flags & ImGuiDockNodeFlags_DockSpace) { - DockSpace(id, ImVec2(0, 0), flags | ImGuiDockNodeFlags_KeepAliveOnly); + DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly); node = DockContextFindNodeByID(ctx, id); } else @@ -13070,7 +13077,7 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) node = DockContextFindNodeByID(ctx, id); if (!node) node = DockContextAddNode(ctx, id); - node->Flags = flags; + node->LocalFlags = flags; } node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame. return node->ID; @@ -13097,7 +13104,7 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL; if (root_id && root_node == NULL) return; - bool has_document_root = false; + bool has_central_node = false; ImGuiDataAutority backup_root_node_autority_for_pos = root_node ? root_node->AutorityForPos : ImGuiDataAutority_Auto; ImGuiDataAutority backup_root_node_autority_for_size = root_node ? root_node->AutorityForSize : ImGuiDataAutority_Auto; @@ -13111,7 +13118,7 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) if (want_removal) { if (node->IsCentralNode) - has_document_root = true; + has_central_node = true; if (root_id != 0) DockContextQueueNotifyRemovedNode(ctx, node); if (root_node) @@ -13149,7 +13156,7 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) dc->Nodes.Clear(); dc->Requests.clear(); } - else if (has_document_root) + else if (has_central_node) { root_node->IsCentralNode = true; } @@ -13227,7 +13234,8 @@ static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID ds { ImGuiContext* ctx = GImGui; ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx, dst_node_id_if_known); - dst_node->Flags = src_node->Flags; + dst_node->SharedFlags = src_node->SharedFlags; + dst_node->LocalFlags = src_node->LocalFlags; dst_node->Pos = src_node->Pos; dst_node->Size = src_node->Size; dst_node->SizeRef = src_node->SizeRef; @@ -13488,7 +13496,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos() window->DockIsActive = true; window->DockTabIsVisible = false; - if (node->Flags & ImGuiDockNodeFlags_KeepAliveOnly) + if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly) return; // When the window is selected we mark it as visible. @@ -14206,9 +14214,14 @@ void ImGui::ShowDockingDebug() ImGui::BulletText("VisibleWindow: 0x%08X %s", node->VisibleWindow ? node->VisibleWindow->ID : 0, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); ImGui::BulletText("SelectedTabID: 0x%08X", node->SelectedTabID); ImGui::BulletText("LastFocusedNodeID: 0x%08X", node->LastFocusedNodeID); - ImGui::BulletText("Flags 0x%02X%s%s%s%s", - node->Flags, node->IsDockSpace() ? ", IsDockSpace" : "", node->IsCentralNode ? ", IsCentralNode" : "", - (g.FrameCount - node->LastFrameAlive < 2) ? ", IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? ", IsActive" : ""); + if (ImGui::TreeNode("flags", "SharedFlags 0x%03X NodeFlags 0x%03X%s%s%s%s", + node->SharedFlags, node->LocalFlags, node->IsDockSpace() ? ", IsDockSpace" : "", node->IsCentralNode ? ", IsCentralNode" : "", + (g.FrameCount - node->LastFrameAlive < 2) ? ", IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? ", IsActive" : "")) + { + ImGui::CheckboxFlags("NodeFlags: NoSplit", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); + ImGui::CheckboxFlags("NodeFlags: NoResize", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::TreePop(); + } if (node->ChildNodes[0]) NodeDockNode(node->ChildNodes[0], "Child[0]"); if (node->ChildNodes[1]) diff --git a/imgui.h b/imgui.h index 123d395d..fb483c27 100644 --- a/imgui.h +++ b/imgui.h @@ -878,17 +878,18 @@ enum ImGuiTabItemFlags_ ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() }; -// Flags for ImGui::DockSpace(), inherited by child nodes. +// Flags for ImGui::DockSpace(), shared/inherited by child nodes. +// (Some flags can be applied to individual nodes directly) enum ImGuiDockNodeFlags_ { ImGuiDockNodeFlags_None = 0, - ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. - //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Disable Central Node (the node which can stay empty) - ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Disable docking inside the Central Node, which will be always kept empty. Note: when turned off, existing docked nodes will be preserved. - ImGuiDockNodeFlags_NoSplit = 1 << 3, // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. - ImGuiDockNodeFlags_NoResize = 1 << 4, // Disable resizing child nodes using the splitter/separators. Useful with programatically setup dockspaces. - ImGuiDockNodeFlags_PassthruCentralNode = 1 << 5, // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. - ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Tab bar will automatically hide when there is a single window in the dock node. + ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Shared // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Shared // Disable Central Node (the node which can stay empty) + ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Shared // Disable docking inside the Central Node, which will be always kept empty. + ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // Shared // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + ImGuiDockNodeFlags_NoSplit = 1 << 4, // Shared/Local // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. + ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing child nodes using the splitter/separators. Useful with programatically setup dockspaces. + ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Shared/Local // Tab bar will automatically hide when there is a single window in the dock node. }; // Flags for ImGui::IsWindowFocused() diff --git a/imgui_internal.h b/imgui_internal.h index 1bf90ec5..3ff3a688 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -851,7 +851,9 @@ struct ImGuiTabBarRef enum ImGuiDockNodeFlagsPrivate_ { - ImGuiDockNodeFlags_DockSpace = 1 << 10 + ImGuiDockNodeFlags_DockSpace = 1 << 10, // Local // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, + ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar // When splitting those flags are moved to the inheriting child, never duplicated }; enum ImGuiDataAutority_ @@ -865,7 +867,8 @@ enum ImGuiDataAutority_ struct ImGuiDockNode { ImGuiID ID; - ImGuiDockNodeFlags Flags; + ImGuiDockNodeFlags SharedFlags; // Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node) + ImGuiDockNodeFlags LocalFlags; // Flags specific to this node ImGuiDockNode* ParentNode; ImGuiDockNode* ChildNodes[2]; // [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array. ImVector Windows; // Note: unordered list! Iterate TabBar->Tabs for user-order. @@ -904,10 +907,11 @@ struct ImGuiDockNode ImGuiDockNode(ImGuiID id); ~ImGuiDockNode(); bool IsRootNode() const { return ParentNode == NULL; } - bool IsDockSpace() const { return (Flags & ImGuiDockNodeFlags_DockSpace) != 0; } + bool IsDockSpace() const { return (LocalFlags & ImGuiDockNodeFlags_DockSpace) != 0; } bool IsSplitNode() const { return ChildNodes[0] != NULL; } bool IsLeafNode() const { return ChildNodes[0] == NULL; } bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } + ImGuiDockNodeFlags GetMergedFlags() const { return SharedFlags | LocalFlags; } ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } }; From fc95da8aa3e96a191a471027a8b01a674bd56076 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Mar 2019 20:32:44 +0100 Subject: [PATCH 190/566] Docking: Internals: Moved CentralNode and HiddenTabBar state into LocalFlags for consistency. (#2423, #2109) --- imgui.cpp | 90 +++++++++++++++++++++++------------------------- imgui_internal.h | 10 ++++-- 2 files changed, 51 insertions(+), 49 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 58d91dba..e18d69fd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5815,7 +5815,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } // Docking: Unhide tab bar - if (window->DockNode && window->DockNode->IsHiddenTabBar) + if (window->DockNode && window->DockNode->IsHiddenTabBar()) { float unhide_sz_draw = ImFloor(g.FontSize * 0.70f); float unhide_sz_hit = ImFloor(g.FontSize * 0.55f); @@ -11098,8 +11098,10 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc node->SplitAxis = settings->SplitAxis; if (settings->IsDockSpace) node->LocalFlags |= ImGuiDockNodeFlags_DockSpace; - node->IsCentralNode = settings->IsCentralNode != 0; - node->IsHiddenTabBar = settings->IsHiddenTabBar != 0; + if (settings->IsCentralNode) + node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; + if (settings->IsHiddenTabBar) + node->LocalFlags |= ImGuiDockNodeFlags_HiddenTabBar; // Bind host window immediately if it already exist (in case of a rebuild) // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set. @@ -11198,7 +11200,7 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) if (target_node) IM_ASSERT(target_node->LastFrameAlive <= g.FrameCount); if (target_node && target_window && target_node == target_window->DockNodeAsHost) - IM_ASSERT(target_node->Windows.Size > 0 || target_node->IsSplitNode() || target_node->IsCentralNode); + IM_ASSERT(target_node->Windows.Size > 0 || target_node->IsSplitNode() || target_node->IsCentralNode()); // Create new node and add existing window to it if (target_node == NULL) @@ -11226,7 +11228,7 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) new_node->HostWindow = target_node->HostWindow; target_node = new_node; } - target_node->IsHiddenTabBar = false; + target_node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar; if (target_node != payload_node) { @@ -11256,13 +11258,14 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) DockNodeMoveWindows(visible_node, target_node); DockSettingsRenameNodeReferences(target_node->ID, visible_node->ID); } - if (target_node->IsCentralNode) + if (target_node->IsCentralNode()) { // Central node property needs to be moved to a leaf node, pick the last focused one. + // FIXME-DOCKING: If we had to transfer other flags here, what would the policy be? ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeID); IM_ASSERT(last_focused_node != NULL && DockNodeGetRootNode(last_focused_node) == DockNodeGetRootNode(payload_node)); - last_focused_node->IsCentralNode = true; - target_node->IsCentralNode = false; + last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; + target_node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode; } IM_ASSERT(target_node->Windows.Size == 0); @@ -11311,7 +11314,7 @@ void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) IM_ASSERT(node->IsLeafNode()); IM_ASSERT(node->Windows.Size >= 1); - if (node->IsRootNode() || node->IsCentralNode) + if (node->IsRootNode() || node->IsCentralNode()) { // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. ImGuiDockNode* new_node = DockContextAddNode(ctx, 0); @@ -11357,7 +11360,7 @@ ImGuiDockNode::ImGuiDockNode(ImGuiID id) AutorityForPos = AutorityForSize = ImGuiDataAutority_DockNode; AutorityForViewport = ImGuiDataAutority_Auto; IsVisible = true; - IsFocused = IsCentralNode = IsHiddenTabBar = HasCloseButton = HasCollapseButton = false; + IsFocused = HasCloseButton = HasCollapseButton = false; WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; } @@ -11468,19 +11471,19 @@ static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window if (node->TabBar) { TabBarRemoveTab(node->TabBar, window->ID); - const int tab_count_threshold_for_tab_bar = node->IsCentralNode ? 1 : 2; + const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2; if (node->Windows.Size < tab_count_threshold_for_tab_bar) DockNodeRemoveTabBar(node); } - if (node->Windows.Size == 0 && !node->IsCentralNode && !node->IsDockSpace() && window->DockId != node->ID) + if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID) { // Automatic dock node delete themselves if they are not holding at least one tab DockContextRemoveNode(&g, node, true); return; } - if (node->Windows.Size == 1 && !node->IsCentralNode && node->HostWindow) + if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow) { ImGuiWindow* remaining_window = node->Windows[0]; if (node->HostWindow->ViewportOwned && node->IsRootNode()) @@ -11590,7 +11593,7 @@ static void DockNodeUpdateScanRec(ImGuiDockNode* node, ImGuiDockNodeUpdateScanRe results->FirstNodeWithWindows = node; results->CountNodesWithWindows++; } - if (node->IsCentralNode) + if (node->IsCentralNode()) { IM_ASSERT(results->CentralNode == NULL); // Should be only one IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this."); @@ -11639,7 +11642,7 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod if (!remove) continue; window->DockTabWantClose = false; - if (node->Windows.Size == 1 && !node->IsCentralNode) + if (node->Windows.Size == 1 && !node->IsCentralNode()) { DockNodeHideHostWindow(node); DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return @@ -11651,15 +11654,15 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod // Auto-hide tab bar option ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); - if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar) + if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar()) node->WantHiddenTabBarToggle = true; node->WantHiddenTabBarUpdate = false; // Apply toggles at a single point of the frame (here!) if (node->Windows.Size > 1) - node->IsHiddenTabBar = false; + node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar; else if (node->WantHiddenTabBarToggle) - node->IsHiddenTabBar ^= 1; + node->LocalFlags ^= ImGuiDockNodeFlags_HiddenTabBar; node->WantHiddenTabBarToggle = false; DockNodeUpdateVisibleFlag(node); @@ -11668,7 +11671,7 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node) { // Update visibility flag - bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode; + bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode(); is_visible |= (node->Windows.Size > 0); is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible); is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible); @@ -11968,7 +11971,7 @@ static ImGuiID ImGui::DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar node->IsFocused = true; if (tab_bar->Tabs.Size == 1) { - if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar)) + if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar())) node->WantHiddenTabBarToggle = true; } else @@ -12008,7 +12011,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w is_focused = true; // Hidden tab bar will show a triangle on the upper-left (in Begin) - if (node->IsHiddenTabBar) + if (node->IsHiddenTabBar()) { node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL; node->IsFocused = is_focused; @@ -12375,13 +12378,13 @@ static bool ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNo data->IsCenterAvailable = !is_outer_docking; if (src_is_visibly_splitted && (!host_node || !host_node->IsEmpty())) data->IsCenterAvailable = false; - if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode) + if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode()) data->IsCenterAvailable = false; data->IsSidesAvailable = true; if ((host_node && (host_node_flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) data->IsSidesAvailable = false; - if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode) + if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode()) data->IsSidesAvailable = false; // Calculate drop shapes geometry for allowed splitting directions @@ -12470,7 +12473,7 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock ImVec2 tab_pos = tab_bar_rect.Min; if (host_node && host_node->TabBar) { - if (!host_node->IsHiddenTabBar) + if (!host_node->IsHiddenTabBar()) tab_pos.x += host_node->TabBar->OffsetMax + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. else tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x; @@ -12572,10 +12575,7 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_; - child_inheritor->IsCentralNode = parent_node->IsCentralNode; - child_inheritor->IsHiddenTabBar = parent_node->IsHiddenTabBar; parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; - parent_node->IsCentralNode = false; } void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child) @@ -12610,8 +12610,6 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG // Flags transfer parent_node->LocalFlags = ((child_0 ? child_0->LocalFlags : 0) | (child_1 ? child_1->LocalFlags : 0)) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; - parent_node->IsCentralNode = (child_0 && child_0->IsCentralNode) || (child_1 && child_1->IsCentralNode); - parent_node->IsHiddenTabBar = merge_lead_child->IsHiddenTabBar; if (child_0) { @@ -12665,12 +12663,12 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si } // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node - else if (child_1->IsCentralNode && child_0->SizeRef[axis] != 0.0f) + else if (child_1->IsCentralNode() && child_0->SizeRef[axis] != 0.0f) { child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]); child_1_size[axis] = (size_avail - child_0_size[axis]); } - else if (child_0->IsCentralNode && child_1->SizeRef[axis] != 0.0f) + else if (child_0->IsCentralNode() && child_1->SizeRef[axis] != 0.0f) { child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]); child_0_size[axis] = (size_avail - child_1_size[axis]); @@ -12909,7 +12907,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla if (!node) { node = DockContextAddNode(ctx, id); - node->IsCentralNode = true; + node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; } node->SharedFlags = flags; node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); @@ -13091,8 +13089,8 @@ void ImGui::DockBuilderRemoveNode(ImGuiID node_id) return; DockBuilderRemoveNodeDockedWindows(node_id, true); DockBuilderRemoveNodeChildNodes(node_id); - if (node->IsCentralNode && node->ParentNode) - node->ParentNode->IsCentralNode = true; + if (node->IsCentralNode() && node->ParentNode) + node->ParentNode->LocalFlags = ImGuiDockNodeFlags_CentralNode; DockContextRemoveNode(ctx, node, true); } @@ -13117,7 +13115,7 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id); if (want_removal) { - if (node->IsCentralNode) + if (node->IsCentralNode()) has_central_node = true; if (root_id != 0) DockContextQueueNotifyRemovedNode(ctx, node); @@ -13158,7 +13156,7 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) } else if (has_central_node) { - root_node->IsCentralNode = true; + root_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; } } @@ -13240,7 +13238,6 @@ static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID ds dst_node->Size = src_node->Size; dst_node->SizeRef = src_node->SizeRef; dst_node->SplitAxis = src_node->SplitAxis; - dst_node->IsCentralNode = src_node->IsCentralNode; out_node_remap_pairs->push_back(src_node->ID); out_node_remap_pairs->push_back(dst_node->ID); @@ -13514,7 +13511,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) // Update window flag IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0); window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize; - if (node->IsHiddenTabBar) + if (node->IsHiddenTabBar()) window->Flags |= ImGuiWindowFlags_NoTitleBar; else window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! @@ -13580,7 +13577,7 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) else allow_null_target_node = true; // Dock into a regular window - const ImRect explicit_target_rect = (target_node && target_node->TabBar && !target_node->IsHiddenTabBar) ? target_node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); + const ImRect explicit_target_rect = (target_node && target_node->TabBar && !target_node->IsHiddenTabBar()) ? target_node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); // Preview docking request and find out split direction/ratio @@ -13590,7 +13587,7 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) { ImGuiDockPreviewData split_inner, split_outer; ImGuiDockPreviewData* split_data = &split_inner; - if (target_node && (target_node->ParentNode || target_node->IsCentralNode)) + if (target_node && (target_node->ParentNode || target_node->IsCentralNode())) if (ImGuiDockNode* root_node = DockNodeGetRootNode(target_node)) if (DockNodePreviewDockCalc(window, root_node, payload_window, &split_outer, is_explicit_target, true)) split_data = &split_outer; @@ -13714,8 +13711,8 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None; node_settings.Depth = (char)depth; node_settings.IsDockSpace = (char)node->IsDockSpace(); - node_settings.IsCentralNode = (char)node->IsCentralNode; - node_settings.IsHiddenTabBar = (char)node->IsHiddenTabBar; + node_settings.IsCentralNode = (char)node->IsCentralNode(); + node_settings.IsHiddenTabBar = (char)node->IsHiddenTabBar(); node_settings.Pos = ImVec2ih((short)node->Pos.x, (short)node->Pos.y); node_settings.Size = ImVec2ih((short)node->Size.x, (short)node->Size.y); node_settings.SizeRef = ImVec2ih((short)node->SizeRef.x, (short)node->SizeRef.y); @@ -14215,11 +14212,12 @@ void ImGui::ShowDockingDebug() ImGui::BulletText("SelectedTabID: 0x%08X", node->SelectedTabID); ImGui::BulletText("LastFocusedNodeID: 0x%08X", node->LastFocusedNodeID); if (ImGui::TreeNode("flags", "SharedFlags 0x%03X NodeFlags 0x%03X%s%s%s%s", - node->SharedFlags, node->LocalFlags, node->IsDockSpace() ? ", IsDockSpace" : "", node->IsCentralNode ? ", IsCentralNode" : "", + node->SharedFlags, node->LocalFlags, node->IsDockSpace() ? ", IsDockSpace" : "", node->IsCentralNode() ? ", IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? ", IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? ", IsActive" : "")) { - ImGui::CheckboxFlags("NodeFlags: NoSplit", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); - ImGui::CheckboxFlags("NodeFlags: NoResize", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("LocalFlags: NoSplit", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); + ImGui::CheckboxFlags("LocalFlags: NoResize", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("LocalFlags: HiddenTabBar",(unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); ImGui::TreePop(); } if (node->ChildNodes[0]) @@ -14327,7 +14325,7 @@ void ImGui::ShowDockingDebug() char buf[64] = ""; char* p = buf; ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); - p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode ? " *CentralNode*" : ""); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); int depth = DockNodeGetDepth(node); diff --git a/imgui_internal.h b/imgui_internal.h index 3ff3a688..1ed273cc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -851,9 +851,13 @@ struct ImGuiTabBarRef enum ImGuiDockNodeFlagsPrivate_ { + // [Internal] ImGuiDockNodeFlags_DockSpace = 1 << 10, // Local // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + ImGuiDockNodeFlags_CentralNode = 1 << 11, // Local + ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Local // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, - ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar // When splitting those flags are moved to the inheriting child, never duplicated + ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_HiddenTabBar, + ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace // When splitting those flags are moved to the inheriting child, never duplicated }; enum ImGuiDataAutority_ @@ -894,8 +898,6 @@ struct ImGuiDockNode ImGuiDataAutority AutorityForViewport :3; bool IsVisible :1; // Set to false when the node is hidden (usually disabled as it has no active window) bool IsFocused :1; - bool IsCentralNode :1; - bool IsHiddenTabBar :1; bool HasCloseButton :1; bool HasCollapseButton :1; bool WantCloseAll :1; // Set when closing all tabs at once. @@ -908,6 +910,8 @@ struct ImGuiDockNode ~ImGuiDockNode(); bool IsRootNode() const { return ParentNode == NULL; } bool IsDockSpace() const { return (LocalFlags & ImGuiDockNodeFlags_DockSpace) != 0; } + bool IsCentralNode() const { return (LocalFlags & ImGuiDockNodeFlags_CentralNode) != 0; } + bool IsHiddenTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } bool IsSplitNode() const { return ChildNodes[0] != NULL; } bool IsLeafNode() const { return ChildNodes[0] == NULL; } bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } From 5a665e423c5a6dd4d7a327f1a85eaca299d343ef Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 27 Mar 2019 20:44:49 +0100 Subject: [PATCH 191/566] Docking: Added ImGuiDockNodeFlags_NoTabBar (not exposed publicly). (#2423, #2109) --- imgui.cpp | 28 ++++++++++++++++------------ imgui_internal.h | 6 ++++-- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e18d69fd..5a86f8f1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5814,8 +5814,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } - // Docking: Unhide tab bar - if (window->DockNode && window->DockNode->IsHiddenTabBar()) + // Docking: Unhide tab bar (small triangle in the corner) + if (window->DockNode && window->DockNode->IsHiddenTabBar() && !window->DockNode->IsNoTabBar()) { float unhide_sz_draw = ImFloor(g.FontSize * 0.70f); float unhide_sz_hit = ImFloor(g.FontSize * 0.55f); @@ -11247,7 +11247,7 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) { if (target_node->Windows.Size > 0) { - // We can dock into a node that already has windows _only_ if our payload is a node tree with a single visible node. + // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. // In this situation, we move the windows of the target node into the currently visible node of the payload. // This allows us to preserve some of the underlying dock tree settings nicely. IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockCalc() early on and never submitted. @@ -11725,6 +11725,10 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) } } + // Remove tab bar if not needed + if (node->TabBar && node->IsNoTabBar()) + DockNodeRemoveTabBar(node); + // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) if (node->Windows.Size <= 1 && node->IsRootNode() && node->IsLeafNode() && !node->IsDockSpace() && !g.IO.ConfigDockingTabBarOnSingleWindows) { @@ -12011,7 +12015,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w is_focused = true; // Hidden tab bar will show a triangle on the upper-left (in Begin) - if (node->IsHiddenTabBar()) + if (node->IsHiddenTabBar() || node->IsNoTabBar()) { node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL; node->IsFocused = is_focused; @@ -12473,7 +12477,7 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock ImVec2 tab_pos = tab_bar_rect.Min; if (host_node && host_node->TabBar) { - if (!host_node->IsHiddenTabBar()) + if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar()) tab_pos.x += host_node->TabBar->OffsetMax + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. else tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x; @@ -13195,6 +13199,7 @@ void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persi } } +// FIXME-DOCK: We are not exposing nor using split_outer. ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_other) { ImGuiContext* ctx = GImGui; @@ -13511,7 +13516,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) // Update window flag IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0); window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize; - if (node->IsHiddenTabBar()) + if (node->IsHiddenTabBar() || node->IsNoTabBar()) window->Flags |= ImGuiWindowFlags_NoTitleBar; else window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! @@ -13577,7 +13582,7 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) else allow_null_target_node = true; // Dock into a regular window - const ImRect explicit_target_rect = (target_node && target_node->TabBar && !target_node->IsHiddenTabBar()) ? target_node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); + const ImRect explicit_target_rect = (target_node && target_node->TabBar && !target_node->IsHiddenTabBar() && !target_node->IsNoTabBar()) ? target_node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); // Preview docking request and find out split direction/ratio @@ -14209,14 +14214,13 @@ void ImGui::ShowDockingDebug() ImGui::BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); ImGui::BulletText("VisibleWindow: 0x%08X %s", node->VisibleWindow ? node->VisibleWindow->ID : 0, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); - ImGui::BulletText("SelectedTabID: 0x%08X", node->SelectedTabID); - ImGui::BulletText("LastFocusedNodeID: 0x%08X", node->LastFocusedNodeID); - if (ImGui::TreeNode("flags", "SharedFlags 0x%03X NodeFlags 0x%03X%s%s%s%s", - node->SharedFlags, node->LocalFlags, node->IsDockSpace() ? ", IsDockSpace" : "", node->IsCentralNode() ? ", IsCentralNode" : "", - (g.FrameCount - node->LastFrameAlive < 2) ? ", IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? ", IsActive" : "")) + ImGui::BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabID, node->LastFocusedNodeID); + ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : ""); + if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) { ImGui::CheckboxFlags("LocalFlags: NoSplit", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); ImGui::CheckboxFlags("LocalFlags: NoResize", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("LocalFlags: NoTabBar", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar); ImGui::CheckboxFlags("LocalFlags: HiddenTabBar",(unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index 1ed273cc..1c52d078 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -854,9 +854,10 @@ enum ImGuiDockNodeFlagsPrivate_ // [Internal] ImGuiDockNodeFlags_DockSpace = 1 << 10, // Local // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. ImGuiDockNodeFlags_CentralNode = 1 << 11, // Local + ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Local // Tab bar is completely unavailable. No triangle in the corner to enable it back. ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Local // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, - ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_HiddenTabBar, + ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar, ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace // When splitting those flags are moved to the inheriting child, never duplicated }; @@ -911,7 +912,8 @@ struct ImGuiDockNode bool IsRootNode() const { return ParentNode == NULL; } bool IsDockSpace() const { return (LocalFlags & ImGuiDockNodeFlags_DockSpace) != 0; } bool IsCentralNode() const { return (LocalFlags & ImGuiDockNodeFlags_CentralNode) != 0; } - bool IsHiddenTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } + bool IsHiddenTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } // Hidden tab bar can be shown back by clicking the small triangle + bool IsNoTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_NoTabBar) != 0; } // Never show a tab bar bool IsSplitNode() const { return ChildNodes[0] != NULL; } bool IsLeafNode() const { return ChildNodes[0] == NULL; } bool IsEmpty() const { return ChildNodes[0] == NULL && Windows.Size == 0; } From 9a0e71a6ecef4402d0504e3a2c9a05ca705ed5db Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 28 Mar 2019 15:41:49 +0100 Subject: [PATCH 192/566] Internals: Renamed the ImGuiWindow HiddenFrameXXX fields to decorrelate them from resizing behavior, as those values are set by other logic. --- imgui.cpp | 46 +++++++++++++++++++++++++--------------------- imgui_internal.h | 4 ++-- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 835eda8a..b129cb18 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2533,7 +2533,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) AutoFitOnlyGrows = false; AutoFitChildAxises = 0x00; AutoPosLastDirection = ImGuiDir_None; - HiddenFramesRegular = HiddenFramesForResize = 0; + HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); @@ -4617,7 +4617,7 @@ static ImVec2 CalcSizeContents(ImGuiWindow* window) if (window->Collapsed) if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) return window->SizeContents; - if (window->Hidden && window->HiddenFramesForResize == 0 && window->HiddenFramesRegular > 0) + if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0) return window->SizeContents; ImVec2 sz; @@ -4962,7 +4962,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update the Appearing flag bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on - const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesForResize > 0); + const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0); if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; @@ -5062,20 +5062,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update contents size from last frame for auto-fitting (or use explicit size) window->SizeContents = CalcSizeContents(window); - if (window->HiddenFramesRegular > 0) - window->HiddenFramesRegular--; - if (window->HiddenFramesForResize > 0) - window->HiddenFramesForResize--; + if (window->HiddenFramesCanSkipItems > 0) + window->HiddenFramesCanSkipItems--; + if (window->HiddenFramesCannotSkipItems > 0) + window->HiddenFramesCannotSkipItems--; // Hide new windows for one frame until they calculate their size if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api)) - window->HiddenFramesForResize = 1; + window->HiddenFramesCannotSkipItems = 1; // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) // We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0) { - window->HiddenFramesForResize = 1; + window->HiddenFramesCannotSkipItems = 1; if (flags & ImGuiWindowFlags_AlwaysAutoResize) { if (!window_size_x_set_by_api) @@ -5181,7 +5181,7 @@ 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->HiddenFramesForResize == 0); + const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); if (window_pos_with_pivot) SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering) else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) @@ -5250,7 +5250,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) PushClipRect(viewport_rect.Min, viewport_rect.Max, true); // Draw modal window background (darkens what is behind them, all viewports) - const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesForResize <= 0; + const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0; const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow); if (dim_bg_for_modal || dim_bg_for_window_list) { @@ -5516,24 +5516,28 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) - window->HiddenFramesRegular = 1; + window->HiddenFramesCanSkipItems = 1; // Completely hide along with parent or if parent is collapsed if (parent_window && (parent_window->Collapsed || parent_window->Hidden)) - window->HiddenFramesRegular = 1; + window->HiddenFramesCanSkipItems = 1; } // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) if (style.Alpha <= 0.0f) - window->HiddenFramesRegular = 1; + window->HiddenFramesCanSkipItems = 1; // Update the Hidden flag - window->Hidden = (window->HiddenFramesRegular > 0) || (window->HiddenFramesForResize > 0); + window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); - // Return false if we don't intend to display anything to allow user to perform an early out optimization - window->SkipItems = (window->Collapsed || !window->Active || window->Hidden) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesForResize <= 0; + // Update the SkipItems flag, used to early out of all items functions (no layout required) + bool skip_items = false; + if (window->Collapsed || !window->Active || window->Hidden) + if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) + skip_items = true; + window->SkipItems = skip_items; - return !window->SkipItems; + return !skip_items; } // Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead. @@ -6740,7 +6744,7 @@ void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_ { // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. window->Hidden = true; - window->HiddenFramesRegular = 1; + window->HiddenFramesCanSkipItems = 1; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount); } ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; @@ -8649,7 +8653,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) { ImGuiWindow* tooltip_window = g.CurrentWindow; tooltip_window->SkipItems = true; - tooltip_window->HiddenFramesRegular = 1; + tooltip_window->HiddenFramesCanSkipItems = 1; } } @@ -9506,7 +9510,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window)); ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); - ImGui::BulletText("Appearing: %d, Hidden: %d (Reg %d Resize %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesRegular, window->HiddenFramesForResize, window->SkipItems); + ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); if (!window->NavRectRel[0].IsInverted()) diff --git a/imgui_internal.h b/imgui_internal.h index cf0c7cd6..824c2824 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1228,8 +1228,8 @@ struct IMGUI_API ImGuiWindow bool AutoFitOnlyGrows; int AutoFitChildAxises; ImGuiDir AutoPosLastDirection; - int HiddenFramesRegular; // Hide the window for N frames - int HiddenFramesForResize; // Hide the window for N frames while allowing items to be submitted so we can measure their size + int HiddenFramesCanSkipItems; // Hide the window for N frames + int HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size ImGuiCond SetWindowPosAllowFlags; // store acceptable condition flags for SetNextWindowPos() use. ImGuiCond SetWindowSizeAllowFlags; // store acceptable condition flags for SetNextWindowSize() use. ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use. From b6ae8a0dca909c5384afee2a091ade3b28e1d443 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 28 Mar 2019 16:04:00 +0100 Subject: [PATCH 193/566] Docking: Disable SkipItems when directly/programmatically focused (possible generalization of code currently in BeginDocked which relies on tab bar interaction, will remove that code in next commit). (#2453, #2109) --- docs/TODO.txt | 4 +++- imgui.cpp | 9 ++++++++- imgui_internal.h | 1 + 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 4842ae0c..be4ef7cc 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -130,7 +130,9 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - dock: merge docking branch (#2109) - - dock: A~ Unreal style document system (requires low-level controls of dockspace serialization fork/copy/delete). this is mostly working but the DockBuilderXXX api are not exposed/finished. + - dock: B~ rework code to be able to lazily create tab bar instance in a single place. The _Unsorted tab flag could be replacing a trailing-counter in DockNode? + - dock: B~ fully track windows/settings reference in dock nodes. perhaps find a representation that allows facilitate use of dock builder functions. + - dock: B~ Unreal style document system (requires low-level controls of dockspace serialization fork/copy/delete). this is mostly working but the DockBuilderXXX api are not exposed/finished. - dock: B: when docking outer, perform size locking on neighbors nodes the same way we do it with splitters, so other nodes are not resized. - dock: B~ central node resizing behavior incorrect. - dock: B: changing title font/style per-window is not supported as dock nodes are created in NewFrame. diff --git a/imgui.cpp b/imgui.cpp index 2661b070..267ae676 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2587,6 +2587,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; + LastFrameJustFocused = -1; ItemWidthDefault = 0.0f; FontWindowScale = FontDpiScale = 1.0f; SettingsIdx = -1; @@ -6070,7 +6071,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) g.NextWindowData.Clear(); if (window->DockIsActive && !window->DockTabIsVisible) - window->HiddenFramesCanSkipItems = 1; + { + if (window->LastFrameJustFocused == g.FrameCount) // This may be a better a generalization for the code in BeginDocked() setting the same field. + window->HiddenFramesCannotSkipItems = 1; + else + window->HiddenFramesCanSkipItems = 1; + } if (flags & ImGuiWindowFlags_ChildWindow) { @@ -6219,6 +6225,7 @@ void ImGui::FocusWindow(ImGuiWindow* window) // Passing NULL allow to disable keyboard focus if (!window) return; + window->LastFrameJustFocused = g.FrameCount; // Select in dock node if (window->DockNode && window->DockNode->TabBar) diff --git a/imgui_internal.h b/imgui_internal.h index e4a4ea22..9f735e6b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1405,6 +1405,7 @@ struct IMGUI_API ImGuiWindow ImVec2ih HitTestHoleSize, HitTestHoleOffset; ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. Maximum visible content position ~~ Pos + (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis int LastFrameActive; // Last frame number the window was Active. + int LastFrameJustFocused; // Last frame number the window was made Focused. float ItemWidthDefault; ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items ImGuiStorage StateStorage; From 47219dd5c673024107616ecb589fa5250d398b07 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 28 Mar 2019 16:13:06 +0100 Subject: [PATCH 194/566] Docking: Remove code in BeginDocked() to set HiddenFramesCannotSkipItems based on upcoming tab bar selection, solely based on focus (might break something subtle?). Follow-up to c355ed126775f36dfb19202af8526ba2ce183877. (#2453, #2109) --- imgui.cpp | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 267ae676..9bad7a0a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6070,9 +6070,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->BeginCount++; g.NextWindowData.Clear(); + // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. + // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. + // This is analogous to regular windows being hidden from one frame. + // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. if (window->DockIsActive && !window->DockTabIsVisible) { - if (window->LastFrameJustFocused == g.FrameCount) // This may be a better a generalization for the code in BeginDocked() setting the same field. + if (window->LastFrameJustFocused == g.FrameCount) window->HiddenFramesCannotSkipItems = 1; else window->HiddenFramesCanSkipItems = 1; @@ -13527,14 +13531,6 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) if (node->VisibleWindow == window) window->DockTabIsVisible = true; - // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. - // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. - // This is analogous to regular windows being hidden from one frame. It is especially important as nested TabBars would otherwise generate flicker in the form - // of one empty frame. - // Note that we set HiddenFramesCannotSkipItems=2 because BeginDocked() is called just before Begin() has a chance to decrement the value. Effectively it'll be a 1 frame thing. - if (!window->DockTabIsVisible && node->TabBar && node->TabBar->NextSelectedTabId == window->ID) - window->HiddenFramesCannotSkipItems = 2; - // Update window flag IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0); window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize; From 5af385ea78d13a8390d95590dd557c8e3385278b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 28 Mar 2019 18:02:03 +0100 Subject: [PATCH 195/566] Viewport: Renamed member + added note about a Docking issue with restoring focus. --- imgui.cpp | 12 ++++++++---- imgui_internal.h | 4 ++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9bad7a0a..e54f8e3c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6260,6 +6260,10 @@ void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window) if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow)) if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) { + // FIXME-DOCKING: This is failing (lagging by one frame) for docked windows. + // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B. + // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update) + // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself? ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window); FocusWindow(focus_window); return; @@ -10554,8 +10558,8 @@ void ImGui::UpdatePlatformWindows() // Even without focus, we assume the window becomes front-most. // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available. - if (viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount) - viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount; + if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) + viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; } // Clear request flags @@ -10576,8 +10580,8 @@ void ImGui::UpdatePlatformWindows() } if (focused_viewport && g.PlatformLastFocusedViewport != focused_viewport->ID) { - if (focused_viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount) - focused_viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount; + if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) + focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; g.PlatformLastFocusedViewport = focused_viewport->ID; } } diff --git a/imgui_internal.h b/imgui_internal.h index 9f735e6b..89d0df5b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -951,7 +951,6 @@ struct ImGuiContext ImVector CurrentWindowStack; ImGuiStorage WindowsById; int WindowsActiveCount; - int WindowsFrontMostStampCount; // Every time the front-most window changes, we stamp its viewport with an incrementing counter ImGuiWindow* CurrentWindow; // Being drawn into ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) @@ -996,6 +995,7 @@ struct ImGuiContext ImGuiViewportP* MouseViewport; ImGuiViewportP* MouseLastHoveredViewport; // Last known viewport that was hovered by mouse (even if we are not hovering any viewport any more) + honoring the _NoInputs flag. ImGuiID PlatformLastFocusedViewport; // Record of last focused platform window/viewport, when this changes we stamp the viewport as front-most + int ViewportFrontMostStampCount; // Every time the front-most window changes, we stamp its viewport with an incrementing counter // Navigation data (for gamepad/keyboard) ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow' @@ -1141,7 +1141,6 @@ struct ImGuiContext FrameCount = 0; FrameCountEnded = FrameCountPlatformEnded = FrameCountRendered = -1; WindowsActiveCount = 0; - WindowsFrontMostStampCount = 0; CurrentWindow = NULL; HoveredWindow = NULL; HoveredRootWindow = NULL; @@ -1175,6 +1174,7 @@ struct ImGuiContext CurrentViewport = NULL; MouseViewport = MouseLastHoveredViewport = NULL; PlatformLastFocusedViewport = 0; + ViewportFrontMostStampCount = 0; NavWindow = NULL; NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0; From 9bf6509c6ef4ead477e5127f5729a55b971f8a4a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 28 Mar 2019 18:43:27 +0100 Subject: [PATCH 196/566] Docking: Fixed focus restore lagging by a frame when a tab stops being submitted. (#2109) Building on a little build of technical debt there, should transition toward a more general docking-agnostic system (#2304) --- docs/TODO.txt | 4 +++- imgui.cpp | 20 ++++++++++++++------ imgui_internal.h | 1 + imgui_widgets.cpp | 14 ++++++++++++++ 4 files changed, 32 insertions(+), 7 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index be4ef7cc..b911e9c8 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -9,6 +9,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - doc/test: checklist app to verify binding/integration of imgui (test inputs, rendering, callback, etc.). - doc/tips: tips of the day: website? applet in imgui_club? + - window: preserve/restore relative focus ordering (persistent or not) (#2304) -> also see docking reference to same #. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis). (#690) - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. @@ -130,6 +131,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - dock: merge docking branch (#2109) + - dock: B: ordering currently held in tab bar should be implicitly held by windows themselves (also see #2304) + - dock: B- tab bar: the order/focus restoring code could be part of TabBar and not DockNode? (#8) - dock: B~ rework code to be able to lazily create tab bar instance in a single place. The _Unsorted tab flag could be replacing a trailing-counter in DockNode? - dock: B~ fully track windows/settings reference in dock nodes. perhaps find a representation that allows facilitate use of dock builder functions. - dock: B~ Unreal style document system (requires low-level controls of dockspace serialization fork/copy/delete). this is mostly working but the DockBuilderXXX api are not exposed/finished. @@ -148,7 +151,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - dock: B- dpi: look at interaction with the hi-dpi and multi-dpi stuff. - dock: B- tab bar: appearing on first frame with a dumb layout would do less harm that not appearing? (when behind dynamic branch) or store titles + render in EndTabBar() - dock: B- tab bar: make selected tab always shows its full title? - - dock: B- tab bar: the order/focus restoring code could be part of TabBar and not DockNode? (#8) - dock: B- nav: design interactions so nav controls can dock/undock - dock: B- dockspace: flag to lock the dock tree and/or sizes (ImGuiDockNodeFlags_Locked?) - dock: B- reintroduce collapsing a floating dock node. also collapsing a docked dock node! diff --git a/imgui.cpp b/imgui.cpp index e54f8e3c..8d3364b0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1040,7 +1040,7 @@ static float NavUpdatePageUpPageDown(int allowed_dir_flags); static inline void NavUpdateAnyRequestFlag(); static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id); static ImVec2 NavCalcPreferredRefPos(); -static void NavSaveLastChildNavWindow(ImGuiWindow* nav_window); +static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); // Misc @@ -8143,7 +8143,9 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov } } -static void ImGui::NavSaveLastChildNavWindow(ImGuiWindow* nav_window) +// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). +// This way we could find the last focused window among our children. It would be much less confusing this way? +static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window) { ImGuiWindow* parent_window = nav_window; while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) @@ -8152,10 +8154,16 @@ static void ImGui::NavSaveLastChildNavWindow(ImGuiWindow* nav_window) parent_window->NavLastChildNavWindow = nav_window; } -// Call when we are expected to land on Layer 0 after FocusWindow() +// Restore the last focused child. +// Call when we are expected to land on the Main Layer (0) after FocusWindow() static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window) { - return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window; + if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive) + return window->NavLastChildNavWindow; + if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar) + if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar)) + return tab->Window; + return window; } static void NavRestoreLayer(ImGuiNavLayer layer) @@ -8380,7 +8388,7 @@ static void ImGui::NavUpdate() // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0 if (g.NavWindow) - NavSaveLastChildNavWindow(g.NavWindow); + NavSaveLastChildNavWindowIntoParent(g.NavWindow); if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0) g.NavWindow->NavLastChildNavWindow = NULL; @@ -8833,7 +8841,7 @@ static void ImGui::NavUpdateWindowing() // Move to parent menu if necessary ImGuiWindow* new_nav_window = g.NavWindow; while (new_nav_window->ParentWindow - && (new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0 + && (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) new_nav_window = new_nav_window->ParentWindow; diff --git a/imgui_internal.h b/imgui_internal.h index 89d0df5b..68c80344 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1707,6 +1707,7 @@ namespace ImGui // Tab Bars IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags, ImGuiDockNode* dock_node); IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); + IMGUI_API ImGuiTabItem* TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar); IMGUI_API void TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window); IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id); IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 031a9fd8..3dcb5096 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6455,6 +6455,20 @@ ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id) return NULL; } +// FIXME: See references to #2304 in TODO.txt +ImGuiTabItem* ImGui::TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar) +{ + ImGuiTabItem* most_recently_selected_tab = NULL; + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) + if (tab->Window && tab->Window->WasActive) + most_recently_selected_tab = tab; + } + return most_recently_selected_tab; +} + // The purpose of this call is to register tab in advance so we can control their order at the time they appear. // Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function. void ImGui::TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window) From 512d39d03169fdaa5a122eae586ab90577ee9af7 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 29 Mar 2019 16:17:04 +0100 Subject: [PATCH 197/566] Examples: OpenGL3: Minor tweaks, clarifications + not calling glBindBuffer more than necessary in the render loop. --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_allegro5.cpp | 2 +- examples/imgui_impl_opengl3.cpp | 50 +++++++++++++++++--------------- examples/imgui_impl_vulkan.cpp | 3 +- imgui.h | 2 +- 5 files changed, 32 insertions(+), 26 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e1911d3e..5193b8bf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,7 @@ Other Changes: - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) +- Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: FreeGLUT: Made io.DeltaTime always > 0. (#2430) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index ffd59d73..3b589c32 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -154,7 +154,7 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() { // Build texture atlas ImGuiIO &io = ImGui::GetIO(); - unsigned char *pixels; + unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 98904363..347da470 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. // 2019-03-15: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). // 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. @@ -104,8 +105,8 @@ static char g_GlslVersionString[32] = ""; static GLuint g_FontTexture = 0; static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; -static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; -static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; +static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location +static int g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location static unsigned int g_VboHandle = 0, g_ElementsHandle = 0; // Functions @@ -170,7 +171,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) #endif GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_ES2 - GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); + GLint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array_object); #endif #ifdef GL_POLYGON_MODE GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); @@ -226,20 +227,23 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. #endif + // 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. #ifndef IMGUI_IMPL_OPENGL_ES2 - // Recreate the VAO every time - // (This is to easily allow multiple GL contexts. VAO are not shared among GL contexts, and we don't track creation/deletion of windows so we don't have an obvious key to use to cache them.) - GLuint vao_handle = 0; - glGenVertexArrays(1, &vao_handle); - glBindVertexArray(vao_handle); + GLuint vertex_array_object = 0; + glGenVertexArrays(1, &vertex_array_object); + glBindVertexArray(vertex_array_object); #endif + + // Bind vertex/index buffers and setup attributes for ImDrawVert glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); - glEnableVertexAttribArray(g_AttribLocationPosition); - glEnableVertexAttribArray(g_AttribLocationUV); - glEnableVertexAttribArray(g_AttribLocationColor); - glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)); - glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); - glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); + glEnableVertexAttribArray(g_AttribLocationVtxPos); + glEnableVertexAttribArray(g_AttribLocationVtxUV); + glEnableVertexAttribArray(g_AttribLocationVtxColor); + glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)); + glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); + glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports @@ -251,10 +255,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) const ImDrawList* cmd_list = draw_data->CmdLists[n]; size_t idx_buffer_offset = 0; - glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); + // Upload vertex/index buffers glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) @@ -280,7 +282,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (clip_origin_lower_left) glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y)); else - glScissor((int)clip_rect.x, (int)clip_rect.y, (int)clip_rect.z, (int)clip_rect.w); // Support for GL 4.5's glClipControl(GL_UPPER_LEFT) + glScissor((int)clip_rect.x, (int)clip_rect.y, (int)clip_rect.z, (int)clip_rect.w); // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); @@ -290,8 +292,10 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) idx_buffer_offset += pcmd->ElemCount * sizeof(ImDrawIdx); } } + + // Destroy the temporary VAO #ifndef IMGUI_IMPL_OPENGL_ES2 - glDeleteVertexArrays(1, &vao_handle); + glDeleteVertexArrays(1, &vertex_array_object); #endif // Restore modified GL state @@ -302,7 +306,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) #endif glActiveTexture(last_active_texture); #ifndef IMGUI_IMPL_OPENGL_ES2 - glBindVertexArray(last_vertex_array); + glBindVertexArray(last_vertex_array_object); #endif glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); @@ -554,9 +558,9 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); - g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); - g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); - g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); + g_AttribLocationVtxPos = glGetAttribLocation(g_ShaderHandle, "Position"); + g_AttribLocationVtxUV = glGetAttribLocation(g_ShaderHandle, "UV"); + g_AttribLocationVtxColor = glGetAttribLocation(g_ShaderHandle, "Color"); // Create buffers glGenBuffers(1, &g_VboHandle); diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index eabc49ea..77c9408c 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -221,7 +221,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm if (!fd->IndexBuffer || fd->IndexBufferSize < index_size) CreateOrResizeBuffer(fd->IndexBuffer, fd->IndexBufferMemory, fd->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); - // Upload Vertex and index Data: + // Upload vertex/index data into a single contiguous GPU buffer { ImDrawVert* vtx_dst = NULL; ImDrawIdx* idx_dst = NULL; @@ -305,6 +305,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { + // User callback (registered via ImDrawList::AddCallback) pcmd->UserCallback(cmd_list, pcmd); } else diff --git a/imgui.h b/imgui.h index 4c8ab81d..1d907b04 100644 --- a/imgui.h +++ b/imgui.h @@ -19,7 +19,7 @@ Index of this file: // Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // Obsolete functions // Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) -// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) +// Draw List API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) // Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) */ From 163779da5108ad8d54c1d3fdaef6fa276b8bd36b Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 29 Mar 2019 16:18:26 +0100 Subject: [PATCH 198/566] Examples: DirectX12: Various tidying up. --- examples/imgui_impl_dx11.cpp | 2 +- examples/imgui_impl_dx12.cpp | 95 +++++++++++++++++------------------- 2 files changed, 47 insertions(+), 50 deletions(-) diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index a686d6bb..060d86cd 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -90,7 +90,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) return; } - // Copy and convert all vertices into a single contiguous buffer + // Upload vertex/index data into a single contiguous GPU buffer D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource; if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK) return; diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index f9e1884f..04fe7fd0 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-29: Misc: Various minor tidying up. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData(). @@ -43,14 +44,14 @@ static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {}; struct FrameResources { - ID3D12Resource* IB; - ID3D12Resource* VB; - int VertexBufferSize; - int IndexBufferSize; + ID3D12Resource* IndexBuffer; + ID3D12Resource* VertexBuffer; + int IndexBufferSize; + int VertexBufferSize; }; -static FrameResources* g_pFrameResources = NULL; -static UINT g_numFramesInFlight = 0; -static UINT g_frameIndex = UINT_MAX; +static FrameResources* g_pFrameResources = NULL; +static UINT g_numFramesInFlight = 0; +static UINT g_frameIndex = UINT_MAX; struct VERTEX_CONSTANT_BUFFER { @@ -64,17 +65,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL // FIXME: I'm assuming that this only gets called once per frame! // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. g_frameIndex = g_frameIndex + 1; - FrameResources* frameResources = &g_pFrameResources[g_frameIndex % g_numFramesInFlight]; - ID3D12Resource* g_pVB = frameResources->VB; - ID3D12Resource* g_pIB = frameResources->IB; - int g_VertexBufferSize = frameResources->VertexBufferSize; - int g_IndexBufferSize = frameResources->IndexBufferSize; + FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight]; // Create and grow vertex/index buffers if needed - if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount) + if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount) { - if (g_pVB) { g_pVB->Release(); g_pVB = NULL; } - g_VertexBufferSize = draw_data->TotalVtxCount + 5000; + if (fr->VertexBuffer != NULL) { fr->VertexBuffer->Release(); fr->VertexBuffer = NULL; } + fr->VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; @@ -83,7 +80,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL D3D12_RESOURCE_DESC desc; memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC)); desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = g_VertexBufferSize * sizeof(ImDrawVert); + desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert); desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; @@ -91,15 +88,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pVB)) < 0) + if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) return; - frameResources->VB = g_pVB; - frameResources->VertexBufferSize = g_VertexBufferSize; } - if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount) + if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount) { - if (g_pIB) { g_pIB->Release(); g_pIB = NULL; } - g_IndexBufferSize = draw_data->TotalIdxCount + 10000; + if (fr->IndexBuffer != NULL) { fr->IndexBuffer->Release(); fr->IndexBuffer = NULL; } + fr->IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; @@ -108,7 +103,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL D3D12_RESOURCE_DESC desc; memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC)); desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = g_IndexBufferSize * sizeof(ImDrawIdx); + desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx); desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; @@ -116,19 +111,17 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&g_pIB)) < 0) + if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) return; - frameResources->IB = g_pIB; - frameResources->IndexBufferSize = g_IndexBufferSize; } - // Copy and convert all vertices into a single contiguous buffer + // Upload vertex/index data into a single contiguous GPU buffer void* vtx_resource, *idx_resource; D3D12_RANGE range; memset(&range, 0, sizeof(D3D12_RANGE)); - if (g_pVB->Map(0, &range, &vtx_resource) != S_OK) + if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK) return; - if (g_pIB->Map(0, &range, &idx_resource) != S_OK) + if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK) return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource; @@ -140,14 +133,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } - g_pVB->Unmap(0, &range); - g_pIB->Unmap(0, &range); + fr->VertexBuffer->Unmap(0, &range); + fr->IndexBuffer->Unmap(0, &range); // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). VERTEX_CONSTANT_BUFFER vertex_constant_buffer; { - VERTEX_CONSTANT_BUFFER* constant_buffer = &vertex_constant_buffer; float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; @@ -159,7 +151,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL { 0.0f, 0.0f, 0.5f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; - memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); + memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp)); } // Setup viewport @@ -177,14 +169,14 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL unsigned int offset = 0; D3D12_VERTEX_BUFFER_VIEW vbv; memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW)); - vbv.BufferLocation = g_pVB->GetGPUVirtualAddress() + offset; - vbv.SizeInBytes = g_VertexBufferSize * stride; + vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset; + vbv.SizeInBytes = fr->VertexBufferSize * stride; vbv.StrideInBytes = stride; ctx->IASetVertexBuffers(0, 1, &vbv); D3D12_INDEX_BUFFER_VIEW ibv; memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW)); - ibv.BufferLocation = g_pIB->GetGPUVirtualAddress(); - ibv.SizeInBytes = g_IndexBufferSize * sizeof(ImDrawIdx); + ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress(); + ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx); ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; ctx->IASetIndexBuffer(&ibv); ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); @@ -192,7 +184,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL ctx->SetGraphicsRootSignature(g_pRootSignature); ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); - // Setup render state + // Setup blend factor const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; ctx->OMSetBlendFactor(blend_factor); @@ -208,10 +200,12 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { + // User callback (registered via ImDrawList::AddCallback) pcmd->UserCallback(cmd_list, pcmd); } else { + // Apply Scissor, Bind texture, Draw const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) }; ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId); ctx->RSSetScissorRects(1, &r); @@ -490,9 +484,9 @@ bool ImGui_ImplDX12_CreateDeviceObjects() // Create the input layout static D3D12_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; psoDesc.InputLayout = { local_layout, 3 }; } @@ -576,15 +570,17 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() if (!g_pd3dDevice) return; + ImGuiIO& io = ImGui::GetIO(); if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; } if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; } if (g_pRootSignature) { g_pRootSignature->Release(); g_pRootSignature = NULL; } if (g_pPipelineState) { g_pPipelineState->Release(); g_pPipelineState = NULL; } - if (g_pFontTextureResource) { g_pFontTextureResource->Release(); g_pFontTextureResource = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. + if (g_pFontTextureResource) { g_pFontTextureResource->Release(); g_pFontTextureResource = NULL; io.Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. for (UINT i = 0; i < g_numFramesInFlight; i++) { - if (g_pFrameResources[i].IB) { g_pFrameResources[i].IB->Release(); g_pFrameResources[i].IB = NULL; } - if (g_pFrameResources[i].VB) { g_pFrameResources[i].VB->Release(); g_pFrameResources[i].VB = NULL; } + FrameResources* fr = &g_pFrameResources[i]; + if (fr->IndexBuffer) { fr->IndexBuffer->Release(); fr->IndexBuffer = NULL; } + if (fr->VertexBuffer) { fr->VertexBuffer->Release(); fr->VertexBuffer = NULL; } } } @@ -605,10 +601,11 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO // Create buffers with a default size (they will later be grown as needed) for (int i = 0; i < num_frames_in_flight; i++) { - g_pFrameResources[i].IB = NULL; - g_pFrameResources[i].VB = NULL; - g_pFrameResources[i].VertexBufferSize = 5000; - g_pFrameResources[i].IndexBufferSize = 10000; + FrameResources* fr = &g_pFrameResources[i]; + fr->IndexBuffer = NULL; + fr->VertexBuffer = NULL; + fr->IndexBufferSize = 10000; + fr->VertexBufferSize = 5000; } return true; @@ -618,10 +615,10 @@ void ImGui_ImplDX12_Shutdown() { ImGui_ImplDX12_InvalidateDeviceObjects(); delete[] g_pFrameResources; + g_pFrameResources = NULL; g_pd3dDevice = NULL; g_hFontSrvCpuDescHandle.ptr = 0; g_hFontSrvGpuDescHandle.ptr = 0; - g_pFrameResources = NULL; g_numFramesInFlight = 0; g_frameIndex = UINT_MAX; } From e21bbee311a13c451a72fb0710fd25d963d2a974 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 29 Mar 2019 18:29:15 +0100 Subject: [PATCH 199/566] Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). FreeType: Fixed suggested code to not require an initial build call.. (#2454) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_dx9.cpp | 22 ++++------------------ misc/freetype/README.md | 9 +++++---- 3 files changed, 10 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5193b8bf..e3b717d9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,7 @@ Other Changes: - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. +- Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: FreeGLUT: Made io.DeltaTime always > 0. (#2430) diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index c0b9c74e..566ea4ce 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -10,6 +10,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example. @@ -253,24 +254,9 @@ void ImGui_ImplDX9_InvalidateDeviceObjects() { if (!g_pd3dDevice) return; - if (g_pVB) - { - g_pVB->Release(); - g_pVB = NULL; - } - if (g_pIB) - { - g_pIB->Release(); - g_pIB = NULL; - } - - // At this point note that we set ImGui::GetIO().Fonts->TexID to be == g_FontTexture, so clear both. - ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(g_FontTexture == io.Fonts->TexID); - if (g_FontTexture) - g_FontTexture->Release(); - g_FontTexture = NULL; - io.Fonts->TexID = NULL; + if (g_pVB) { g_pVB->Release(); g_pVB = NULL; } + if (g_pIB) { g_pIB->Release(); g_pIB = NULL; } + if (g_FontTexture) { g_FontTexture->Release(); g_FontTexture = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. } void ImGui_ImplDX9_NewFrame() diff --git a/misc/freetype/README.md b/misc/freetype/README.md index 4c53cd9c..397adec7 100644 --- a/misc/freetype/README.md +++ b/misc/freetype/README.md @@ -43,7 +43,8 @@ while (true) if (freetype_test.UpdateRebuild()) { // REUPLOAD FONT TEXTURE TO GPU - // e.g ImGui_ImplOpenGL3_DestroyDeviceObjects() + ImGui_ImplOpenGL3_CreateDeviceObjects() + ImGui_ImplXXX_DestroyDeviceObjects(); + ImGui_ImplXXX_CreateDeviceObjects(); } ImGui::NewFrame(); freetype_test.ShowFreetypeOptionsWindow(); @@ -85,10 +86,10 @@ struct FreeTypeTest if (!WantRebuild) return false; ImGuiIO& io = ImGui::GetIO(); - for (int n = 0; n < io.Fonts->Fonts.Size; n++) + io.Fonts->TexGlyphPadding = FontsPadding; + for (int n = 0; n < io.Fonts->ConfigData.Size; n++) { - ImFontConfig* font_config = (ImFontConfig*)io.Fonts->Fonts[n]->ConfigData; - io.Fonts->TexGlyphPadding = FontsPadding; + ImFontConfig* font_config = (ImFontConfig*)&io.Fonts->ConfigData[n]; font_config->RasterizerMultiply = FontsMultiply; font_config->RasterizerFlags = (BuildMode == FontBuildMode_FreeType) ? FontsFlags : 0x00; } From d9568c717de8ec53445bad00be73133f1a110317 Mon Sep 17 00:00:00 2001 From: Nicolas Noble Date: Sun, 31 Mar 2019 01:35:03 -0700 Subject: [PATCH 200/566] Silencing -Wstack-protector (#2459) --- imgui_draw.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 06340c07..dcdf0e3f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -73,6 +73,7 @@ Index of this file: #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif From 3a737e665ab3f663c29596f18a6c8ed96b152a70 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 1 Apr 2019 17:32:14 +0200 Subject: [PATCH 201/566] Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). + demo typo --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_vulkan.cpp | 7 ++++--- imgui_demo.cpp | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e3b717d9..4834cb3f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,7 @@ Other Changes: - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. +- Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: FreeGLUT: Made io.DeltaTime always > 0. (#2430) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 77c9408c..ad9406ca 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case. @@ -216,9 +217,9 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Create the Vertex and Index buffers: size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); - if (!fd->VertexBuffer || fd->VertexBufferSize < vertex_size) + if (fd->VertexBuffer == VK_NULL_HANDLE || fd->VertexBufferSize < vertex_size) CreateOrResizeBuffer(fd->VertexBuffer, fd->VertexBufferMemory, fd->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); - if (!fd->IndexBuffer || fd->IndexBufferSize < index_size) + if (fd->IndexBuffer == VK_NULL_HANDLE || fd->IndexBufferSize < index_size) CreateOrResizeBuffer(fd->IndexBuffer, fd->IndexBufferMemory, fd->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); // Upload vertex/index data into a single contiguous GPU buffer @@ -262,7 +263,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm VkBuffer vertex_buffers[1] = { fd->VertexBuffer }; VkDeviceSize vertex_offset[1] = { 0 }; vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset); - vkCmdBindIndexBuffer(command_buffer, fd->IndexBuffer, 0, VK_INDEX_TYPE_UINT16); + vkCmdBindIndexBuffer(command_buffer, fd->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); } // Setup viewport: diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 37eacfa3..7496cd23 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1546,7 +1546,7 @@ static void ShowDemoWindowWidgets() "IsItemEdited() = %d\n" "IsItemActivated() = %d\n" "IsItemDeactivated() = %d\n" - "IsItemDeactivatedEdit() = %d\n" + "IsItemDeactivatedAfterEdit() = %d\n" "IsItemVisible() = %d\n" "GetItemRectMin() = (%.1f, %.1f)\n" "GetItemRectMax() = (%.1f, %.1f)\n" From e3cd6b1cbb025d62289a550c913d1a6f8e97357f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 1 Apr 2019 18:12:24 +0200 Subject: [PATCH 202/566] Examples: Vulkan: Using IM_ARRAYSIZE() where possible. --- examples/imgui_impl_vulkan.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index ad9406ca..3aafb555 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -212,7 +212,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm VkResult err; FrameDataForRender* fd = &g_FramesDataBuffers[g_FrameIndex]; - g_FrameIndex = (g_FrameIndex + 1) % IMGUI_VK_QUEUED_FRAMES; + g_FrameIndex = (g_FrameIndex + 1) % IM_ARRAYSIZE(g_FramesDataBuffers); // Create the Vertex and Index buffers: size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); @@ -694,7 +694,7 @@ void ImGui_ImplVulkan_InvalidateDeviceObjects() { ImGui_ImplVulkan_InvalidateFontUploadObjects(); - for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++) + for (int i = 0; i < IM_ARRAYSIZE(g_FramesDataBuffers); i++) { FrameDataForRender* fd = &g_FramesDataBuffers[i]; if (fd->VertexBuffer) { vkDestroyBuffer (g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } @@ -867,7 +867,7 @@ void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_ // Create Command Buffers VkResult err; - for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++) + for (int i = 0; i < IM_ARRAYSIZE(wd->Frames); i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; { @@ -1068,7 +1068,7 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(g_Queue); - for (int i = 0; i < IMGUI_VK_QUEUED_FRAMES; i++) + for (int i = 0; i < IM_ARRAYSIZE(wd->Frames); i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; vkDestroyFence(device, fd->Fence, allocator); From 4a57507f75e1e0da7d3bd72345ab3ae86f4df81e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 10:40:14 +0200 Subject: [PATCH 203/566] InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) Not using isprint. + todo items. --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 3 ++- imgui.cpp | 2 +- imgui_demo.cpp | 3 ++- imgui_widgets.cpp | 10 +++++++--- 5 files changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4834cb3f..f2b0b447 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,6 +38,7 @@ Breaking Changes: Other Changes: - InputText: Fixed selection background starts rendering one frame after the cursor movement when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] +- InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] diff --git a/docs/TODO.txt b/docs/TODO.txt index f1774f8c..7e540b7b 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -138,7 +138,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - button: provide a button that looks framed. (?) - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - - image button: not taking an explicit id is odd. + - image button: not taking an explicit id can be problematic. (#2464, #1390) - slider/drag: ctrl+click when format doesn't include a % character.. disable? display underlying value in default format? (see InputScalarAsWidgetReplacement) - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). (#1946) @@ -329,6 +329,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: glfw: could go idle when minimized? if (glfwGetWindowAttrib(window, GLFW_ICONIFIED)) { glfwWaitEvents(); continue; } // issue: DeltaTime will be super high on resume, perhaps provide a way to let impl know (#440) - examples: opengl: rename imgui_impl_opengl2 to impl_opengl_legacy and imgui_impl_opengl3 to imgui_impl_opengl? (#1900) - examples: opengl: could use a single vertex buffer and glBufferSubData for uploads? + - examples: vulkan: viewport: support for synchronized swapping of multiple swap chains. - optimization: replace vsnprintf with stb_printf? or enable the defines/infrastructure to allow it (#1038) - optimization: add clipping for multi-component widgets (SliderFloatX, ColorEditX, etc.). one problem is that nav branch can't easily clip parent group when there is a move request. - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) diff --git a/imgui.cpp b/imgui.cpp index b129cb18..506a22aa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -933,7 +933,7 @@ CODE #endif #include "imgui_internal.h" -#include // toupper, isprint +#include // toupper #include // vsnprintf, sscanf, printf #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include // intptr_t diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7496cd23..423022c1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -49,7 +49,7 @@ Index of this file: #endif #include "imgui.h" -#include // toupper, isprint +#include // toupper #include // INT_MIN, INT_MAX #include // sqrtf, powf, cosf, sinf, floorf, ceilf #include // vsnprintf, sscanf, printf @@ -2571,6 +2571,7 @@ static void ShowDemoWindowMisc() ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); } ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f151e119..88e90cbc 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -37,7 +37,7 @@ Index of this file: #endif #include "imgui_internal.h" -#include // toupper, isprint +#include // toupper #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include // intptr_t #else @@ -3139,7 +3139,8 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f { unsigned int c = *p_char; - if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) + // Filter non-printable (NB: isprint is unreliable! see #2467) + if (c < 0x20) { bool pass = false; pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); @@ -3148,9 +3149,11 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f return false; } - if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. + // Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME) + if (c >= 0xE000 && c <= 0xF8FF) return false; + // Generic named filters if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific)) { if (flags & ImGuiInputTextFlags_CharsDecimal) @@ -3174,6 +3177,7 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f return false; } + // Custom callback filter if (flags & ImGuiInputTextFlags_CallbackCharFilter) { ImGuiInputTextCallbackData callback_data; From 01e29a393340aeac3fbc63fa5f618bb9d3555c7f Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 10:45:51 +0200 Subject: [PATCH 204/566] InputText: Fixed ImGuiInputTextFlags_AllowTabInput leading to two tabs characters being inserted if the back-end provided both Key and Character input. (#2467, #1336) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 8 +------- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f2b0b447..b4f7a9c2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,8 @@ Other Changes: - InputText: Fixed selection background starts rendering one frame after the cursor movement when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] - InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) +- InputText: Fixed ImGuiInputTextFlags_AllowTabInput leading to two tabs characters being inserted + if the back-end provided both Key and Character input. (#2467, #1336) - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 88e90cbc..04fe9d61 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3333,7 +3333,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ FocusWindow(window); IM_ASSERT(ImGuiNavInput_COUNT < 32); g.ActiveIdBlockNavInputFlags = (1 << ImGuiNavInput_Cancel); - if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out + if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out as we will use the \t character. g.ActiveIdBlockNavInputFlags |= (1 << ImGuiNavInput_KeyTab_); if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory)) g.ActiveIdAllowNavDirFlags = ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down)); @@ -3506,12 +3506,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ state->OnKeyPressed((int)c); } } - else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !is_readonly) - { - unsigned int c = '\t'; // Insert TAB - if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) - state->OnKeyPressed((int)c); - } else if (IsKeyPressedMap(ImGuiKey_Escape)) { clear_active_id = cancel_edit = true; From da035ced9752224050f88bec01ba3313972d30ab Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 11:04:00 +0200 Subject: [PATCH 205/566] InputText, Examples/SDL: Emulate \t input if back-end doesn't provide it. (#1336, #2467) + Fix some output filename in SDL build batch files. --- docs/TODO.txt | 1 + examples/example_sdl_opengl2/build_win32.bat | 4 ++-- examples/example_sdl_opengl3/build_win32.bat | 2 +- imgui_widgets.cpp | 18 ++++++++++++++---- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 7e540b7b..45d34748 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -80,6 +80,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input text: force scroll to end or scroll to a given line/contents (so user can implement a log or a search feature) - input text: a side bar that could e.g. preview where errors are. probably left to the user to draw but we'd need to give them the info there. - input text: a way for the user to provide syntax coloring. + - input text: Shift+TAB with ImGuiInputTextFlags_AllowTabInput works inconsistently depending on whether back-end emits actual Tab Key + \t Char or not (SDL doesn't). - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). - input text multi-line: support for cut/paste without selection (cut/paste the current line) - input text multi-line: line numbers? status bar? (follow up on #200) diff --git a/examples/example_sdl_opengl2/build_win32.bat b/examples/example_sdl_opengl2/build_win32.bat index 97692d9e..d209b2a2 100644 --- a/examples/example_sdl_opengl2/build_win32.bat +++ b/examples/example_sdl_opengl2/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_sdl_opengl2.exe +set OUT_EXE=example_sdl_opengl2 set INCLUDES=/I.. /I..\.. /I%SDL2_DIR%\include set SOURCES=main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl2.cpp ..\..\imgui*.cpp set LIBS=/libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_DIR%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console +cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl_opengl3/build_win32.bat b/examples/example_sdl_opengl3/build_win32.bat index f263c4b3..ce105602 100644 --- a/examples/example_sdl_opengl3/build_win32.bat +++ b/examples/example_sdl_opengl3/build_win32.bat @@ -1,6 +1,6 @@ @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_sdl_opengl3.exe +set OUT_EXE=example_sdl_opengl3 set INCLUDES=/I.. /I..\.. /I%SDL2_DIR%\include /I..\libs\gl3w set SOURCES=main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c set LIBS=/libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 04fe9d61..941b02ef 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3435,12 +3435,22 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (state->SelectedAllMouseLock && !io.MouseDown[0]) state->SelectedAllMouseLock = false; + // It is ill-defined whether the back-end needs to send a \t character when pressing the TAB keys. + // Win32 and GLFW naturally do it but not SDL. + const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper); + if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !ignore_char_inputs && !io.KeyShift && !is_readonly) + if (!io.InputQueueCharacters.contains('\t')) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) + state->OnKeyPressed((int)c); + } + + // Process regular text input (before we check for Return because using some IME will effectively send a Return?) + // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. if (io.InputQueueCharacters.Size > 0) { - // Process text input (before we check for Return because using some IME will effectively send a Return?) - // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. - bool ignore_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper); - if (!ignore_inputs && !is_readonly && !user_nav_input_start) + if (!ignore_char_inputs && !is_readonly && !user_nav_input_start) for (int n = 0; n < io.InputQueueCharacters.Size; n++) { // Insert character if they pass filtering From 8dab7ac0213088af8f2ce28ab0c2df65b2a6873d Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 11:14:34 +0200 Subject: [PATCH 206/566] InputText: Made Shift+Tab consistently do nothing regardless of whether the back-end emits both char and keys or just keys. (#2467, #1336) --- docs/TODO.txt | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 1 + imgui_widgets.cpp | 2 ++ 4 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 45d34748..24525947 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -80,7 +80,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input text: force scroll to end or scroll to a given line/contents (so user can implement a log or a search feature) - input text: a side bar that could e.g. preview where errors are. probably left to the user to draw but we'd need to give them the info there. - input text: a way for the user to provide syntax coloring. - - input text: Shift+TAB with ImGuiInputTextFlags_AllowTabInput works inconsistently depending on whether back-end emits actual Tab Key + \t Char or not (SDL doesn't). + - input text: Shift+TAB with ImGuiInputTextFlags_AllowTabInput could eat preceding blanks, up to tab_count. - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). - input text multi-line: support for cut/paste without selection (cut/paste the current line) - input text multi-line: line numbers? status bar? (follow up on #200) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dcdf0e3f..97f25bd4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2468,7 +2468,7 @@ void ImFont::BuildLookupTable() ImFontGlyph& tab_glyph = Glyphs.back(); tab_glyph = *FindGlyph((ImWchar)' '); tab_glyph.Codepoint = '\t'; - tab_glyph.AdvanceX *= 4; + tab_glyph.AdvanceX *= IM_TABSIZE; IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size-1); } diff --git a/imgui_internal.h b/imgui_internal.h index 824c2824..bcbaec6a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -129,6 +129,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointe #else #define IM_NEWLINE "\n" #endif +#define IM_TABSIZE (4) #define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) #define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 941b02ef..4ebbc1f5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3455,6 +3455,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Insert character if they pass filtering unsigned int c = (unsigned int)io.InputQueueCharacters[n]; + if (c == '\t' && io.KeyShift) + continue; if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) state->OnKeyPressed((int)c); } From 5c4cc370bb0e063d8e12b9fff71c85fab6b0cbbd Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 11:23:54 +0200 Subject: [PATCH 207/566] Examples: Vulkan: Added shader sources/references in the .cpp source. --- examples/example_glfw_vulkan/glsl_shader.frag | 2 +- examples/example_glfw_vulkan/glsl_shader.vert | 8 +++--- examples/imgui_impl_vulkan.cpp | 27 +++++++++++++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/examples/example_glfw_vulkan/glsl_shader.frag b/examples/example_glfw_vulkan/glsl_shader.frag index 313a8880..ce7e6f72 100644 --- a/examples/example_glfw_vulkan/glsl_shader.frag +++ b/examples/example_glfw_vulkan/glsl_shader.frag @@ -3,7 +3,7 @@ layout(location = 0) out vec4 fColor; layout(set=0, binding=0) uniform sampler2D sTexture; -layout(location = 0) in struct{ +layout(location = 0) in struct { vec4 Color; vec2 UV; } In; diff --git a/examples/example_glfw_vulkan/glsl_shader.vert b/examples/example_glfw_vulkan/glsl_shader.vert index 20b29082..9425365a 100644 --- a/examples/example_glfw_vulkan/glsl_shader.vert +++ b/examples/example_glfw_vulkan/glsl_shader.vert @@ -3,16 +3,16 @@ layout(location = 0) in vec2 aPos; layout(location = 1) in vec2 aUV; layout(location = 2) in vec4 aColor; -layout(push_constant) uniform uPushConstant{ +layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc; -out gl_PerVertex{ +out gl_PerVertex { vec4 gl_Position; }; -layout(location = 0) out struct{ +layout(location = 0) out struct { vec4 Color; vec2 UV; } Out; @@ -21,5 +21,5 @@ void main() { Out.Color = aColor; Out.UV = aUV; - gl_Position = vec4(aPos*pc.uScale+pc.uTranslate, 0, 1); + gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1); } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 3aafb555..962ce841 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -76,6 +76,23 @@ static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; // glsl_shader.vert, compiled with: // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert +/* +#version 450 core +layout(location = 0) in vec2 aPos; +layout(location = 1) in vec2 aUV; +layout(location = 2) in vec4 aColor; +layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc; + +out gl_PerVertex { vec4 gl_Position; }; +layout(location = 0) out struct { vec4 Color; vec2 UV; } Out; + +void main() +{ + Out.Color = aColor; + Out.UV = aUV; + gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1); +} +*/ static uint32_t __glsl_shader_vert_spv[] = { 0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b, @@ -123,6 +140,16 @@ static uint32_t __glsl_shader_vert_spv[] = // glsl_shader.frag, compiled with: // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag +/* +#version 450 core +layout(location = 0) out vec4 fColor; +layout(set=0, binding=0) uniform sampler2D sTexture; +layout(location = 0) in struct { vec4 Color; vec2 UV; } In; +void main() +{ + fColor = In.Color * texture(sTexture, In.UV.st); +} +*/ static uint32_t __glsl_shader_frag_spv[] = { 0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b, From a402f5b9a95e39aa287765409569ab255a22796c Mon Sep 17 00:00:00 2001 From: Andrew Willmott Date: Tue, 2 Apr 2019 12:25:33 +0100 Subject: [PATCH 208/566] Add makefile for freeglut --- examples/.gitignore | 1 + examples/example_freeglut_opengl2/Makefile | 65 ++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 examples/example_freeglut_opengl2/Makefile diff --git a/examples/.gitignore b/examples/.gitignore index b9e1bb62..b2cde198 100644 --- a/examples/.gitignore +++ b/examples/.gitignore @@ -33,6 +33,7 @@ example_glfw_opengl2/example_glfw_opengl2 example_glfw_opengl3/example_glfw_opengl3 example_sdl_opengl2/example_sdl_opengl2 example_sdl_opengl3/example_sdl_opengl3 +example_freeglut_opengl2/example_freeglut_opengl2 ## Dear ImGui Ini files imgui.ini diff --git a/examples/example_freeglut_opengl2/Makefile b/examples/example_freeglut_opengl2/Makefile new file mode 100644 index 00000000..9b409ab0 --- /dev/null +++ b/examples/example_freeglut_opengl2/Makefile @@ -0,0 +1,65 @@ +# +# Cross Platform Makefile +# Compatible with Ubuntu 14.04.1 and Mac OS X +# +# Linux: +# apt-get install freeglut3-dev +# + +#CXX = g++ +#CXX = clang++ + +EXE = example_freeglut_opengl2 +SOURCES = main.cpp +SOURCES += ../imgui_impl_freeglut.cpp ../imgui_impl_opengl2.cpp +SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) + +UNAME_S := $(shell uname -s) + + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + LIBS = -lGL -lglut + + CXXFLAGS = -I ../ -I../.. + CXXFLAGS += -Wall -Wformat + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + LIBS = -framework OpenGL -framework GLUT + + CXXFLAGS = -I .. -I../.. + CXXFLAGS += -Wall -Wformat + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) + ECHO_MESSAGE = "Windows" + LIBS = -lgdi32 -lopengl32 -limm32 -lglut + + CXXFLAGS = -I ../ -I../../ + CXXFLAGS += -Wall -Wformat + CFLAGS = $(CXXFLAGS) +endif + + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../../%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) From 81f70e5b7c0267cf142ece59f7c11325ee55348d Mon Sep 17 00:00:00 2001 From: Andrew Willmott Date: Tue, 2 Apr 2019 12:47:14 +0100 Subject: [PATCH 209/566] Fixups for OSX --- examples/example_freeglut_opengl2/main.cpp | 8 +++++++- examples/imgui_impl_freeglut.cpp | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/examples/example_freeglut_opengl2/main.cpp b/examples/example_freeglut_opengl2/main.cpp index c52dfe2a..f62c36d5 100644 --- a/examples/example_freeglut_opengl2/main.cpp +++ b/examples/example_freeglut_opengl2/main.cpp @@ -7,7 +7,11 @@ #include "imgui.h" #include "../imgui_impl_freeglut.h" #include "../imgui_impl_opengl2.h" -#include +#ifdef __APPLE__ + #include +#else + #include +#endif #ifdef _MSC_VER #pragma warning (disable: 4505) // unreferenced local function has been removed @@ -87,7 +91,9 @@ int main(int argc, char** argv) { // Create GLUT window glutInit(&argc, argv); +#ifndef __APPLE__ glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); +#endif glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE); glutInitWindowSize(1280, 720); glutCreateWindow("Dear ImGui FreeGLUT+OpenGL2 Example"); diff --git a/examples/imgui_impl_freeglut.cpp b/examples/imgui_impl_freeglut.cpp index 32671a6d..61cab500 100644 --- a/examples/imgui_impl_freeglut.cpp +++ b/examples/imgui_impl_freeglut.cpp @@ -21,7 +21,11 @@ #include "imgui.h" #include "imgui_impl_freeglut.h" -#include +#ifdef __APPLE__ + #include +#else + #include +#endif #ifdef _MSC_VER #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) @@ -68,7 +72,9 @@ void ImGui_ImplFreeGLUT_InstallFuncs() glutMotionFunc(ImGui_ImplFreeGLUT_MotionFunc); glutPassiveMotionFunc(ImGui_ImplFreeGLUT_MotionFunc); glutMouseFunc(ImGui_ImplFreeGLUT_MouseFunc); +#ifndef __APPLE__ glutMouseWheelFunc(ImGui_ImplFreeGLUT_MouseWheelFunc); +#endif glutKeyboardFunc(ImGui_ImplFreeGLUT_KeyboardFunc); glutKeyboardUpFunc(ImGui_ImplFreeGLUT_KeyboardUpFunc); glutSpecialFunc(ImGui_ImplFreeGLUT_SpecialFunc); From 3fad375f5f868bc1b89079b173b9bfcdcf6a586d Mon Sep 17 00:00:00 2001 From: Andrew Willmott Date: Tue, 2 Apr 2019 16:07:28 +0100 Subject: [PATCH 210/566] ifdef freeglut extensions properly --- examples/example_freeglut_opengl2/main.cpp | 2 +- examples/imgui_impl_freeglut.cpp | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/example_freeglut_opengl2/main.cpp b/examples/example_freeglut_opengl2/main.cpp index f62c36d5..cc12e651 100644 --- a/examples/example_freeglut_opengl2/main.cpp +++ b/examples/example_freeglut_opengl2/main.cpp @@ -91,7 +91,7 @@ int main(int argc, char** argv) { // Create GLUT window glutInit(&argc, argv); -#ifndef __APPLE__ +#ifdef __FREEGLUT_EXT_H__ glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); #endif glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE); diff --git a/examples/imgui_impl_freeglut.cpp b/examples/imgui_impl_freeglut.cpp index 61cab500..7054c378 100644 --- a/examples/imgui_impl_freeglut.cpp +++ b/examples/imgui_impl_freeglut.cpp @@ -72,7 +72,7 @@ void ImGui_ImplFreeGLUT_InstallFuncs() glutMotionFunc(ImGui_ImplFreeGLUT_MotionFunc); glutPassiveMotionFunc(ImGui_ImplFreeGLUT_MotionFunc); glutMouseFunc(ImGui_ImplFreeGLUT_MouseFunc); -#ifndef __APPLE__ +#ifdef __FREEGLUT_EXT_H__ glutMouseWheelFunc(ImGui_ImplFreeGLUT_MouseWheelFunc); #endif glutKeyboardFunc(ImGui_ImplFreeGLUT_KeyboardFunc); @@ -181,6 +181,7 @@ void ImGui_ImplFreeGLUT_MouseFunc(int glut_button, int state, int x, int y) io.MouseDown[button] = false; } +#ifdef __FREEGLUT_EXT_H__ void ImGui_ImplFreeGLUT_MouseWheelFunc(int button, int dir, int x, int y) { ImGuiIO& io = ImGui::GetIO(); @@ -191,6 +192,7 @@ void ImGui_ImplFreeGLUT_MouseWheelFunc(int button, int dir, int x, int y) io.MouseWheel -= 1.0; (void)button; // Unused } +#endif void ImGui_ImplFreeGLUT_ReshapeFunc(int w, int h) { From ece322ff12c4bea3a44b211ef470529163fb622b Mon Sep 17 00:00:00 2001 From: Andrew Willmott Date: Wed, 3 Apr 2019 14:53:11 +0100 Subject: [PATCH 211/566] freeglut -> glut rename --- docs/README.md | 2 +- examples/.gitignore | 2 +- examples/README.txt | 8 +-- .../Makefile | 4 +- .../example_freeglut_opengl2.vcxproj | 8 +-- .../example_freeglut_opengl2.vcxproj.filters | 6 +- .../main.cpp | 18 +++--- examples/imgui_impl_freeglut.h | 33 ---------- ..._impl_freeglut.cpp => imgui_impl_glut.cpp} | 60 +++++++++---------- examples/imgui_impl_glut.h | 33 ++++++++++ 10 files changed, 87 insertions(+), 87 deletions(-) rename examples/{example_freeglut_opengl2 => example_glut_opengl2}/Makefile (92%) rename examples/{example_freeglut_opengl2 => example_glut_opengl2}/example_freeglut_opengl2.vcxproj (98%) rename examples/{example_freeglut_opengl2 => example_glut_opengl2}/example_freeglut_opengl2.vcxproj.filters (93%) rename examples/{example_freeglut_opengl2 => example_glut_opengl2}/main.cpp (92%) delete mode 100644 examples/imgui_impl_freeglut.h rename examples/{imgui_impl_freeglut.cpp => imgui_impl_glut.cpp} (78%) create mode 100644 examples/imgui_impl_glut.h diff --git a/docs/README.md b/docs/README.md index 1a70ebf3..febacf05 100644 --- a/docs/README.md +++ b/docs/README.md @@ -134,7 +134,7 @@ Languages: (third-party bindings) Frameworks: - Renderers: DirectX 9/10/11/12, Metal, OpenGL2, OpenGL3+/ES2/ES3, Vulkan: [examples/](https://github.com/ocornut/imgui/tree/master/examples) -- Platform: GLFW, SDL, Win32, OSX, Freeglut: [examples/](https://github.com/ocornut/imgui/tree/master/examples) +- Platform: GLFW, SDL, Win32, OSX, GLUT: [examples/](https://github.com/ocornut/imgui/tree/master/examples) - Framework: Allegro 5, Marmalade: [examples/](https://github.com/ocornut/imgui/tree/master/examples) - Unmerged PR: SDL2 + OpenGLES + Emscripten: [#336](https://github.com/ocornut/imgui/pull/336) - Unmerged PR: Android: [#421](https://github.com/ocornut/imgui/pull/421) diff --git a/examples/.gitignore b/examples/.gitignore index b2cde198..428ea446 100644 --- a/examples/.gitignore +++ b/examples/.gitignore @@ -33,7 +33,7 @@ example_glfw_opengl2/example_glfw_opengl2 example_glfw_opengl3/example_glfw_opengl3 example_sdl_opengl2/example_sdl_opengl2 example_sdl_opengl3/example_sdl_opengl3 -example_freeglut_opengl2/example_freeglut_opengl2 +example_glut_opengl2/example_glut_opengl2 ## Dear ImGui Ini files imgui.ini diff --git a/examples/README.txt b/examples/README.txt index 97787f47..2876f7ee 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -104,7 +104,7 @@ List of Platforms Bindings in this repository: imgui_impl_osx.mm ; macOS native API imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org imgui_impl_win32.cpp ; Win32 native API (Windows) - imgui_impl_freeglut.cpp ; FreeGLUT (if you really miss the 90's) + imgui_impl_glut.cpp ; GLUT (if you really miss the 90's) List of Renderer Bindings in this repository: @@ -223,9 +223,9 @@ example_allegro5/ Allegro 5 example. = main.cpp + imgui_impl_allegro5.cpp -example_freeglut_opengl2/ - FreeGLUT + OpenGL2. - = main.cpp + imgui_impl_freeglut.cpp + imgui_impl_opengl2.cpp +example_glut_opengl2/ + GLUT (E.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2. + = main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp example_marmalade/ Marmalade example using IwGx. diff --git a/examples/example_freeglut_opengl2/Makefile b/examples/example_glut_opengl2/Makefile similarity index 92% rename from examples/example_freeglut_opengl2/Makefile rename to examples/example_glut_opengl2/Makefile index 9b409ab0..25ddc43a 100644 --- a/examples/example_freeglut_opengl2/Makefile +++ b/examples/example_glut_opengl2/Makefile @@ -9,9 +9,9 @@ #CXX = g++ #CXX = clang++ -EXE = example_freeglut_opengl2 +EXE = example_glut_opengl2 SOURCES = main.cpp -SOURCES += ../imgui_impl_freeglut.cpp ../imgui_impl_opengl2.cpp +SOURCES += ../imgui_impl_glut.cpp ../imgui_impl_opengl2.cpp SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) diff --git a/examples/example_freeglut_opengl2/example_freeglut_opengl2.vcxproj b/examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj similarity index 98% rename from examples/example_freeglut_opengl2/example_freeglut_opengl2.vcxproj rename to examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj index e3bd4176..58599e6d 100644 --- a/examples/example_freeglut_opengl2/example_freeglut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj @@ -20,7 +20,7 @@ {F90D0333-5FB1-440D-918D-DD39A1B5187E} - example_freeglut_opengl2 + example_glut_opengl2 @@ -154,7 +154,7 @@ - + @@ -162,7 +162,7 @@ - + @@ -172,4 +172,4 @@ - \ No newline at end of file + diff --git a/examples/example_freeglut_opengl2/example_freeglut_opengl2.vcxproj.filters b/examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj.filters similarity index 93% rename from examples/example_freeglut_opengl2/example_freeglut_opengl2.vcxproj.filters rename to examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj.filters index eb6d8526..290d43d7 100644 --- a/examples/example_freeglut_opengl2/example_freeglut_opengl2.vcxproj.filters +++ b/examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj.filters @@ -22,7 +22,7 @@ imgui - + sources @@ -42,7 +42,7 @@ imgui - + sources @@ -55,4 +55,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_freeglut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp similarity index 92% rename from examples/example_freeglut_opengl2/main.cpp rename to examples/example_glut_opengl2/main.cpp index cc12e651..4a4a03ad 100644 --- a/examples/example_freeglut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -1,11 +1,11 @@ -// dear imgui: standalone example application for FreeGLUT + OpenGL2, using legacy fixed pipeline +// dear imgui: standalone example application for GLUT + OpenGL2, using legacy fixed pipeline // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. // !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! #include "imgui.h" -#include "../imgui_impl_freeglut.h" +#include "../imgui_impl_glut.h" #include "../imgui_impl_opengl2.h" #ifdef __APPLE__ #include @@ -65,7 +65,7 @@ void glut_display_func() { // Start the Dear ImGui frame ImGui_ImplOpenGL2_NewFrame(); - ImGui_ImplFreeGLUT_NewFrame(); + ImGui_ImplGLUT_NewFrame(); my_display_code(); @@ -96,11 +96,11 @@ int main(int argc, char** argv) #endif glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE); glutInitWindowSize(1280, 720); - glutCreateWindow("Dear ImGui FreeGLUT+OpenGL2 Example"); + glutCreateWindow("Dear ImGui GLUT+OpenGL2 Example"); // Setup GLUT display function - // We will also call ImGui_ImplFreeGLUT_InstallFuncs() to get all the other functions installed for us, - // otherwise it is possible to install our own functions and call the imgui_impl_freeglut.h functions ourselves. + // We will also call ImGui_ImplGLUT_InstallFuncs() to get all the other functions installed for us, + // otherwise it is possible to install our own functions and call the imgui_impl_glut.h functions ourselves. glutDisplayFunc(glut_display_func); // Setup Dear ImGui context @@ -113,8 +113,8 @@ int main(int argc, char** argv) //ImGui::StyleColorsClassic(); // Setup Platform/Renderer bindings - ImGui_ImplFreeGLUT_Init(); - ImGui_ImplFreeGLUT_InstallFuncs(); + ImGui_ImplGLUT_Init(); + ImGui_ImplGLUT_InstallFuncs(); ImGui_ImplOpenGL2_Init(); // Load Fonts @@ -136,7 +136,7 @@ int main(int argc, char** argv) // Cleanup ImGui_ImplOpenGL2_Shutdown(); - ImGui_ImplFreeGLUT_Shutdown(); + ImGui_ImplGLUT_Shutdown(); ImGui::DestroyContext(); return 0; diff --git a/examples/imgui_impl_freeglut.h b/examples/imgui_impl_freeglut.h deleted file mode 100644 index 6d565ec6..00000000 --- a/examples/imgui_impl_freeglut.h +++ /dev/null @@ -1,33 +0,0 @@ -// dear imgui: Platform Binding for FreeGLUT -// This needs to be used along with a Renderer (e.g. OpenGL2) - -// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! -// !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! - -// Issues: -// [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I -// [ ] Platform: Missing clipboard support (not supported by Glut). -// [ ] Platform: Missing gamepad support. - -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui - -#pragma once - -IMGUI_IMPL_API bool ImGui_ImplFreeGLUT_Init(); -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_InstallFuncs(); -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_NewFrame(); - -// You can call ImGui_ImplFreeGLUT_InstallFuncs() to get all those functions installed automatically, -// or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency.. -//---------------------------------------- GLUT name --------------------------------------------- Decent Name --------- -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_MouseWheelFunc(int button, int dir, int x, int y); // ~ MouseWheelFunc -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_KeyboardFunc(unsigned char c, int x, int y); // ~ CharPressedFunc -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc -IMGUI_IMPL_API void ImGui_ImplFreeGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc diff --git a/examples/imgui_impl_freeglut.cpp b/examples/imgui_impl_glut.cpp similarity index 78% rename from examples/imgui_impl_freeglut.cpp rename to examples/imgui_impl_glut.cpp index 7054c378..60333caf 100644 --- a/examples/imgui_impl_freeglut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for FreeGLUT +// dear imgui: Platform Binding for GLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! @@ -17,10 +17,10 @@ // (minor and older changes stripped away, please see git history for details) // 2019-03-25: Misc: Made io.DeltaTime always above zero. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. -// 2018-03-22: Added FreeGLUT Platform binding. +// 2018-03-22: Added GLUT Platform binding. #include "imgui.h" -#include "imgui_impl_freeglut.h" +#include "imgui_impl_glut.h" #ifdef __APPLE__ #include #else @@ -33,10 +33,10 @@ static int g_Time = 0; // Current time, in milliseconds -bool ImGui_ImplFreeGLUT_Init() +bool ImGui_ImplGLUT_Init() { ImGuiIO& io = ImGui::GetIO(); - io.BackendPlatformName ="imgui_impl_freeglut"; + io.BackendPlatformName ="imgui_impl_glut"; g_Time = 0; @@ -66,26 +66,26 @@ bool ImGui_ImplFreeGLUT_Init() return true; } -void ImGui_ImplFreeGLUT_InstallFuncs() +void ImGui_ImplGLUT_InstallFuncs() { - glutReshapeFunc(ImGui_ImplFreeGLUT_ReshapeFunc); - glutMotionFunc(ImGui_ImplFreeGLUT_MotionFunc); - glutPassiveMotionFunc(ImGui_ImplFreeGLUT_MotionFunc); - glutMouseFunc(ImGui_ImplFreeGLUT_MouseFunc); + glutReshapeFunc(ImGui_ImplGLUT_ReshapeFunc); + glutMotionFunc(ImGui_ImplGLUT_MotionFunc); + glutPassiveMotionFunc(ImGui_ImplGLUT_MotionFunc); + glutMouseFunc(ImGui_ImplGLUT_MouseFunc); #ifdef __FREEGLUT_EXT_H__ - glutMouseWheelFunc(ImGui_ImplFreeGLUT_MouseWheelFunc); + glutMouseWheelFunc(ImGui_ImplGLUT_MouseWheelFunc); #endif - glutKeyboardFunc(ImGui_ImplFreeGLUT_KeyboardFunc); - glutKeyboardUpFunc(ImGui_ImplFreeGLUT_KeyboardUpFunc); - glutSpecialFunc(ImGui_ImplFreeGLUT_SpecialFunc); - glutSpecialUpFunc(ImGui_ImplFreeGLUT_SpecialUpFunc); + glutKeyboardFunc(ImGui_ImplGLUT_KeyboardFunc); + glutKeyboardUpFunc(ImGui_ImplGLUT_KeyboardUpFunc); + glutSpecialFunc(ImGui_ImplGLUT_SpecialFunc); + glutSpecialUpFunc(ImGui_ImplGLUT_SpecialUpFunc); } -void ImGui_ImplFreeGLUT_Shutdown() +void ImGui_ImplGLUT_Shutdown() { } -void ImGui_ImplFreeGLUT_NewFrame() +void ImGui_ImplGLUT_NewFrame() { // Setup time step ImGuiIO& io = ImGui::GetIO(); @@ -100,7 +100,7 @@ void ImGui_ImplFreeGLUT_NewFrame() ImGui::NewFrame(); } -static void ImGui_ImplFreeGLUT_UpdateKeyboardMods() +static void ImGui_ImplGLUT_UpdateKeyboardMods() { ImGuiIO& io = ImGui::GetIO(); int mods = glutGetModifiers(); @@ -109,7 +109,7 @@ static void ImGui_ImplFreeGLUT_UpdateKeyboardMods() io.KeyAlt = (mods & GLUT_ACTIVE_ALT) != 0; } -void ImGui_ImplFreeGLUT_KeyboardFunc(unsigned char c, int x, int y) +void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) { // Send character to imgui //printf("char_down_func %d '%c'\n", c, c); @@ -127,11 +127,11 @@ void ImGui_ImplFreeGLUT_KeyboardFunc(unsigned char c, int x, int y) io.KeysDown[c] = io.KeysDown[c - 'A' + 'a'] = true; else io.KeysDown[c] = true; - ImGui_ImplFreeGLUT_UpdateKeyboardMods(); + ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } -void ImGui_ImplFreeGLUT_KeyboardUpFunc(unsigned char c, int x, int y) +void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y) { //printf("char_up_func %d '%c'\n", c, c); ImGuiIO& io = ImGui::GetIO(); @@ -143,31 +143,31 @@ void ImGui_ImplFreeGLUT_KeyboardUpFunc(unsigned char c, int x, int y) io.KeysDown[c] = io.KeysDown[c - 'A' + 'a'] = false; else io.KeysDown[c] = false; - ImGui_ImplFreeGLUT_UpdateKeyboardMods(); + ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } -void ImGui_ImplFreeGLUT_SpecialFunc(int key, int x, int y) +void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y) { //printf("key_down_func %d\n", key); ImGuiIO& io = ImGui::GetIO(); if (key + 256 < IM_ARRAYSIZE(io.KeysDown)) io.KeysDown[key + 256] = true; - ImGui_ImplFreeGLUT_UpdateKeyboardMods(); + ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } -void ImGui_ImplFreeGLUT_SpecialUpFunc(int key, int x, int y) +void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y) { //printf("key_up_func %d\n", key); ImGuiIO& io = ImGui::GetIO(); if (key + 256 < IM_ARRAYSIZE(io.KeysDown)) io.KeysDown[key + 256] = false; - ImGui_ImplFreeGLUT_UpdateKeyboardMods(); + ImGui_ImplGLUT_UpdateKeyboardMods(); (void)x; (void)y; // Unused } -void ImGui_ImplFreeGLUT_MouseFunc(int glut_button, int state, int x, int y) +void ImGui_ImplGLUT_MouseFunc(int glut_button, int state, int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2((float)x, (float)y); @@ -182,7 +182,7 @@ void ImGui_ImplFreeGLUT_MouseFunc(int glut_button, int state, int x, int y) } #ifdef __FREEGLUT_EXT_H__ -void ImGui_ImplFreeGLUT_MouseWheelFunc(int button, int dir, int x, int y) +void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2((float)x, (float)y); @@ -194,13 +194,13 @@ void ImGui_ImplFreeGLUT_MouseWheelFunc(int button, int dir, int x, int y) } #endif -void ImGui_ImplFreeGLUT_ReshapeFunc(int w, int h) +void ImGui_ImplGLUT_ReshapeFunc(int w, int h) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)w, (float)h); } -void ImGui_ImplFreeGLUT_MotionFunc(int x, int y) +void ImGui_ImplGLUT_MotionFunc(int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2((float)x, (float)y); diff --git a/examples/imgui_impl_glut.h b/examples/imgui_impl_glut.h new file mode 100644 index 00000000..59fe0d51 --- /dev/null +++ b/examples/imgui_impl_glut.h @@ -0,0 +1,33 @@ +// dear imgui: Platform Binding for GLUT +// This needs to be used along with a Renderer (e.g. OpenGL2) + +// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! +// !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! + +// Issues: +// [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I +// [ ] Platform: Missing clipboard support (not supported by Glut). +// [ ] Platform: Missing gamepad support. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +#pragma once + +IMGUI_IMPL_API bool ImGui_ImplGLUT_Init(); +IMGUI_IMPL_API void ImGui_ImplGLUT_InstallFuncs(); +IMGUI_IMPL_API void ImGui_ImplGLUT_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame(); + +// You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically, +// or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency.. +//---------------------------------------- GLUT name --------------------------------------------- Decent Name --------- +IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc +IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc +IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc +IMGUI_IMPL_API void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y); // ~ MouseWheelFunc +IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y); // ~ CharPressedFunc +IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc +IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc +IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc From cdb109f617bd44df718f2c7c367ece02e2468da9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 16:23:50 +0200 Subject: [PATCH 212/566] Renamed freeglut vcxproj files + Comments, Changelog (#2465) --- docs/CHANGELOG.txt | 4 +++- examples/README.txt | 4 ++-- ...freeglut_opengl2.vcxproj => example_glut_opengl2.vcxproj} | 0 ....vcxproj.filters => example_glut_opengl2.vcxproj.filters} | 0 examples/example_glut_opengl2/main.cpp | 4 ++-- examples/imgui_impl_glut.cpp | 5 +++-- examples/imgui_impl_glut.h | 4 ++-- 7 files changed, 12 insertions(+), 9 deletions(-) rename examples/example_glut_opengl2/{example_freeglut_opengl2.vcxproj => example_glut_opengl2.vcxproj} (100%) rename examples/example_glut_opengl2/{example_freeglut_opengl2.vcxproj.filters => example_glut_opengl2.vcxproj.filters} (100%) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b4f7a9c2..316e69f3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,7 +49,9 @@ Other Changes: - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) -- Examples: FreeGLUT: Made io.DeltaTime always > 0. (#2430) +- Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] +- Examples: GLUT: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. (#2465) [@andrewwillmott] +- Examples: GLUT: Made io.DeltaTime always > 0. (#2430) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 2876f7ee..03974745 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -104,7 +104,7 @@ List of Platforms Bindings in this repository: imgui_impl_osx.mm ; macOS native API imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org imgui_impl_win32.cpp ; Win32 native API (Windows) - imgui_impl_glut.cpp ; GLUT (if you really miss the 90's) + imgui_impl_glut.cpp ; GLUT/FreeGLUT (not recommended unless really miss the 90's) List of Renderer Bindings in this repository: @@ -224,7 +224,7 @@ example_allegro5/ = main.cpp + imgui_impl_allegro5.cpp example_glut_opengl2/ - GLUT (E.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2. + GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2. = main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp example_marmalade/ diff --git a/examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj similarity index 100% rename from examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj rename to examples/example_glut_opengl2/example_glut_opengl2.vcxproj diff --git a/examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj.filters b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters similarity index 100% rename from examples/example_glut_opengl2/example_freeglut_opengl2.vcxproj.filters rename to examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 4a4a03ad..1089baee 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -1,7 +1,7 @@ -// dear imgui: standalone example application for GLUT + OpenGL2, using legacy fixed pipeline +// dear imgui: standalone example application for GLUT/FreeGLUT + OpenGL2, using legacy fixed pipeline // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. -// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! +// !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! #include "imgui.h" diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index 60333caf..d8bd7498 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -1,7 +1,7 @@ -// dear imgui: Platform Binding for GLUT +// dear imgui: Platform Binding for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) -// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! +// !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! // Issues: @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-03: Misc: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. // 2019-03-25: Misc: Made io.DeltaTime always above zero. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-03-22: Added GLUT Platform binding. diff --git a/examples/imgui_impl_glut.h b/examples/imgui_impl_glut.h index 59fe0d51..8fde9bab 100644 --- a/examples/imgui_impl_glut.h +++ b/examples/imgui_impl_glut.h @@ -1,7 +1,7 @@ -// dear imgui: Platform Binding for GLUT +// dear imgui: Platform Binding for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) -// !!! GLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! +// !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! // Issues: From fc523646529c336505c64f38f33dca463213709d Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 17:23:31 +0200 Subject: [PATCH 213/566] Tabs to Spaces, comments. --- examples/example_glfw_vulkan/main.cpp | 140 +++++++++++++------------- examples/example_sdl_vulkan/main.cpp | 28 +++--- examples/imgui_impl_metal.mm | 2 +- examples/imgui_impl_opengl2.cpp | 4 +- examples/imgui_impl_vulkan.cpp | 10 +- examples/imgui_impl_vulkan.h | 3 + imgui.cpp | 2 +- 7 files changed, 96 insertions(+), 93 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index fa098af8..0a9b8ccc 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -233,77 +233,77 @@ static void CleanupVulkan() static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) { - VkResult err; + VkResult err; - VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; - err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); - check_vk_result(err); + VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; + err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + check_vk_result(err); ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[wd->FrameIndex]; { - err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking - check_vk_result(err); - - err = vkResetFences(g_Device, 1, &fd->Fence); - check_vk_result(err); - } - { - err = vkResetCommandPool(g_Device, fd->CommandPool, 0); - check_vk_result(err); - VkCommandBufferBeginInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - err = vkBeginCommandBuffer(fd->CommandBuffer, &info); - check_vk_result(err); - } - { - VkRenderPassBeginInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; - info.renderPass = wd->RenderPass; - info.framebuffer = wd->Framebuffer[wd->FrameIndex]; - info.renderArea.extent.width = wd->Width; - info.renderArea.extent.height = wd->Height; - info.clearValueCount = 1; - info.pClearValues = &wd->ClearValue; - vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); - } - - // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); - - // Submit command buffer - vkCmdEndRenderPass(fd->CommandBuffer); - { - VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - VkSubmitInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &image_acquired_semaphore; - info.pWaitDstStageMask = &wait_stage; - info.commandBufferCount = 1; - info.pCommandBuffers = &fd->CommandBuffer; - info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &fd->RenderCompleteSemaphore; - - err = vkEndCommandBuffer(fd->CommandBuffer); - check_vk_result(err); - err = vkQueueSubmit(g_Queue, 1, &info, fd->Fence); - check_vk_result(err); - } + err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking + check_vk_result(err); + + err = vkResetFences(g_Device, 1, &fd->Fence); + check_vk_result(err); + } + { + err = vkResetCommandPool(g_Device, fd->CommandPool, 0); + check_vk_result(err); + VkCommandBufferBeginInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + err = vkBeginCommandBuffer(fd->CommandBuffer, &info); + check_vk_result(err); + } + { + VkRenderPassBeginInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + info.renderPass = wd->RenderPass; + info.framebuffer = wd->Framebuffer[wd->FrameIndex]; + info.renderArea.extent.width = wd->Width; + info.renderArea.extent.height = wd->Height; + info.clearValueCount = 1; + info.pClearValues = &wd->ClearValue; + vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); + } + + // Record Imgui Draw Data and draw funcs into command buffer + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); + + // Submit command buffer + vkCmdEndRenderPass(fd->CommandBuffer); + { + VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + info.waitSemaphoreCount = 1; + info.pWaitSemaphores = &image_acquired_semaphore; + info.pWaitDstStageMask = &wait_stage; + info.commandBufferCount = 1; + info.pCommandBuffers = &fd->CommandBuffer; + info.signalSemaphoreCount = 1; + info.pSignalSemaphores = &fd->RenderCompleteSemaphore; + + err = vkEndCommandBuffer(fd->CommandBuffer); + check_vk_result(err); + err = vkQueueSubmit(g_Queue, 1, &info, fd->Fence); + check_vk_result(err); + } } static void FramePresent(ImGui_ImplVulkanH_WindowData* wd) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[wd->FrameIndex]; - VkPresentInfoKHR info = {}; - info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; - info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &fd->RenderCompleteSemaphore; - info.swapchainCount = 1; - info.pSwapchains = &wd->Swapchain; - info.pImageIndices = &wd->FrameIndex; - VkResult err = vkQueuePresentKHR(g_Queue, &info); - check_vk_result(err); + VkPresentInfoKHR info = {}; + info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + info.waitSemaphoreCount = 1; + info.pWaitSemaphores = &fd->RenderCompleteSemaphore; + info.swapchainCount = 1; + info.pSwapchains = &wd->Swapchain; + info.pImageIndices = &wd->FrameIndex; + VkResult err = vkQueuePresentKHR(g_Queue, &info); + check_vk_result(err); } static void glfw_error_callback(int error, const char* description) @@ -315,12 +315,12 @@ static void glfw_resize_callback(GLFWwindow*, int w, int h) { g_ResizeWanted = true; g_ResizeWidth = w; - g_ResizeHeight = h; + g_ResizeHeight = h; } int main(int, char**) { - // Setup window + // Setup window glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return 1; @@ -433,11 +433,11 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); - if (g_ResizeWanted) - { - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight); - g_ResizeWanted = false; - } + if (g_ResizeWanted) + { + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight); + g_ResizeWanted = false; + } // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); @@ -484,7 +484,7 @@ int main(int, char**) // Rendering ImGui::Render(); memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); - FrameRender(wd); + FrameRender(wd); FramePresent(wd); } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index c5205750..e17a8ab7 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -223,18 +223,18 @@ static void CleanupVulkan() static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) { - VkResult err; + VkResult err; - VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; - err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); - check_vk_result(err); + VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; + err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + check_vk_result(err); ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[wd->FrameIndex]; { - err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking + err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking check_vk_result(err); - err = vkResetFences(g_Device, 1, &fd->Fence); + err = vkResetFences(g_Device, 1, &fd->Fence); check_vk_result(err); } { @@ -250,7 +250,7 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) VkRenderPassBeginInfo info = {}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; info.renderPass = wd->RenderPass; - info.framebuffer = wd->Framebuffer[wd->FrameIndex]; + info.framebuffer = wd->Framebuffer[wd->FrameIndex]; info.renderArea.extent.width = wd->Width; info.renderArea.extent.height = wd->Height; info.clearValueCount = 1; @@ -258,17 +258,17 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); } - // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); + // Record Imgui Draw Data and draw funcs into command buffer + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); - // Submit command buffer + // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); { VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; VkSubmitInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &image_acquired_semaphore; + info.pWaitSemaphores = &image_acquired_semaphore; info.pWaitDstStageMask = &wait_stage; info.commandBufferCount = 1; info.pCommandBuffers = &fd->CommandBuffer; @@ -291,8 +291,8 @@ static void FramePresent(ImGui_ImplVulkanH_WindowData* wd) info.pWaitSemaphores = &fd->RenderCompleteSemaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; - info.pImageIndices = &wd->FrameIndex; - VkResult err = vkQueuePresentKHR(g_Queue, &info); + info.pImageIndices = &wd->FrameIndex; + VkResult err = vkQueuePresentKHR(g_Queue, &info); check_vk_result(err); } @@ -470,7 +470,7 @@ int main(int, char**) // Rendering ImGui::Render(); memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); - FrameRender(wd); + FrameRender(wd); FramePresent(wd); } diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index 95de91c6..c04ecbf1 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -18,7 +18,7 @@ #include "imgui_impl_metal.h" #import -// #import // Not suported in XCode 9.2. Maybe a macro to detect the SDK version can be used (something like #if MACOS_SDK >= 10.13 ...) +// #import // Not supported in XCode 9.2. Maybe a macro to detect the SDK version can be used (something like #if MACOS_SDK >= 10.13 ...) #import #pragma mark - Support classes diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index 5acccc08..17e8b728 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -103,9 +103,9 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) glEnable(GL_TEXTURE_2D); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - // If you are using this code with non-legacy OpenGL header/contexts (which you should not, prefer using imgui_impl_opengl3.cpp!!), + // If you are using this code with non-legacy OpenGL header/contexts (which you should not, prefer using imgui_impl_opengl3.cpp!!), // you may need to backup/reset/restore current shader using the lines below. DO NOT MODIFY THIS FILE! Add the code in your calling function: - // GLint last_program; + // GLint last_program; // glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); // glUseProgram(0); // ImGui_ImplOpenGL2_RenderDrawData(...); diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 962ce841..f22efd55 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -946,7 +946,7 @@ int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_m void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h) { - uint32_t min_image_count = 2; // FIXME: this should become a function parameter + uint32_t min_image_count = 2; // FIXME: this should become a function parameter VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; @@ -974,7 +974,7 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice VkSwapchainCreateInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; info.surface = wd->Surface; - info.minImageCount = min_image_count; + info.minImageCount = min_image_count; info.imageFormat = wd->SurfaceFormat.format; info.imageColorSpace = wd->SurfaceFormat.colorSpace; info.imageArrayLayers = 1; @@ -989,9 +989,9 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap); check_vk_result(err); if (info.minImageCount < cap.minImageCount) - info.minImageCount = cap.minImageCount; - else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount) - info.minImageCount = cap.maxImageCount; + info.minImageCount = cap.minImageCount; + else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount) + info.minImageCount = cap.maxImageCount; if (cap.currentExtent.width == 0xffffffff) { diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 0a01bc0e..8bb35c86 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -46,6 +46,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateDeviceObjects(); //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers +// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: @@ -69,6 +70,7 @@ IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysic IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); // Helper structure to hold the data needed by one rendering frame +// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) struct ImGui_ImplVulkanH_FrameData { uint32_t BackbufferIndex; // Keep track of recently rendered swapchain frame indices @@ -82,6 +84,7 @@ struct ImGui_ImplVulkanH_FrameData }; // Helper structure to hold the data needed by one rendering context into one OS window +// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) struct ImGui_ImplVulkanH_WindowData { int Width; diff --git a/imgui.cpp b/imgui.cpp index 506a22aa..c0184541 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1333,7 +1333,7 @@ const char* ImStrchrRange(const char* str, const char* str_end, char c) int ImStrlenW(const ImWchar* str) { - //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits + //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits int n = 0; while (*str++) n++; return n; From 9ba64f9fe314ee684f566cd95da15054bd12e039 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 4 Apr 2019 22:02:36 +0200 Subject: [PATCH 214/566] Viewport: Fixed PushClipRectFullScreen() missing out on negative coordinates. Among other things, the outer highlight during CTRL+Tab wouldn't appear in negative coordinates monitors. (~#2176, #1542) --- imgui.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f2cfc5ec..5db1d8a9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3625,10 +3625,10 @@ void ImGui::NewFrame() g.IO.Fonts->Locked = true; SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); - ImVec2 virtual_space_max(0,0); + ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); for (int n = 0; n < g.Viewports.Size; n++) - virtual_space_max = ImMax(virtual_space_max, g.Viewports[n]->Pos + g.Viewports[n]->Size); - g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, virtual_space_max.x, virtual_space_max.y); + virtual_space.Add(g.Viewports[n]->GetRect()); + g.DrawListSharedData.ClipRectFullscreen = ImVec4(virtual_space.Min.x, virtual_space.Min.y, virtual_space.Max.x, virtual_space.Max.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; // Mark rendering data as invalid to prevent user who may have a handle on it to use it. @@ -10334,6 +10334,8 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame + g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x); + g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y); g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x); g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y); From 1c3311e4d646dc6f81bb54de8ce0990373e39282 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 4 Apr 2019 22:09:12 +0200 Subject: [PATCH 215/566] Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_vulkan.cpp | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 316e69f3..a4cbd4de 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,7 @@ Other Changes: GL function loaders early, and help users understand what they are missing. (#2421) - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). +- Examples: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] - Examples: GLUT: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. (#2465) [@andrewwillmott] diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index f22efd55..2d497931 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. @@ -347,6 +348,12 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) { + // Negative offsets are illegal for vkCmdSetScissor + if (clip_rect.x < 0.0f) + clip_rect.x = 0.0f; + if (clip_rect.y < 0.0f) + clip_rect.y = 0.0f; + // Apply scissor/clipping rectangle VkRect2D scissor; scissor.offset.x = (int32_t)(clip_rect.x); From b88a3b271123f08fbfc53f5a746a4583b086224b Mon Sep 17 00:00:00 2001 From: MindSpunk Date: Sun, 9 Sep 2018 16:04:44 +1000 Subject: [PATCH 216/566] Examples: Vulkan: Added calls to supports runtime changing back buffer count. (#2071) --- examples/example_glfw_vulkan/main.cpp | 41 ++++++++++--- examples/example_sdl_vulkan/main.cpp | 48 ++++++++++++++- examples/imgui_impl_vulkan.cpp | 87 ++++++++++++++++++++------- examples/imgui_impl_vulkan.h | 10 ++- 4 files changed, 150 insertions(+), 36 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 0a9b8ccc..6459a7aa 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -23,6 +23,7 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif +static uint32_t g_MinImageCount = 2; static VkAllocationCallbacks* g_Allocator = NULL; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; @@ -211,8 +212,8 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height); + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); } static void CleanupVulkan() @@ -373,6 +374,7 @@ int main(int, char**) init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; init_info.CheckVkResultFn = check_vk_result; + init_info.QueuedFrames = wd->BackBufferCount; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); // Load Fonts @@ -433,11 +435,14 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); - if (g_ResizeWanted) - { - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight); - g_ResizeWanted = false; - } + if (g_ResizeWanted) + { + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); + ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); + g_WindowData.FrameIndex = 0; + g_ResizeWanted = false; + } // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); @@ -478,6 +483,28 @@ int main(int, char**) ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) show_another_window = false; + + if (ImGui::Button("Increase")) + { + g_MinImageCount++; + g_ResizeWanted = true; + } + + ImGui::SameLine(); + if (ImGui::Button("Decrease")) + { + if (g_MinImageCount != 2) + { + g_MinImageCount--; + g_ResizeWanted = true; + } + } + + ImGui::SameLine(); + ImGui::Text("Back Buffers: %i", g_MinImageCount); + + ImGui::Text("Frame Index %i", wd->FrameIndex); + ImGui::End(); } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index e17a8ab7..b9bcffe9 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -15,6 +15,8 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif +static uint32_t g_MinImageCount = 2; +static bool g_PendingSwapchainRebuild = false; static VkAllocationCallbacks* g_Allocator = NULL; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; @@ -201,8 +203,8 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height); + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); } static void CleanupVulkan() @@ -296,6 +298,20 @@ static void FramePresent(ImGui_ImplVulkanH_WindowData* wd) check_vk_result(err); } +static void RebuildSwapChain(int width, int height) +{ + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); + ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); + g_WindowData.FrameIndex = 0; + g_PendingSwapchainRebuild = false; +} + +static void RebuildSwapChain() +{ + RebuildSwapChain(g_WindowData.Width, g_WindowData.Height); +} + int main(int, char**) { // Setup SDL @@ -354,6 +370,7 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; + init_info.QueuedFrames = wd->BackBufferCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); @@ -422,9 +439,12 @@ int main(int, char**) if (event.type == SDL_QUIT) done = true; if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, (int)event.window.data1, (int)event.window.data2); + RebuildSwapChain((int)event.window.data1, (int)event.window.data2); } + if (g_PendingSwapchainRebuild) + RebuildSwapChain(); + // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); ImGui_ImplSDL2_NewFrame(window); @@ -464,6 +484,28 @@ int main(int, char**) ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) show_another_window = false; + + if (ImGui::Button("Increase")) + { + g_MinImageCount++; + g_PendingSwapchainRebuild = true; + } + + ImGui::SameLine(); + if (ImGui::Button("Decrease")) + { + if (g_MinImageCount != 2) + { + g_MinImageCount--; + g_PendingSwapchainRebuild = true; + } + } + + ImGui::SameLine(); + ImGui::Text("Back Buffers: %i", g_MinImageCount); + + ImGui::Text("Frame Index %i", wd->FrameIndex); + ImGui::End(); } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 2d497931..833e4d3e 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -64,8 +64,8 @@ struct FrameDataForRender VkBuffer VertexBuffer; VkBuffer IndexBuffer; }; -static int g_FrameIndex = 0; -static FrameDataForRender g_FramesDataBuffers[IMGUI_VK_QUEUED_FRAMES] = {}; +static int g_FrameIndex = 0; +static ImVector g_FramesDataBuffers = {}; // Font data static VkSampler g_FontSampler = VK_NULL_HANDLE; @@ -240,7 +240,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm VkResult err; FrameDataForRender* fd = &g_FramesDataBuffers[g_FrameIndex]; - g_FrameIndex = (g_FrameIndex + 1) % IM_ARRAYSIZE(g_FramesDataBuffers); + g_FrameIndex = (g_FrameIndex + 1) % g_FramesDataBuffers.size(); // Create the Vertex and Index buffers: size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); @@ -728,15 +728,6 @@ void ImGui_ImplVulkan_InvalidateDeviceObjects() { ImGui_ImplVulkan_InvalidateFontUploadObjects(); - for (int i = 0; i < IM_ARRAYSIZE(g_FramesDataBuffers); i++) - { - FrameDataForRender* fd = &g_FramesDataBuffers[i]; - if (fd->VertexBuffer) { vkDestroyBuffer (g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } - if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; } - if (fd->IndexBuffer) { vkDestroyBuffer (g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } - if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } - } - if (g_FontView) { vkDestroyImageView(g_Device, g_FontView, g_Allocator); g_FontView = VK_NULL_HANDLE; } if (g_FontImage) { vkDestroyImage(g_Device, g_FontImage, g_Allocator); g_FontImage = VK_NULL_HANDLE; } if (g_FontMemory) { vkFreeMemory(g_Device, g_FontMemory, g_Allocator); g_FontMemory = VK_NULL_HANDLE; } @@ -746,6 +737,18 @@ void ImGui_ImplVulkan_InvalidateDeviceObjects() if (g_Pipeline) { vkDestroyPipeline(g_Device, g_Pipeline, g_Allocator); g_Pipeline = VK_NULL_HANDLE; } } +void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() +{ + for (int i = 0; i < g_FramesDataBuffers.size(); i++) + { + FrameDataForRender* fd = &g_FramesDataBuffers[i]; + if (fd->VertexBuffer) { vkDestroyBuffer(g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } + if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; } + if (fd->IndexBuffer) { vkDestroyBuffer(g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } + if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } + } +} + bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) { ImGuiIO& io = ImGui::GetIO(); @@ -768,6 +771,11 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend g_DescriptorPool = info->DescriptorPool; g_Allocator = info->Allocator; g_CheckVkResultFn = info->CheckVkResultFn; + g_FramesDataBuffers.resize(info->QueuedFrames); + for (int i = 0; i < g_FramesDataBuffers.size(); i++) + { + g_FramesDataBuffers[i] = FrameDataForRender(); + } ImGui_ImplVulkan_CreateDeviceObjects(); @@ -776,6 +784,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend void ImGui_ImplVulkan_Shutdown() { + ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); ImGui_ImplVulkan_InvalidateDeviceObjects(); } @@ -783,6 +792,24 @@ void ImGui_ImplVulkan_NewFrame() { } +void ImGui_ImplVulkan_SetQueuedFramesCount(uint32_t count) +{ + if (count == g_FramesDataBuffers.size()) + { + return; + } + ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); + + uint32_t old_size = g_FramesDataBuffers.size(); + g_FramesDataBuffers.resize(count); + for (uint32_t i = old_size; i < count; i++) + { + + g_FramesDataBuffers[i] = FrameDataForRender(); + } + g_FrameIndex = 0; +} + //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers @@ -901,7 +928,7 @@ void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_ // Create Command Buffers VkResult err; - for (int i = 0; i < IM_ARRAYSIZE(wd->Frames); i++) + for (int i = 0; i < wd->Frames.size(); i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; { @@ -951,10 +978,8 @@ int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_m return 1; } -void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h) +void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) { - uint32_t min_image_count = 2; // FIXME: this should become a function parameter - VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; err = vkDeviceWaitIdle(device); @@ -1015,7 +1040,18 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, NULL); check_vk_result(err); err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, wd->BackBuffer); - check_vk_result(err); + check_vk_result(err); + + for (uint32_t i = 0; i < wd->Frames.size(); i++) + { + ImGui_ImplVulkanH_DestroyFrameData(g_Instance, device, &wd->Frames[i], allocator); + } + uint32_t old_size = wd->Frames.size(); + wd->Frames.resize(wd->BackBufferCount); + for (uint32_t i = 0; i < wd->Frames.size(); i++) + { + wd->Frames[i] = ImGui_ImplVulkanH_FrameData(); + } } if (old_swapchain) vkDestroySwapchainKHR(device, old_swapchain, allocator); @@ -1102,14 +1138,10 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(g_Queue); - for (int i = 0; i < IM_ARRAYSIZE(wd->Frames); i++) + for (int i = 0; i < wd->Frames.size(); i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; - vkDestroyFence(device, fd->Fence, allocator); - vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); - vkDestroyCommandPool(device, fd->CommandPool, allocator); - vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); - vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); + ImGui_ImplVulkanH_DestroyFrameData(instance, device, fd, allocator); } for (uint32_t i = 0; i < wd->BackBufferCount; i++) { @@ -1121,3 +1153,12 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I vkDestroySurfaceKHR(instance, wd->Surface, allocator); *wd = ImGui_ImplVulkanH_WindowData(); } + +void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator) +{ + vkDestroyFence(device, fd->Fence, allocator); + vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); + vkDestroyCommandPool(device, fd->CommandPool, allocator); + vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); + vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); +} diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 8bb35c86..96cf52be 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -15,7 +15,7 @@ #include -#define IMGUI_VK_QUEUED_FRAMES 2 +//#define IMGUI_VK_QUEUED_FRAMES 2 // Please zero-clear before use. struct ImGui_ImplVulkan_InitInfo @@ -27,6 +27,7 @@ struct ImGui_ImplVulkan_InitInfo VkQueue Queue; VkPipelineCache PipelineCache; VkDescriptorPool DescriptorPool; + int QueuedFrames; const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); }; @@ -35,6 +36,7 @@ struct ImGui_ImplVulkan_InitInfo IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplVulkan_SetQueuedFramesCount(uint32_t count); IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFontUploadObjects(); @@ -42,6 +44,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFontUploadObjects(); // Called by ImGui_ImplVulkan_Init() might be useful elsewhere. IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); //------------------------------------------------------------------------- @@ -63,8 +66,9 @@ struct ImGui_ImplVulkanH_FrameData; struct ImGui_ImplVulkanH_WindowData; IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, uint32_t queue_family, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator); -IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h); +IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator); +IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); @@ -101,7 +105,7 @@ struct ImGui_ImplVulkanH_WindowData VkImageView BackBufferView[16]; VkFramebuffer Framebuffer[16]; uint32_t FrameIndex; - ImGui_ImplVulkanH_FrameData Frames[IMGUI_VK_QUEUED_FRAMES]; + ImVector Frames; IMGUI_IMPL_API ImGui_ImplVulkanH_WindowData(); }; From c7eef99a331595600c69965426ffc7c26837aa5e Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Sep 2018 22:18:24 +0200 Subject: [PATCH 217/566] Examples: Vulkan: Fixed tabs->space, removed extraneous braces and empty lines. (#2071) --- examples/example_glfw_vulkan/main.cpp | 62 ++++++++++---------- examples/example_sdl_vulkan/main.cpp | 69 +++++++++++------------ examples/imgui_impl_vulkan.cpp | 81 ++++++++++++--------------- examples/imgui_impl_vulkan.h | 2 +- 4 files changed, 99 insertions(+), 115 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 6459a7aa..6e25185f 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -23,7 +23,7 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif -static uint32_t g_MinImageCount = 2; +static uint32_t g_MinImageCount = 2; static VkAllocationCallbacks* g_Allocator = NULL; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; @@ -213,7 +213,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR // Create SwapChain, RenderPass, Framebuffer, etc. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); } static void CleanupVulkan() @@ -374,7 +374,7 @@ int main(int, char**) init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; init_info.CheckVkResultFn = check_vk_result; - init_info.QueuedFrames = wd->BackBufferCount; + init_info.QueuedFrames = wd->BackBufferCount; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); // Load Fonts @@ -435,14 +435,14 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); - if (g_ResizeWanted) - { - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); - ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); - g_WindowData.FrameIndex = 0; - g_ResizeWanted = false; - } + if (g_ResizeWanted) + { + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); + ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); + g_WindowData.FrameIndex = 0; + g_ResizeWanted = false; + } // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); @@ -484,26 +484,26 @@ int main(int, char**) if (ImGui::Button("Close Me")) show_another_window = false; - if (ImGui::Button("Increase")) - { - g_MinImageCount++; - g_ResizeWanted = true; - } - - ImGui::SameLine(); - if (ImGui::Button("Decrease")) - { - if (g_MinImageCount != 2) - { - g_MinImageCount--; - g_ResizeWanted = true; - } - } - - ImGui::SameLine(); - ImGui::Text("Back Buffers: %i", g_MinImageCount); - - ImGui::Text("Frame Index %i", wd->FrameIndex); + if (ImGui::Button("Increase")) + { + g_MinImageCount++; + g_ResizeWanted = true; + } + + ImGui::SameLine(); + if (ImGui::Button("Decrease")) + { + if (g_MinImageCount != 2) + { + g_MinImageCount--; + g_ResizeWanted = true; + } + } + + ImGui::SameLine(); + ImGui::Text("Back Buffers: %i", g_MinImageCount); + + ImGui::Text("Frame Index %i", wd->FrameIndex); ImGui::End(); } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index b9bcffe9..b430f5a0 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -15,8 +15,8 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif -static uint32_t g_MinImageCount = 2; -static bool g_PendingSwapchainRebuild = false; +static uint32_t g_MinImageCount = 2; +static bool g_PendingSwapchainRebuild = false; static VkAllocationCallbacks* g_Allocator = NULL; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; @@ -204,7 +204,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR // Create SwapChain, RenderPass, Framebuffer, etc. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); } static void CleanupVulkan() @@ -300,16 +300,11 @@ static void FramePresent(ImGui_ImplVulkanH_WindowData* wd) static void RebuildSwapChain(int width, int height) { - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, width, height, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); - ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); - g_WindowData.FrameIndex = 0; - g_PendingSwapchainRebuild = false; -} - -static void RebuildSwapChain() -{ - RebuildSwapChain(g_WindowData.Width, g_WindowData.Height); + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); + ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); + g_WindowData.FrameIndex = 0; + g_PendingSwapchainRebuild = false; } int main(int, char**) @@ -370,7 +365,7 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; - init_info.QueuedFrames = wd->BackBufferCount; + init_info.QueuedFrames = wd->BackBufferCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); @@ -439,11 +434,11 @@ int main(int, char**) if (event.type == SDL_QUIT) done = true; if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) - RebuildSwapChain((int)event.window.data1, (int)event.window.data2); + RebuildSwapChain((int)event.window.data1, (int)event.window.data2); } - if (g_PendingSwapchainRebuild) - RebuildSwapChain(); + if (g_PendingSwapchainRebuild) + RebuildSwapChain(g_WindowData.Width, g_WindowData.Height); // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); @@ -485,26 +480,26 @@ int main(int, char**) if (ImGui::Button("Close Me")) show_another_window = false; - if (ImGui::Button("Increase")) - { - g_MinImageCount++; - g_PendingSwapchainRebuild = true; - } - - ImGui::SameLine(); - if (ImGui::Button("Decrease")) - { - if (g_MinImageCount != 2) - { - g_MinImageCount--; - g_PendingSwapchainRebuild = true; - } - } - - ImGui::SameLine(); - ImGui::Text("Back Buffers: %i", g_MinImageCount); - - ImGui::Text("Frame Index %i", wd->FrameIndex); + if (ImGui::Button("Increase")) + { + g_MinImageCount++; + g_PendingSwapchainRebuild = true; + } + + ImGui::SameLine(); + if (ImGui::Button("Decrease")) + { + if (g_MinImageCount != 2) + { + g_MinImageCount--; + g_PendingSwapchainRebuild = true; + } + } + + ImGui::SameLine(); + ImGui::Text("Back Buffers: %i", g_MinImageCount); + + ImGui::Text("Frame Index %i", wd->FrameIndex); ImGui::End(); } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 833e4d3e..a74323ee 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -739,14 +739,14 @@ void ImGui_ImplVulkan_InvalidateDeviceObjects() void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() { - for (int i = 0; i < g_FramesDataBuffers.size(); i++) - { - FrameDataForRender* fd = &g_FramesDataBuffers[i]; - if (fd->VertexBuffer) { vkDestroyBuffer(g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } - if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; } - if (fd->IndexBuffer) { vkDestroyBuffer(g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } - if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } - } + for (int i = 0; i < g_FramesDataBuffers.size(); i++) + { + FrameDataForRender* fd = &g_FramesDataBuffers[i]; + if (fd->VertexBuffer) { vkDestroyBuffer(g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } + if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; } + if (fd->IndexBuffer) { vkDestroyBuffer(g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } + if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } + } } bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) @@ -771,11 +771,9 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend g_DescriptorPool = info->DescriptorPool; g_Allocator = info->Allocator; g_CheckVkResultFn = info->CheckVkResultFn; - g_FramesDataBuffers.resize(info->QueuedFrames); - for (int i = 0; i < g_FramesDataBuffers.size(); i++) - { - g_FramesDataBuffers[i] = FrameDataForRender(); - } + g_FramesDataBuffers.resize(info->QueuedFrames); + for (int i = 0; i < g_FramesDataBuffers.size(); i++) + g_FramesDataBuffers[i] = FrameDataForRender(); ImGui_ImplVulkan_CreateDeviceObjects(); @@ -784,7 +782,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend void ImGui_ImplVulkan_Shutdown() { - ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); + ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); ImGui_ImplVulkan_InvalidateDeviceObjects(); } @@ -794,20 +792,15 @@ void ImGui_ImplVulkan_NewFrame() void ImGui_ImplVulkan_SetQueuedFramesCount(uint32_t count) { - if (count == g_FramesDataBuffers.size()) - { - return; - } - ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); - - uint32_t old_size = g_FramesDataBuffers.size(); - g_FramesDataBuffers.resize(count); - for (uint32_t i = old_size; i < count; i++) - { - - g_FramesDataBuffers[i] = FrameDataForRender(); - } - g_FrameIndex = 0; + if (count == g_FramesDataBuffers.size()) + return; + ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); + + uint32_t old_size = g_FramesDataBuffers.size(); + g_FramesDataBuffers.resize(count); + for (uint32_t i = old_size; i < count; i++) + g_FramesDataBuffers[i] = FrameDataForRender(); + g_FrameIndex = 0; } @@ -1040,18 +1033,14 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, NULL); check_vk_result(err); err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, wd->BackBuffer); - check_vk_result(err); - - for (uint32_t i = 0; i < wd->Frames.size(); i++) - { - ImGui_ImplVulkanH_DestroyFrameData(g_Instance, device, &wd->Frames[i], allocator); - } - uint32_t old_size = wd->Frames.size(); - wd->Frames.resize(wd->BackBufferCount); - for (uint32_t i = 0; i < wd->Frames.size(); i++) - { - wd->Frames[i] = ImGui_ImplVulkanH_FrameData(); - } + check_vk_result(err); + + for (uint32_t i = 0; i < wd->Frames.size(); i++) + ImGui_ImplVulkanH_DestroyFrameData(g_Instance, device, &wd->Frames[i], allocator); + uint32_t old_size = wd->Frames.size(); + wd->Frames.resize(wd->BackBufferCount); + for (uint32_t i = 0; i < wd->Frames.size(); i++) + wd->Frames[i] = ImGui_ImplVulkanH_FrameData(); } if (old_swapchain) vkDestroySwapchainKHR(device, old_swapchain, allocator); @@ -1141,7 +1130,7 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I for (int i = 0; i < wd->Frames.size(); i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; - ImGui_ImplVulkanH_DestroyFrameData(instance, device, fd, allocator); + ImGui_ImplVulkanH_DestroyFrameData(instance, device, fd, allocator); } for (uint32_t i = 0; i < wd->BackBufferCount; i++) { @@ -1156,9 +1145,9 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator) { - vkDestroyFence(device, fd->Fence, allocator); - vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); - vkDestroyCommandPool(device, fd->CommandPool, allocator); - vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); - vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); + vkDestroyFence(device, fd->Fence, allocator); + vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); + vkDestroyCommandPool(device, fd->CommandPool, allocator); + vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); + vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 96cf52be..9164e6c3 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -27,7 +27,7 @@ struct ImGui_ImplVulkan_InitInfo VkQueue Queue; VkPipelineCache PipelineCache; VkDescriptorPool DescriptorPool; - int QueuedFrames; + int QueuedFrames; const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); }; From 317859a3dad32ef8acf1ba77d6e266e6c1f7e379 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 15:48:22 +0200 Subject: [PATCH 218/566] Examples: Vulkan: Updated Changelog, removed debug code, tweaked code, made GLFW/SDL match each others. Initialize FrameDataForRender fields. Added Assertion. Clearing fields on DestroyFrameData(). (#2071) --- docs/CHANGELOG.txt | 3 ++ examples/example_glfw_vulkan/main.cpp | 35 ++++------------- examples/example_sdl_vulkan/main.cpp | 54 +++++++++------------------ examples/imgui_impl_vulkan.cpp | 51 +++++++++++++++---------- examples/imgui_impl_vulkan.h | 4 +- 5 files changed, 61 insertions(+), 86 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a4cbd4de..0220f23a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,9 @@ Other Changes: - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. +- Examples: Vulkan: Added QueuedFramesCount field in ImGui_ImplVulkan_InitInfo, required during + initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071) [@nathanvoglsam] + Added ImGui_ImplVulkan_SetQueuedFramesCount() to override QueuedFramesCount while running. - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] - Examples: GLUT: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. (#2465) [@andrewwillmott] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 6e25185f..b04bde38 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -23,7 +23,6 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif -static uint32_t g_MinImageCount = 2; static VkAllocationCallbacks* g_Allocator = NULL; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; @@ -35,7 +34,8 @@ static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_WindowData g_WindowData; -static bool g_ResizeWanted = false; +static int g_MinImageCount = 2; +static bool g_WantSwapChainRebuild = false; static int g_ResizeWidth = 0, g_ResizeHeight = 0; static void check_vk_result(VkResult err) @@ -214,6 +214,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR // Create SwapChain, RenderPass, Framebuffer, etc. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); + IM_ASSERT(wd->BackBufferCount > 0); } static void CleanupVulkan() @@ -314,7 +315,7 @@ static void glfw_error_callback(int error, const char* description) static void glfw_resize_callback(GLFWwindow*, int w, int h) { - g_ResizeWanted = true; + g_WantSwapChainRebuild = true; g_ResizeWidth = w; g_ResizeHeight = h; } @@ -373,8 +374,8 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; + init_info.QueuedFramesCount = (int)wd->BackBufferCount; init_info.CheckVkResultFn = check_vk_result; - init_info.QueuedFrames = wd->BackBufferCount; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); // Load Fonts @@ -435,13 +436,13 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); - if (g_ResizeWanted) + if (g_WantSwapChainRebuild) { ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); g_WindowData.FrameIndex = 0; - g_ResizeWanted = false; + g_WantSwapChainRebuild = false; } // Start the Dear ImGui frame @@ -483,28 +484,6 @@ int main(int, char**) ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) show_another_window = false; - - if (ImGui::Button("Increase")) - { - g_MinImageCount++; - g_ResizeWanted = true; - } - - ImGui::SameLine(); - if (ImGui::Button("Decrease")) - { - if (g_MinImageCount != 2) - { - g_MinImageCount--; - g_ResizeWanted = true; - } - } - - ImGui::SameLine(); - ImGui::Text("Back Buffers: %i", g_MinImageCount); - - ImGui::Text("Frame Index %i", wd->FrameIndex); - ImGui::End(); } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index b430f5a0..15eb62c2 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -15,8 +15,6 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif -static uint32_t g_MinImageCount = 2; -static bool g_PendingSwapchainRebuild = false; static VkAllocationCallbacks* g_Allocator = NULL; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; @@ -28,6 +26,8 @@ static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_WindowData g_WindowData; +static uint32_t g_MinImageCount = 2; +static bool g_WantSwapChainRebuild = false; static void check_vk_result(VkResult err) { @@ -205,6 +205,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR // Create SwapChain, RenderPass, Framebuffer, etc. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); + IM_ASSERT(wd->BackBufferCount > 0); } static void CleanupVulkan() @@ -298,15 +299,6 @@ static void FramePresent(ImGui_ImplVulkanH_WindowData* wd) check_vk_result(err); } -static void RebuildSwapChain(int width, int height) -{ - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, width, height, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); - ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); - g_WindowData.FrameIndex = 0; - g_PendingSwapchainRebuild = false; -} - int main(int, char**) { // Setup SDL @@ -365,7 +357,7 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; - init_info.QueuedFrames = wd->BackBufferCount; + init_info.QueuedFramesCount = wd->BackBufferCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); @@ -434,11 +426,21 @@ int main(int, char**) if (event.type == SDL_QUIT) done = true; if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) - RebuildSwapChain((int)event.window.data1, (int)event.window.data2); + { + g_WindowData.Width = (int)event.window.data1; + g_WindowData.Height = (int)event.window.data2; + g_WantSwapChainRebuild = true; + } } - if (g_PendingSwapchainRebuild) - RebuildSwapChain(g_WindowData.Width, g_WindowData.Height); + if (g_WantSwapChainRebuild) + { + ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); + ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); + g_WindowData.FrameIndex = 0; + g_WantSwapChainRebuild = false; + } // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); @@ -479,28 +481,6 @@ int main(int, char**) ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) show_another_window = false; - - if (ImGui::Button("Increase")) - { - g_MinImageCount++; - g_PendingSwapchainRebuild = true; - } - - ImGui::SameLine(); - if (ImGui::Button("Decrease")) - { - if (g_MinImageCount != 2) - { - g_MinImageCount--; - g_PendingSwapchainRebuild = true; - } - } - - ImGui::SameLine(); - ImGui::Text("Back Buffers: %i", g_MinImageCount); - - ImGui::Text("Frame Index %i", wd->FrameIndex); - ImGui::End(); } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index a74323ee..9eff80fd 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -13,6 +13,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-XX-XX: Vulkan: Added QueuedFramesCount field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). +// 2019-XX-XX: Vulkan: Added ImGui_ImplVulkan_SetQueuedFramesCount() to override QueuedFramesCount while running. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. @@ -63,9 +65,11 @@ struct FrameDataForRender VkDeviceSize IndexBufferSize; VkBuffer VertexBuffer; VkBuffer IndexBuffer; + + FrameDataForRender() { VertexBufferMemory = IndexBufferMemory = VK_NULL_HANDLE; VertexBufferSize = IndexBufferSize = VK_NULL_HANDLE; VertexBuffer = IndexBuffer = VK_NULL_HANDLE; } }; static int g_FrameIndex = 0; -static ImVector g_FramesDataBuffers = {}; +static ImVector g_FramesDataBuffers; // Font data static VkSampler g_FontSampler = VK_NULL_HANDLE; @@ -240,7 +244,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm VkResult err; FrameDataForRender* fd = &g_FramesDataBuffers[g_FrameIndex]; - g_FrameIndex = (g_FrameIndex + 1) % g_FramesDataBuffers.size(); + g_FrameIndex = (g_FrameIndex + 1) % g_FramesDataBuffers.Size; // Create the Vertex and Index buffers: size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); @@ -739,7 +743,7 @@ void ImGui_ImplVulkan_InvalidateDeviceObjects() void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() { - for (int i = 0; i < g_FramesDataBuffers.size(); i++) + for (int i = 0; i < g_FramesDataBuffers.Size; i++) { FrameDataForRender* fd = &g_FramesDataBuffers[i]; if (fd->VertexBuffer) { vkDestroyBuffer(g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } @@ -747,6 +751,7 @@ void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() if (fd->IndexBuffer) { vkDestroyBuffer(g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } } + g_FramesDataBuffers.clear(); } bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) @@ -759,6 +764,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend IM_ASSERT(info->Device != VK_NULL_HANDLE); IM_ASSERT(info->Queue != VK_NULL_HANDLE); IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE); + IM_ASSERT(info->QueuedFramesCount >= 2); IM_ASSERT(render_pass != VK_NULL_HANDLE); g_Instance = info->Instance; @@ -771,9 +777,10 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend g_DescriptorPool = info->DescriptorPool; g_Allocator = info->Allocator; g_CheckVkResultFn = info->CheckVkResultFn; - g_FramesDataBuffers.resize(info->QueuedFrames); - for (int i = 0; i < g_FramesDataBuffers.size(); i++) - g_FramesDataBuffers[i] = FrameDataForRender(); + + g_FramesDataBuffers.reserve(info->QueuedFramesCount); + for (int i = 0; i < info->QueuedFramesCount; i++) + g_FramesDataBuffers.push_back(FrameDataForRender()); ImGui_ImplVulkan_CreateDeviceObjects(); @@ -790,17 +797,16 @@ void ImGui_ImplVulkan_NewFrame() { } -void ImGui_ImplVulkan_SetQueuedFramesCount(uint32_t count) +void ImGui_ImplVulkan_SetQueuedFramesCount(int count) { - if (count == g_FramesDataBuffers.size()) + if (count == g_FramesDataBuffers.Size) return; ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); - uint32_t old_size = g_FramesDataBuffers.size(); - g_FramesDataBuffers.resize(count); - for (uint32_t i = old_size; i < count; i++) - g_FramesDataBuffers[i] = FrameDataForRender(); g_FrameIndex = 0; + g_FramesDataBuffers.reserve(count); + for (int i = 0; i < count; i++) + g_FramesDataBuffers.push_back(FrameDataForRender()); } @@ -921,7 +927,7 @@ void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_ // Create Command Buffers VkResult err; - for (int i = 0; i < wd->Frames.size(); i++) + for (int i = 0; i < wd->Frames.Size; i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; { @@ -1035,12 +1041,13 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, wd->BackBuffer); check_vk_result(err); - for (uint32_t i = 0; i < wd->Frames.size(); i++) + for (int i = 0; i < wd->Frames.Size; i++) ImGui_ImplVulkanH_DestroyFrameData(g_Instance, device, &wd->Frames[i], allocator); - uint32_t old_size = wd->Frames.size(); - wd->Frames.resize(wd->BackBufferCount); - for (uint32_t i = 0; i < wd->Frames.size(); i++) - wd->Frames[i] = ImGui_ImplVulkanH_FrameData(); + wd->Frames.clear(); + + wd->Frames.reserve((int)wd->BackBufferCount); + for (int i = 0; i < (int)wd->BackBufferCount; i++) + wd->Frames.push_back(ImGui_ImplVulkanH_FrameData()); } if (old_swapchain) vkDestroySwapchainKHR(device, old_swapchain, allocator); @@ -1127,7 +1134,7 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(g_Queue); - for (int i = 0; i < wd->Frames.size(); i++) + for (int i = 0; i < wd->Frames.Size; i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; ImGui_ImplVulkanH_DestroyFrameData(instance, device, fd, allocator); @@ -1145,9 +1152,15 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator) { + (void)instance; vkDestroyFence(device, fd->Fence, allocator); vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); vkDestroyCommandPool(device, fd->CommandPool, allocator); vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); + fd->BackbufferIndex = 0; + fd->Fence = VK_NULL_HANDLE; + fd->CommandBuffer = VK_NULL_HANDLE; + fd->CommandPool = VK_NULL_HANDLE; + fd->ImageAcquiredSemaphore = fd->RenderCompleteSemaphore = VK_NULL_HANDLE; } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 9164e6c3..f54caf3d 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -27,7 +27,7 @@ struct ImGui_ImplVulkan_InitInfo VkQueue Queue; VkPipelineCache PipelineCache; VkDescriptorPool DescriptorPool; - int QueuedFrames; + int QueuedFramesCount; const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); }; @@ -36,7 +36,7 @@ struct ImGui_ImplVulkan_InitInfo IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); -IMGUI_IMPL_API void ImGui_ImplVulkan_SetQueuedFramesCount(uint32_t count); +IMGUI_IMPL_API void ImGui_ImplVulkan_SetQueuedFramesCount(int queued_frames_count); // To override QueuedFramesCount after initialization IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFontUploadObjects(); From 54b8a65d9edcdc560ae643f3c4e812ca2639dedf Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 17:56:18 +0200 Subject: [PATCH 219/566] Examples: Vulkan: Renamed QueuedFramesCount to FramesQueueSize. Moved Framebuffer, Backbuffer to FrameData structure. (#2071) --- docs/CHANGELOG.txt | 4 +- examples/example_glfw_vulkan/main.cpp | 8 +-- examples/example_sdl_vulkan/main.cpp | 8 +-- examples/imgui_impl_vulkan.cpp | 83 ++++++++++++--------------- examples/imgui_impl_vulkan.h | 15 +++-- 5 files changed, 54 insertions(+), 64 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0220f23a..6046f19b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,9 +49,9 @@ Other Changes: - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. -- Examples: Vulkan: Added QueuedFramesCount field in ImGui_ImplVulkan_InitInfo, required during +- Examples: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required during initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071) [@nathanvoglsam] - Added ImGui_ImplVulkan_SetQueuedFramesCount() to override QueuedFramesCount while running. + Added ImGui_ImplVulkan_SetFramesQueueSize() to override FramesQueueSize while running. - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] - Examples: GLUT: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. (#2465) [@andrewwillmott] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index b04bde38..cec1217d 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -214,7 +214,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR // Create SwapChain, RenderPass, Framebuffer, etc. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); - IM_ASSERT(wd->BackBufferCount > 0); + IM_ASSERT(wd->FramesQueueSize >= 2); } static void CleanupVulkan() @@ -262,7 +262,7 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) VkRenderPassBeginInfo info = {}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; info.renderPass = wd->RenderPass; - info.framebuffer = wd->Framebuffer[wd->FrameIndex]; + info.framebuffer = fd->Framebuffer; info.renderArea.extent.width = wd->Width; info.renderArea.extent.height = wd->Height; info.clearValueCount = 1; @@ -374,7 +374,7 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; - init_info.QueuedFramesCount = (int)wd->BackBufferCount; + init_info.FramesQueueSize = wd->FramesQueueSize; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); @@ -440,7 +440,7 @@ int main(int, char**) { ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); - ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); + ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 15eb62c2..70ba5a2d 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -205,7 +205,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR // Create SwapChain, RenderPass, Framebuffer, etc. ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); - IM_ASSERT(wd->BackBufferCount > 0); + IM_ASSERT(wd->FramesQueueSize >= 2); } static void CleanupVulkan() @@ -253,7 +253,7 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) VkRenderPassBeginInfo info = {}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; info.renderPass = wd->RenderPass; - info.framebuffer = wd->Framebuffer[wd->FrameIndex]; + info.framebuffer = fd->Framebuffer; info.renderArea.extent.width = wd->Width; info.renderArea.extent.height = wd->Height; info.clearValueCount = 1; @@ -357,7 +357,7 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; - init_info.QueuedFramesCount = wd->BackBufferCount; + init_info.FramesQueueSize = wd->FramesQueueSize; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); @@ -437,7 +437,7 @@ int main(int, char**) { ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); - ImGui_ImplVulkan_SetQueuedFramesCount(g_WindowData.BackBufferCount); + ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 9eff80fd..2d6fc373 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -13,8 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-XX-XX: Vulkan: Added QueuedFramesCount field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). -// 2019-XX-XX: Vulkan: Added ImGui_ImplVulkan_SetQueuedFramesCount() to override QueuedFramesCount while running. +// 2019-XX-XX: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetFramesQueueSize() to override FramesQueueSize while running. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. @@ -764,7 +763,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend IM_ASSERT(info->Device != VK_NULL_HANDLE); IM_ASSERT(info->Queue != VK_NULL_HANDLE); IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE); - IM_ASSERT(info->QueuedFramesCount >= 2); + IM_ASSERT(info->FramesQueueSize >= 2); IM_ASSERT(render_pass != VK_NULL_HANDLE); g_Instance = info->Instance; @@ -778,8 +777,8 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend g_Allocator = info->Allocator; g_CheckVkResultFn = info->CheckVkResultFn; - g_FramesDataBuffers.reserve(info->QueuedFramesCount); - for (int i = 0; i < info->QueuedFramesCount; i++) + g_FramesDataBuffers.reserve(info->FramesQueueSize); + for (int i = 0; i < info->FramesQueueSize; i++) g_FramesDataBuffers.push_back(FrameDataForRender()); ImGui_ImplVulkan_CreateDeviceObjects(); @@ -797,15 +796,15 @@ void ImGui_ImplVulkan_NewFrame() { } -void ImGui_ImplVulkan_SetQueuedFramesCount(int count) +void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size) { - if (count == g_FramesDataBuffers.Size) + if (frames_queue_size == g_FramesDataBuffers.Size) return; ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); g_FrameIndex = 0; - g_FramesDataBuffers.reserve(count); - for (int i = 0; i < count; i++) + g_FramesDataBuffers.reserve(frames_queue_size); + for (int i = 0; i < frames_queue_size; i++) g_FramesDataBuffers.push_back(FrameDataForRender()); } @@ -828,12 +827,14 @@ void ImGui_ImplVulkan_SetQueuedFramesCount(int count) ImGui_ImplVulkanH_FrameData::ImGui_ImplVulkanH_FrameData() { - BackbufferIndex = 0; CommandPool = VK_NULL_HANDLE; CommandBuffer = VK_NULL_HANDLE; Fence = VK_NULL_HANDLE; ImageAcquiredSemaphore = VK_NULL_HANDLE; RenderCompleteSemaphore = VK_NULL_HANDLE; + BackBuffer = VK_NULL_HANDLE; + BackBufferView = VK_NULL_HANDLE; + Framebuffer = VK_NULL_HANDLE; } ImGui_ImplVulkanH_WindowData::ImGui_ImplVulkanH_WindowData() @@ -846,10 +847,7 @@ ImGui_ImplVulkanH_WindowData::ImGui_ImplVulkanH_WindowData() RenderPass = VK_NULL_HANDLE; ClearEnable = true; memset(&ClearValue, 0, sizeof(ClearValue)); - BackBufferCount = 0; - memset(&BackBuffer, 0, sizeof(BackBuffer)); - memset(&BackBufferView, 0, sizeof(BackBufferView)); - memset(&Framebuffer, 0, sizeof(Framebuffer)); + FramesQueueSize = 0; FrameIndex = 0; } @@ -985,14 +983,10 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice check_vk_result(err); // Destroy old Framebuffer - for (uint32_t i = 0; i < wd->BackBufferCount; i++) - { - if (wd->BackBufferView[i]) - vkDestroyImageView(device, wd->BackBufferView[i], allocator); - if (wd->Framebuffer[i]) - vkDestroyFramebuffer(device, wd->Framebuffer[i], allocator); - } - wd->BackBufferCount = 0; + for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + ImGui_ImplVulkanH_DestroyFrameData(g_Instance, device, &wd->Frames[i], allocator); + wd->Frames.clear(); + wd->FramesQueueSize = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1036,18 +1030,19 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice } err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain); check_vk_result(err); - err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, NULL); + err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->FramesQueueSize, NULL); check_vk_result(err); - err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->BackBufferCount, wd->BackBuffer); + VkImage backbuffers[16] = {}; + IM_ASSERT(wd->FramesQueueSize < IM_ARRAYSIZE(backbuffers)); + err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->FramesQueueSize, backbuffers); check_vk_result(err); - for (int i = 0; i < wd->Frames.Size; i++) - ImGui_ImplVulkanH_DestroyFrameData(g_Instance, device, &wd->Frames[i], allocator); - wd->Frames.clear(); - - wd->Frames.reserve((int)wd->BackBufferCount); - for (int i = 0; i < (int)wd->BackBufferCount; i++) + wd->Frames.reserve((int)wd->FramesQueueSize); + for (int i = 0; i < (int)wd->FramesQueueSize; i++) + { wd->Frames.push_back(ImGui_ImplVulkanH_FrameData()); + wd->Frames[i].BackBuffer = backbuffers[i]; + } } if (old_swapchain) vkDestroySwapchainKHR(device, old_swapchain, allocator); @@ -1101,10 +1096,11 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice info.components.a = VK_COMPONENT_SWIZZLE_A; VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; info.subresourceRange = image_range; - for (uint32_t i = 0; i < wd->BackBufferCount; i++) + for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { - info.image = wd->BackBuffer[i]; - err = vkCreateImageView(device, &info, allocator, &wd->BackBufferView[i]); + ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; + info.image = fd->BackBuffer; + err = vkCreateImageView(device, &info, allocator, &fd->BackBufferView); check_vk_result(err); } } @@ -1120,10 +1116,11 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice info.width = wd->Width; info.height = wd->Height; info.layers = 1; - for (uint32_t i = 0; i < wd->BackBufferCount; i++) + for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { - attachment[0] = wd->BackBufferView[i]; - err = vkCreateFramebuffer(device, &info, allocator, &wd->Framebuffer[i]); + ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; + attachment[0] = fd->BackBufferView; + err = vkCreateFramebuffer(device, &info, allocator, &fd->Framebuffer); check_vk_result(err); } } @@ -1135,15 +1132,7 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I //vkQueueWaitIdle(g_Queue); for (int i = 0; i < wd->Frames.Size; i++) - { - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; - ImGui_ImplVulkanH_DestroyFrameData(instance, device, fd, allocator); - } - for (uint32_t i = 0; i < wd->BackBufferCount; i++) - { - vkDestroyImageView(device, wd->BackBufferView[i], allocator); - vkDestroyFramebuffer(device, wd->Framebuffer[i], allocator); - } + ImGui_ImplVulkanH_DestroyFrameData(instance, device, &wd->Frames[i], allocator); vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); @@ -1158,9 +1147,11 @@ void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, Im vkDestroyCommandPool(device, fd->CommandPool, allocator); vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); - fd->BackbufferIndex = 0; fd->Fence = VK_NULL_HANDLE; fd->CommandBuffer = VK_NULL_HANDLE; fd->CommandPool = VK_NULL_HANDLE; fd->ImageAcquiredSemaphore = fd->RenderCompleteSemaphore = VK_NULL_HANDLE; + + vkDestroyImageView(device, fd->BackBufferView, allocator); + vkDestroyFramebuffer(device, fd->Framebuffer, allocator); } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index f54caf3d..495f6d47 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -27,7 +27,7 @@ struct ImGui_ImplVulkan_InitInfo VkQueue Queue; VkPipelineCache PipelineCache; VkDescriptorPool DescriptorPool; - int QueuedFramesCount; + int FramesQueueSize; // >= 2, generally matches the image count returned by vkGetSwapchainImagesKHR const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); }; @@ -36,7 +36,7 @@ struct ImGui_ImplVulkan_InitInfo IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); -IMGUI_IMPL_API void ImGui_ImplVulkan_SetQueuedFramesCount(int queued_frames_count); // To override QueuedFramesCount after initialization +IMGUI_IMPL_API void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size); // To override FramesQueueSize after initialization IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFontUploadObjects(); @@ -77,12 +77,14 @@ IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresen // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) struct ImGui_ImplVulkanH_FrameData { - uint32_t BackbufferIndex; // Keep track of recently rendered swapchain frame indices VkCommandPool CommandPool; VkCommandBuffer CommandBuffer; VkFence Fence; VkSemaphore ImageAcquiredSemaphore; VkSemaphore RenderCompleteSemaphore; + VkImage BackBuffer; + VkImageView BackBufferView; + VkFramebuffer Framebuffer; IMGUI_IMPL_API ImGui_ImplVulkanH_FrameData(); }; @@ -100,11 +102,8 @@ struct ImGui_ImplVulkanH_WindowData VkRenderPass RenderPass; bool ClearEnable; VkClearValue ClearValue; - uint32_t BackBufferCount; - VkImage BackBuffer[16]; - VkImageView BackBufferView[16]; - VkFramebuffer Framebuffer[16]; - uint32_t FrameIndex; + uint32_t FramesQueueSize; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR) + uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) ImVector Frames; IMGUI_IMPL_API ImGui_ImplVulkanH_WindowData(); From f586764cdd534c9735a918c474f9a0a8b3d747bd Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 18:33:13 +0200 Subject: [PATCH 220/566] Examples: Vulkan: Merged helpers into ImGui_ImplVulkanH_CreateWindowData. Removed ImGui_ImplVulkan_InvalidateFrameDeviceObjects from API. Comments. (#2071) --- examples/example_glfw_vulkan/main.cpp | 11 ++++-- examples/example_sdl_vulkan/main.cpp | 11 ++++-- examples/imgui_impl_vulkan.cpp | 57 ++++++++++++++++++--------- examples/imgui_impl_vulkan.h | 16 +++----- 4 files changed, 59 insertions(+), 36 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index cec1217d..fbb2f499 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -1,6 +1,11 @@ // dear imgui: standalone example application for Glfw + Vulkan // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own application. +// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// - Helper ImGui_ImplVulkanH_XXXX functions and structures are used by this example (main.cpp) and by imgui_impl_vulkan.cpp, +// but should PROBABLY NOT be used by your own app code. Read comments in imgui_impl_vulkan.h. + #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_vulkan.h" @@ -212,8 +217,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); + ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); IM_ASSERT(wd->FramesQueueSize >= 2); } @@ -438,8 +442,7 @@ int main(int, char**) glfwPollEvents(); if (g_WantSwapChainRebuild) { - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); + ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 70ba5a2d..af331302 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -1,6 +1,11 @@ // dear imgui: standalone example application for SDL2 + Vulkan // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own application. +// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// - Helper ImGui_ImplVulkanH_XXXX functions and structures are used by this example (main.cpp) and by imgui_impl_vulkan.cpp, +// but should PROBABLY NOT be used by your own app code. Read comments in imgui_impl_vulkan.h. + #include "imgui.h" #include "imgui_impl_sdl.h" #include "imgui_impl_vulkan.h" @@ -203,8 +208,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, wd, g_Allocator, width, height, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, wd, g_Allocator); + ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); IM_ASSERT(wd->FramesQueueSize >= 2); } @@ -435,8 +439,7 @@ int main(int, char**) if (g_WantSwapChainRebuild) { - ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(g_PhysicalDevice, g_Device, &g_WindowData, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(g_PhysicalDevice, g_Device, g_QueueFamily, &g_WindowData, g_Allocator); + ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 2d6fc373..97a5b9a8 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -78,6 +78,15 @@ static VkImageView g_FontView = VK_NULL_HANDLE; static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE; static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; +// Forward Declarations +void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); + +//----------------------------------------------------------------------------- +// SHADERS +//----------------------------------------------------------------------------- + // glsl_shader.vert, compiled with: // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert /* @@ -183,6 +192,10 @@ static uint32_t __glsl_shader_frag_spv[] = 0x00010038 }; +//----------------------------------------------------------------------------- +// FUNCTIONS +//----------------------------------------------------------------------------- + static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits) { VkPhysicalDeviceMemoryProperties prop; @@ -727,8 +740,22 @@ void ImGui_ImplVulkan_InvalidateFontUploadObjects() } } +static void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() +{ + for (int i = 0; i < g_FramesDataBuffers.Size; i++) + { + FrameDataForRender* fd = &g_FramesDataBuffers[i]; + if (fd->VertexBuffer) { vkDestroyBuffer(g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } + if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; } + if (fd->IndexBuffer) { vkDestroyBuffer(g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } + if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } + } + g_FramesDataBuffers.clear(); +} + void ImGui_ImplVulkan_InvalidateDeviceObjects() { + ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); ImGui_ImplVulkan_InvalidateFontUploadObjects(); if (g_FontView) { vkDestroyImageView(g_Device, g_FontView, g_Allocator); g_FontView = VK_NULL_HANDLE; } @@ -740,19 +767,6 @@ void ImGui_ImplVulkan_InvalidateDeviceObjects() if (g_Pipeline) { vkDestroyPipeline(g_Device, g_Pipeline, g_Allocator); g_Pipeline = VK_NULL_HANDLE; } } -void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() -{ - for (int i = 0; i < g_FramesDataBuffers.Size; i++) - { - FrameDataForRender* fd = &g_FramesDataBuffers[i]; - if (fd->VertexBuffer) { vkDestroyBuffer(g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } - if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; } - if (fd->IndexBuffer) { vkDestroyBuffer(g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } - if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } - } - g_FramesDataBuffers.clear(); -} - bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) { ImGuiIO& io = ImGui::GetIO(); @@ -788,7 +802,6 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend void ImGui_ImplVulkan_Shutdown() { - ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); ImGui_ImplVulkan_InvalidateDeviceObjects(); } @@ -811,6 +824,7 @@ void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size) //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers +// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: @@ -818,9 +832,10 @@ void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size) // 2) the upcoming multi-viewport feature will need them internally. // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, // but it is too much code to duplicate everywhere so we exceptionally expose them. -// Your application/engine will likely already have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). +// +// Your application/engine will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. -// (those functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) +// (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- #include // malloc @@ -917,7 +932,7 @@ VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_d return VK_PRESENT_MODE_FIFO_KHR; // Always available } -void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, uint32_t queue_family, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) { IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); (void)physical_device; @@ -975,7 +990,7 @@ int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_m return 1; } -void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) +void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; @@ -1126,6 +1141,12 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice } } +void ImGui_ImplVulkanH_CreateWindowData(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) +{ + ImGui_ImplVulkanH_CreateWindowDataSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(physical_device, device, wd, queue_family, allocator); +} + void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator) { vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 495f6d47..1fb2711b 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -15,8 +15,6 @@ #include -//#define IMGUI_VK_QUEUED_FRAMES 2 - // Please zero-clear before use. struct ImGui_ImplVulkan_InitInfo { @@ -41,15 +39,14 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, V IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFontUploadObjects(); -// Called by ImGui_ImplVulkan_Init() might be useful elsewhere. +// Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateDeviceObjects(); -IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers -// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) +// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: @@ -57,18 +54,17 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); // 2) the upcoming multi-viewport feature will need them internally. // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, // but it is too much code to duplicate everywhere so we exceptionally expose them. -// Your application/engine will likely already have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). +// +// Your application/engine will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. -// (those functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) +// (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- struct ImGui_ImplVulkanH_FrameData; struct ImGui_ImplVulkanH_WindowData; -IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, uint32_t queue_family, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator); -IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowDataSwapChainAndFramebuffer(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowData(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator); -IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); From 6bf981c85c6045da790c50f17527c8c7f021b4f6 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Apr 2019 19:21:06 +0200 Subject: [PATCH 221/566] Vulkan: More renaming. Comments. --- examples/example_glfw_vulkan/main.cpp | 10 +++++---- examples/example_sdl_vulkan/main.cpp | 10 +++++---- examples/imgui_impl_vulkan.cpp | 29 +++++++++++++++++---------- examples/imgui_impl_vulkan.h | 22 +++++++++++++------- 4 files changed, 45 insertions(+), 26 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index fbb2f499..f9f260d7 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -1,10 +1,12 @@ // dear imgui: standalone example application for Glfw + Vulkan // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. -// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own application. +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. -// - Helper ImGui_ImplVulkanH_XXXX functions and structures are used by this example (main.cpp) and by imgui_impl_vulkan.cpp, -// but should PROBABLY NOT be used by your own app code. Read comments in imgui_impl_vulkan.h. +// You will use those if you want to use this rendering back-end in your engine/app. +// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// Read comments in imgui_impl_vulkan.h. #include "imgui.h" #include "imgui_impl_glfw.h" @@ -424,7 +426,7 @@ int main(int, char**) err = vkDeviceWaitIdle(g_Device); check_vk_result(err); - ImGui_ImplVulkan_InvalidateFontUploadObjects(); + ImGui_ImplVulkan_DestroyFontUploadObjects(); } bool show_demo_window = true; diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index af331302..6c5684e8 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -1,10 +1,12 @@ // dear imgui: standalone example application for SDL2 + Vulkan // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. -// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own application. +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. -// - Helper ImGui_ImplVulkanH_XXXX functions and structures are used by this example (main.cpp) and by imgui_impl_vulkan.cpp, -// but should PROBABLY NOT be used by your own app code. Read comments in imgui_impl_vulkan.h. +// You will use those if you want to use this rendering back-end in your engine/app. +// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// Read comments in imgui_impl_vulkan.h. #include "imgui.h" #include "imgui_impl_sdl.h" @@ -407,7 +409,7 @@ int main(int, char**) err = vkDeviceWaitIdle(g_Device); check_vk_result(err); - ImGui_ImplVulkan_InvalidateFontUploadObjects(); + ImGui_ImplVulkan_DestroyFontUploadObjects(); } bool show_demo_window = true; diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 97a5b9a8..bdf1e661 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -11,6 +11,13 @@ // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. +// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// You will use those if you want to use this rendering back-end in your engine/app. +// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// Read comments in imgui_impl_vulkan.h. + // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2019-XX-XX: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetFramesQueueSize() to override FramesQueueSize while running. @@ -726,7 +733,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() return true; } -void ImGui_ImplVulkan_InvalidateFontUploadObjects() +void ImGui_ImplVulkan_DestroyFontUploadObjects() { if (g_UploadBuffer) { @@ -753,10 +760,10 @@ static void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() g_FramesDataBuffers.clear(); } -void ImGui_ImplVulkan_InvalidateDeviceObjects() +void ImGui_ImplVulkan_DestroyDeviceObjects() { ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); - ImGui_ImplVulkan_InvalidateFontUploadObjects(); + ImGui_ImplVulkan_DestroyFontUploadObjects(); if (g_FontView) { vkDestroyImageView(g_Device, g_FontView, g_Allocator); g_FontView = VK_NULL_HANDLE; } if (g_FontImage) { vkDestroyImage(g_Device, g_FontImage, g_Allocator); g_FontImage = VK_NULL_HANDLE; } @@ -802,7 +809,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend void ImGui_ImplVulkan_Shutdown() { - ImGui_ImplVulkan_InvalidateDeviceObjects(); + ImGui_ImplVulkan_DestroyDeviceObjects(); } void ImGui_ImplVulkan_NewFrame() @@ -847,8 +854,8 @@ ImGui_ImplVulkanH_FrameData::ImGui_ImplVulkanH_FrameData() Fence = VK_NULL_HANDLE; ImageAcquiredSemaphore = VK_NULL_HANDLE; RenderCompleteSemaphore = VK_NULL_HANDLE; - BackBuffer = VK_NULL_HANDLE; - BackBufferView = VK_NULL_HANDLE; + Backbuffer = VK_NULL_HANDLE; + BackbufferView = VK_NULL_HANDLE; Framebuffer = VK_NULL_HANDLE; } @@ -1056,7 +1063,7 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_devic for (int i = 0; i < (int)wd->FramesQueueSize; i++) { wd->Frames.push_back(ImGui_ImplVulkanH_FrameData()); - wd->Frames[i].BackBuffer = backbuffers[i]; + wd->Frames[i].Backbuffer = backbuffers[i]; } } if (old_swapchain) @@ -1114,8 +1121,8 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_devic for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; - info.image = fd->BackBuffer; - err = vkCreateImageView(device, &info, allocator, &fd->BackBufferView); + info.image = fd->Backbuffer; + err = vkCreateImageView(device, &info, allocator, &fd->BackbufferView); check_vk_result(err); } } @@ -1134,7 +1141,7 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_devic for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; - attachment[0] = fd->BackBufferView; + attachment[0] = fd->BackbufferView; err = vkCreateFramebuffer(device, &info, allocator, &fd->Framebuffer); check_vk_result(err); } @@ -1173,6 +1180,6 @@ void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, Im fd->CommandPool = VK_NULL_HANDLE; fd->ImageAcquiredSemaphore = fd->RenderCompleteSemaphore = VK_NULL_HANDLE; - vkDestroyImageView(device, fd->BackBufferView, allocator); + vkDestroyImageView(device, fd->BackbufferView, allocator); vkDestroyFramebuffer(device, fd->Framebuffer, allocator); } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 1fb2711b..6306f30e 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -11,11 +11,19 @@ // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ +// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. +// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// You will use those if you want to use this rendering back-end in your engine/app. +// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// Read comments in imgui_impl_vulkan.h. + #pragma once #include -// Please zero-clear before use. +// Initialization data, for ImGui_ImplVulkan_Init() +// [Please zero-clear before use!] struct ImGui_ImplVulkan_InitInfo { VkInstance Instance; @@ -37,16 +45,16 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); IMGUI_IMPL_API void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size); // To override FramesQueueSize after initialization IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); -IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateFontUploadObjects(); +IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); // Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); -IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyDeviceObjects(); //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers -// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.) +// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: @@ -55,7 +63,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_InvalidateDeviceObjects(); // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, // but it is too much code to duplicate everywhere so we exceptionally expose them. // -// Your application/engine will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). +// Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- @@ -78,8 +86,8 @@ struct ImGui_ImplVulkanH_FrameData VkFence Fence; VkSemaphore ImageAcquiredSemaphore; VkSemaphore RenderCompleteSemaphore; - VkImage BackBuffer; - VkImageView BackBufferView; + VkImage Backbuffer; + VkImageView BackbufferView; VkFramebuffer Framebuffer; IMGUI_IMPL_API ImGui_ImplVulkanH_FrameData(); From 66f4be2e13105d7ae636eff161ff1644275227bd Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 4 Apr 2019 22:27:29 +0200 Subject: [PATCH 222/566] Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). User is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. Removed ImGui_ImplVulkan_SetFramesQueueSize. (#2461, #2348, #2378, #2097, #2071, #1677) --- docs/CHANGELOG.txt | 10 +- examples/example_glfw_vulkan/main.cpp | 7 +- examples/example_sdl_vulkan/main.cpp | 7 +- examples/imgui_impl_vulkan.cpp | 180 ++++++++++---------------- examples/imgui_impl_vulkan.h | 37 ++++-- 5 files changed, 111 insertions(+), 130 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6046f19b..0b3ed421 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -34,6 +34,13 @@ HOW TO UPDATE? ----------------------------------------------------------------------- Breaking Changes: +- Examples: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is + in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. + (The demo helper ImGui_ImplVulkanH_WindowData structure carries them.) (#2461, #2348, #2378, #2097) +- Examples: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required during + initialization to specify the number of in-flight image required by the swap chain. + (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071, #1677) [@nathanvoglsam] + Other Changes: - InputText: Fixed selection background starts rendering one frame after the cursor movement @@ -49,9 +56,6 @@ Other Changes: - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. -- Examples: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required during - initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071) [@nathanvoglsam] - Added ImGui_ImplVulkan_SetFramesQueueSize() to override FramesQueueSize while running. - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] - Examples: GLUT: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. (#2465) [@andrewwillmott] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index f9f260d7..037d4791 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -115,6 +115,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) uint32_t gpu_count; err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, NULL); check_vk_result(err); + IM_ASSERT(gpu_count > 0); VkPhysicalDevice* gpus = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * gpu_count); err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus); @@ -219,7 +220,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); IM_ASSERT(wd->FramesQueueSize >= 2); } @@ -277,7 +278,7 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) } // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer, &fd->RenderBuffers); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -444,7 +445,7 @@ int main(int, char**) glfwPollEvents(); if (g_WantSwapChainRebuild) { - ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 6c5684e8..e4721943 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -106,6 +106,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) uint32_t gpu_count; err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, NULL); check_vk_result(err); + IM_ASSERT(gpu_count > 0); VkPhysicalDevice* gpus = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * gpu_count); err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus); @@ -210,7 +211,7 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); IM_ASSERT(wd->FramesQueueSize >= 2); } @@ -268,7 +269,7 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) } // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer, &fd->RenderBuffers); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -441,7 +442,7 @@ int main(int, char**) if (g_WantSwapChainRebuild) { - ImGui_ImplVulkanH_CreateWindowData(g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); + ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index bdf1e661..61351679 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -20,7 +20,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-XX-XX: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetFramesQueueSize() to override FramesQueueSize while running. +// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. (The demo helper ImGui_ImplVulkanH_WindowData structure carries them.) +// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetFramesQueueSize() to override FramesQueueSize while running. +// 2019-XX-XX: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindowData() optional helper. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. @@ -44,51 +46,37 @@ // Vulkan data static const VkAllocationCallbacks* g_Allocator = NULL; -static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; -static VkInstance g_Instance = VK_NULL_HANDLE; -static VkDevice g_Device = VK_NULL_HANDLE; -static uint32_t g_QueueFamily = (uint32_t)-1; -static VkQueue g_Queue = VK_NULL_HANDLE; -static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; -static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; -static VkRenderPass g_RenderPass = VK_NULL_HANDLE; -static void (*g_CheckVkResultFn)(VkResult err) = NULL; - -static VkDeviceSize g_BufferMemoryAlignment = 256; -static VkPipelineCreateFlags g_PipelineCreateFlags = 0; - -static VkDescriptorSetLayout g_DescriptorSetLayout = VK_NULL_HANDLE; -static VkPipelineLayout g_PipelineLayout = VK_NULL_HANDLE; -static VkDescriptorSet g_DescriptorSet = VK_NULL_HANDLE; -static VkPipeline g_Pipeline = VK_NULL_HANDLE; - -// Frame data -struct FrameDataForRender -{ - VkDeviceMemory VertexBufferMemory; - VkDeviceMemory IndexBufferMemory; - VkDeviceSize VertexBufferSize; - VkDeviceSize IndexBufferSize; - VkBuffer VertexBuffer; - VkBuffer IndexBuffer; - - FrameDataForRender() { VertexBufferMemory = IndexBufferMemory = VK_NULL_HANDLE; VertexBufferSize = IndexBufferSize = VK_NULL_HANDLE; VertexBuffer = IndexBuffer = VK_NULL_HANDLE; } -}; -static int g_FrameIndex = 0; -static ImVector g_FramesDataBuffers; +static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; +static VkInstance g_Instance = VK_NULL_HANDLE; +static VkDevice g_Device = VK_NULL_HANDLE; +static uint32_t g_QueueFamily = (uint32_t)-1; +static VkQueue g_Queue = VK_NULL_HANDLE; +static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; +static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; +static int g_FramesQueueSize = 0; +static VkRenderPass g_RenderPass = VK_NULL_HANDLE; +static void (*g_CheckVkResultFn)(VkResult err) = NULL; + +static VkDeviceSize g_BufferMemoryAlignment = 256; +static VkPipelineCreateFlags g_PipelineCreateFlags = 0x00; +static VkDescriptorSetLayout g_DescriptorSetLayout = VK_NULL_HANDLE; +static VkPipelineLayout g_PipelineLayout = VK_NULL_HANDLE; +static VkDescriptorSet g_DescriptorSet = VK_NULL_HANDLE; +static VkPipeline g_Pipeline = VK_NULL_HANDLE; // Font data -static VkSampler g_FontSampler = VK_NULL_HANDLE; -static VkDeviceMemory g_FontMemory = VK_NULL_HANDLE; -static VkImage g_FontImage = VK_NULL_HANDLE; -static VkImageView g_FontView = VK_NULL_HANDLE; -static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE; -static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; +static VkSampler g_FontSampler = VK_NULL_HANDLE; +static VkDeviceMemory g_FontMemory = VK_NULL_HANDLE; +static VkImage g_FontImage = VK_NULL_HANDLE; +static VkImageView g_FontView = VK_NULL_HANDLE; +static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE; +static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; // Forward Declarations void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); -void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* frb, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); //----------------------------------------------------------------------------- // SHADERS @@ -253,7 +241,7 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) -void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer) +void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* fd) { // 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); @@ -262,8 +250,6 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm return; VkResult err; - FrameDataForRender* fd = &g_FramesDataBuffers[g_FrameIndex]; - g_FrameIndex = (g_FrameIndex + 1) % g_FramesDataBuffers.Size; // Create the Vertex and Index buffers: size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); @@ -747,22 +733,8 @@ void ImGui_ImplVulkan_DestroyFontUploadObjects() } } -static void ImGui_ImplVulkan_InvalidateFrameDeviceObjects() -{ - for (int i = 0; i < g_FramesDataBuffers.Size; i++) - { - FrameDataForRender* fd = &g_FramesDataBuffers[i]; - if (fd->VertexBuffer) { vkDestroyBuffer(g_Device, fd->VertexBuffer, g_Allocator); fd->VertexBuffer = VK_NULL_HANDLE; } - if (fd->VertexBufferMemory) { vkFreeMemory (g_Device, fd->VertexBufferMemory, g_Allocator); fd->VertexBufferMemory = VK_NULL_HANDLE; } - if (fd->IndexBuffer) { vkDestroyBuffer(g_Device, fd->IndexBuffer, g_Allocator); fd->IndexBuffer = VK_NULL_HANDLE; } - if (fd->IndexBufferMemory) { vkFreeMemory (g_Device, fd->IndexBufferMemory, g_Allocator); fd->IndexBufferMemory = VK_NULL_HANDLE; } - } - g_FramesDataBuffers.clear(); -} - void ImGui_ImplVulkan_DestroyDeviceObjects() { - ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); ImGui_ImplVulkan_DestroyFontUploadObjects(); if (g_FontView) { vkDestroyImageView(g_Device, g_FontView, g_Allocator); g_FontView = VK_NULL_HANDLE; } @@ -795,13 +767,10 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend g_RenderPass = render_pass; g_PipelineCache = info->PipelineCache; g_DescriptorPool = info->DescriptorPool; + g_FramesQueueSize = info->FramesQueueSize; g_Allocator = info->Allocator; g_CheckVkResultFn = info->CheckVkResultFn; - g_FramesDataBuffers.reserve(info->FramesQueueSize); - for (int i = 0; i < info->FramesQueueSize; i++) - g_FramesDataBuffers.push_back(FrameDataForRender()); - ImGui_ImplVulkan_CreateDeviceObjects(); return true; @@ -818,14 +787,7 @@ void ImGui_ImplVulkan_NewFrame() void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size) { - if (frames_queue_size == g_FramesDataBuffers.Size) - return; - ImGui_ImplVulkan_InvalidateFrameDeviceObjects(); - - g_FrameIndex = 0; - g_FramesDataBuffers.reserve(frames_queue_size); - for (int i = 0; i < frames_queue_size; i++) - g_FramesDataBuffers.push_back(FrameDataForRender()); + (void)frames_queue_size; } @@ -840,39 +802,13 @@ void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size) // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, // but it is too much code to duplicate everywhere so we exceptionally expose them. // -// Your application/engine will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). +// Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- #include // malloc -ImGui_ImplVulkanH_FrameData::ImGui_ImplVulkanH_FrameData() -{ - CommandPool = VK_NULL_HANDLE; - CommandBuffer = VK_NULL_HANDLE; - Fence = VK_NULL_HANDLE; - ImageAcquiredSemaphore = VK_NULL_HANDLE; - RenderCompleteSemaphore = VK_NULL_HANDLE; - Backbuffer = VK_NULL_HANDLE; - BackbufferView = VK_NULL_HANDLE; - Framebuffer = VK_NULL_HANDLE; -} - -ImGui_ImplVulkanH_WindowData::ImGui_ImplVulkanH_WindowData() -{ - Width = Height = 0; - Swapchain = VK_NULL_HANDLE; - Surface = VK_NULL_HANDLE; - memset(&SurfaceFormat, 0, sizeof(SurfaceFormat)); - PresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR; - RenderPass = VK_NULL_HANDLE; - ClearEnable = true; - memset(&ClearValue, 0, sizeof(ClearValue)); - FramesQueueSize = 0; - FrameIndex = 0; -} - VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space) { IM_ASSERT(request_formats != NULL); @@ -939,15 +875,16 @@ VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_d return VK_PRESENT_MODE_FIFO_KHR; // Always available } -void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) { - IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); + IM_ASSERT(instance != VK_NULL_HANDLE && physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); + (void)instance; (void)physical_device; (void)allocator; // Create Command Buffers VkResult err; - for (int i = 0; i < wd->Frames.Size; i++) + for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; { @@ -985,6 +922,7 @@ void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkPhysicalDevice physical_ } } +// MinImageCount will usually turn into FramesQueueSize int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode) { if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR) @@ -997,17 +935,20 @@ int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_m return 1; } -void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) +// Also destroy old swap chain and in-flight frames data, if any. +void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; err = vkDeviceWaitIdle(device); check_vk_result(err); + // We don't use ImGui_ImplVulkanH_DestroyWindowData() because we want to preserve the old swapchain to create the new one. // Destroy old Framebuffer for (uint32_t i = 0; i < wd->FramesQueueSize; i++) - ImGui_ImplVulkanH_DestroyFrameData(g_Instance, device, &wd->Frames[i], allocator); - wd->Frames.clear(); + ImGui_ImplVulkanH_DestroyFrameData(instance, device, &wd->Frames[i], allocator); + delete[] wd->Frames; + wd->Frames = NULL; wd->FramesQueueSize = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1059,12 +1000,11 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_devic err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->FramesQueueSize, backbuffers); check_vk_result(err); - wd->Frames.reserve((int)wd->FramesQueueSize); - for (int i = 0; i < (int)wd->FramesQueueSize; i++) - { - wd->Frames.push_back(ImGui_ImplVulkanH_FrameData()); + IM_ASSERT(wd->Frames == NULL); + wd->Frames = new ImGui_ImplVulkanH_FrameData[wd->FramesQueueSize]; + memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->FramesQueueSize); + for (uint32_t i = 0; i < wd->FramesQueueSize; i++) wd->Frames[i].Backbuffer = backbuffers[i]; - } } if (old_swapchain) vkDestroySwapchainKHR(device, old_swapchain, allocator); @@ -1148,10 +1088,10 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkPhysicalDevice physical_devic } } -void ImGui_ImplVulkanH_CreateWindowData(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) +void ImGui_ImplVulkanH_CreateWindowData(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) { - ImGui_ImplVulkanH_CreateWindowDataSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(physical_device, device, wd, queue_family, allocator); + ImGui_ImplVulkanH_CreateWindowDataSwapChain(instance, physical_device, device, wd, allocator, width, height, min_image_count); + ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(instance, physical_device, device, wd, queue_family, allocator); } void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator) @@ -1159,11 +1099,14 @@ void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, I vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(g_Queue); - for (int i = 0; i < wd->Frames.Size; i++) + for (uint32_t i = 0; i < wd->FramesQueueSize; i++) ImGui_ImplVulkanH_DestroyFrameData(instance, device, &wd->Frames[i], allocator); + delete[] wd->Frames; + wd->Frames = NULL; vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); + *wd = ImGui_ImplVulkanH_WindowData(); } @@ -1182,4 +1125,17 @@ void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, Im vkDestroyImageView(device, fd->BackbufferView, allocator); vkDestroyFramebuffer(device, fd->Framebuffer, allocator); + + ImGui_ImplVulkanH_DestroyFrameRenderBuffers(instance, device, &fd->RenderBuffers, allocator); +} + +void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* frb, const VkAllocationCallbacks* allocator) +{ + (void)instance; + if (frb->VertexBuffer) { vkDestroyBuffer(device, frb->VertexBuffer, allocator); frb->VertexBuffer = VK_NULL_HANDLE; } + if (frb->VertexBufferMemory) { vkFreeMemory (device, frb->VertexBufferMemory, allocator); frb->VertexBufferMemory = VK_NULL_HANDLE; } + if (frb->IndexBuffer) { vkDestroyBuffer(device, frb->IndexBuffer, allocator); frb->IndexBuffer = VK_NULL_HANDLE; } + if (frb->IndexBufferMemory) { vkFreeMemory (device, frb->IndexBufferMemory, allocator); frb->IndexBufferMemory = VK_NULL_HANDLE; } + frb->VertexBufferSize = 0; + frb->IndexBufferSize = 0; } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 6306f30e..334910f6 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -38,12 +38,26 @@ struct ImGui_ImplVulkan_InitInfo void (*CheckVkResultFn)(VkResult err); }; +// Reusable buffers used for rendering by current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() +// [Please zero-clear before use!] +// In the examples we store those in the helper ImGui_ImplVulkanH_FrameData structure, however as your own engine/app likely won't use the ImGui_Impl_VulkanH_XXXX helpers, +// you are expected to hold on as many ImGui_ImplVulkan_FrameRenderBuffers structures on your side as you have in-flight frames (== init_info.FramesQueueSize) +struct ImGui_ImplVulkan_FrameRenderBuffers +{ + VkDeviceMemory VertexBufferMemory; + VkDeviceMemory IndexBufferMemory; + VkDeviceSize VertexBufferSize; + VkDeviceSize IndexBufferSize; + VkBuffer VertexBuffer; + VkBuffer IndexBuffer; +}; + // Called by user code IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); IMGUI_IMPL_API void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size); // To override FramesQueueSize after initialization -IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); +IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* buffers); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); @@ -71,7 +85,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyDeviceObjects(); struct ImGui_ImplVulkanH_FrameData; struct ImGui_ImplVulkanH_WindowData; -IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowData(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowData(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); @@ -79,6 +93,7 @@ IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresen // Helper structure to hold the data needed by one rendering frame // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) +// [Please zero-clear before use!] struct ImGui_ImplVulkanH_FrameData { VkCommandPool CommandPool; @@ -89,8 +104,7 @@ struct ImGui_ImplVulkanH_FrameData VkImage Backbuffer; VkImageView BackbufferView; VkFramebuffer Framebuffer; - - IMGUI_IMPL_API ImGui_ImplVulkanH_FrameData(); + ImGui_ImplVulkan_FrameRenderBuffers RenderBuffers; }; // Helper structure to hold the data needed by one rendering context into one OS window @@ -106,10 +120,15 @@ struct ImGui_ImplVulkanH_WindowData VkRenderPass RenderPass; bool ClearEnable; VkClearValue ClearValue; - uint32_t FramesQueueSize; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR) - uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) - ImVector Frames; - - IMGUI_IMPL_API ImGui_ImplVulkanH_WindowData(); + uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) + uint32_t FramesQueueSize; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) + ImGui_ImplVulkanH_FrameData* Frames; + + ImGui_ImplVulkanH_WindowData() + { + memset(this, 0, sizeof(*this)); + PresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR; + ClearEnable = true; + } }; From 86f5945f497c42a665c8184edf04fb831c279ecb Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 4 Apr 2019 22:36:12 +0200 Subject: [PATCH 223/566] Vulkan: Storing user info into a single g_VulkanInitInfo structure to simplify code. --- examples/imgui_impl_vulkan.cpp | 126 +++++++++++++++------------------ 1 file changed, 57 insertions(+), 69 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 61351679..25b6428b 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -45,18 +45,8 @@ #include // Vulkan data -static const VkAllocationCallbacks* g_Allocator = NULL; -static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; -static VkInstance g_Instance = VK_NULL_HANDLE; -static VkDevice g_Device = VK_NULL_HANDLE; -static uint32_t g_QueueFamily = (uint32_t)-1; -static VkQueue g_Queue = VK_NULL_HANDLE; -static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; -static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; -static int g_FramesQueueSize = 0; +static ImGui_ImplVulkan_InitInfo g_VulkanInitInfo = {}; static VkRenderPass g_RenderPass = VK_NULL_HANDLE; -static void (*g_CheckVkResultFn)(VkResult err) = NULL; - static VkDeviceSize g_BufferMemoryAlignment = 256; static VkPipelineCreateFlags g_PipelineCreateFlags = 0x00; static VkDescriptorSetLayout g_DescriptorSetLayout = VK_NULL_HANDLE; @@ -193,8 +183,9 @@ static uint32_t __glsl_shader_frag_spv[] = static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits) { + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkPhysicalDeviceMemoryProperties prop; - vkGetPhysicalDeviceMemoryProperties(g_PhysicalDevice, &prop); + vkGetPhysicalDeviceMemoryProperties(v->PhysicalDevice, &prop); for (uint32_t i = 0; i < prop.memoryTypeCount; i++) if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<CheckVkResultFn) + v->CheckVkResultFn(err); } static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& p_buffer_size, size_t new_size, VkBufferUsageFlagBits usage) { + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err; if (buffer != VK_NULL_HANDLE) - vkDestroyBuffer(g_Device, buffer, g_Allocator); + vkDestroyBuffer(v->Device, buffer, v->Allocator); if (buffer_memory) - vkFreeMemory(g_Device, buffer_memory, g_Allocator); + vkFreeMemory(v->Device, buffer_memory, v->Allocator); VkDeviceSize vertex_buffer_size_aligned = ((new_size - 1) / g_BufferMemoryAlignment + 1) * g_BufferMemoryAlignment; VkBufferCreateInfo buffer_info = {}; @@ -221,20 +214,20 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory buffer_info.size = vertex_buffer_size_aligned; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - err = vkCreateBuffer(g_Device, &buffer_info, g_Allocator, &buffer); + err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer); check_vk_result(err); VkMemoryRequirements req; - vkGetBufferMemoryRequirements(g_Device, buffer, &req); + vkGetBufferMemoryRequirements(v->Device, buffer, &req); g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment; VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = req.size; alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); - err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &buffer_memory); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &buffer_memory); check_vk_result(err); - err = vkBindBufferMemory(g_Device, buffer, buffer_memory, 0); + err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0); check_vk_result(err); p_buffer_size = new_size; } @@ -249,6 +242,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount == 0) return; + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err; // Create the Vertex and Index buffers: @@ -263,9 +257,9 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm { ImDrawVert* vtx_dst = NULL; ImDrawIdx* idx_dst = NULL; - err = vkMapMemory(g_Device, fd->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); + err = vkMapMemory(v->Device, fd->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); check_vk_result(err); - err = vkMapMemory(g_Device, fd->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst)); + err = vkMapMemory(v->Device, fd->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst)); check_vk_result(err); for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -282,10 +276,10 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range[1].memory = fd->IndexBufferMemory; range[1].size = VK_WHOLE_SIZE; - err = vkFlushMappedMemoryRanges(g_Device, 2, range); + err = vkFlushMappedMemoryRanges(v->Device, 2, range); check_vk_result(err); - vkUnmapMemory(g_Device, fd->VertexBufferMemory); - vkUnmapMemory(g_Device, fd->IndexBufferMemory); + vkUnmapMemory(v->Device, fd->VertexBufferMemory); + vkUnmapMemory(v->Device, fd->IndexBufferMemory); } // Bind pipeline and descriptor sets: @@ -383,6 +377,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) { + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; @@ -408,17 +403,17 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - err = vkCreateImage(g_Device, &info, g_Allocator, &g_FontImage); + err = vkCreateImage(v->Device, &info, v->Allocator, &g_FontImage); check_vk_result(err); VkMemoryRequirements req; - vkGetImageMemoryRequirements(g_Device, g_FontImage, &req); + vkGetImageMemoryRequirements(v->Device, g_FontImage, &req); VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = req.size; alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits); - err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &g_FontMemory); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &g_FontMemory); check_vk_result(err); - err = vkBindImageMemory(g_Device, g_FontImage, g_FontMemory, 0); + err = vkBindImageMemory(v->Device, g_FontImage, g_FontMemory, 0); check_vk_result(err); } @@ -432,7 +427,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; info.subresourceRange.levelCount = 1; info.subresourceRange.layerCount = 1; - err = vkCreateImageView(g_Device, &info, g_Allocator, &g_FontView); + err = vkCreateImageView(v->Device, &info, v->Allocator, &g_FontView); check_vk_result(err); } @@ -448,7 +443,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) write_desc[0].descriptorCount = 1; write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; write_desc[0].pImageInfo = desc_image; - vkUpdateDescriptorSets(g_Device, 1, write_desc, 0, NULL); + vkUpdateDescriptorSets(v->Device, 1, write_desc, 0, NULL); } // Create the Upload Buffer: @@ -458,34 +453,34 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) buffer_info.size = upload_size; buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - err = vkCreateBuffer(g_Device, &buffer_info, g_Allocator, &g_UploadBuffer); + err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &g_UploadBuffer); check_vk_result(err); VkMemoryRequirements req; - vkGetBufferMemoryRequirements(g_Device, g_UploadBuffer, &req); + vkGetBufferMemoryRequirements(v->Device, g_UploadBuffer, &req); g_BufferMemoryAlignment = (g_BufferMemoryAlignment > req.alignment) ? g_BufferMemoryAlignment : req.alignment; VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = req.size; alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); - err = vkAllocateMemory(g_Device, &alloc_info, g_Allocator, &g_UploadBufferMemory); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &g_UploadBufferMemory); check_vk_result(err); - err = vkBindBufferMemory(g_Device, g_UploadBuffer, g_UploadBufferMemory, 0); + err = vkBindBufferMemory(v->Device, g_UploadBuffer, g_UploadBufferMemory, 0); check_vk_result(err); } // Upload to Buffer: { char* map = NULL; - err = vkMapMemory(g_Device, g_UploadBufferMemory, 0, upload_size, 0, (void**)(&map)); + err = vkMapMemory(v->Device, g_UploadBufferMemory, 0, upload_size, 0, (void**)(&map)); check_vk_result(err); memcpy(map, pixels, upload_size); VkMappedMemoryRange range[1] = {}; range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range[0].memory = g_UploadBufferMemory; range[0].size = upload_size; - err = vkFlushMappedMemoryRanges(g_Device, 1, range); + err = vkFlushMappedMemoryRanges(v->Device, 1, range); check_vk_result(err); - vkUnmapMemory(g_Device, g_UploadBufferMemory); + vkUnmapMemory(v->Device, g_UploadBufferMemory); } // Copy to Image: @@ -534,6 +529,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) bool ImGui_ImplVulkan_CreateDeviceObjects() { + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err; VkShaderModule vert_module; VkShaderModule frag_module; @@ -544,13 +540,13 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; vert_info.codeSize = sizeof(__glsl_shader_vert_spv); vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; - err = vkCreateShaderModule(g_Device, &vert_info, g_Allocator, &vert_module); + err = vkCreateShaderModule(v->Device, &vert_info, v->Allocator, &vert_module); check_vk_result(err); VkShaderModuleCreateInfo frag_info = {}; frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; frag_info.codeSize = sizeof(__glsl_shader_frag_spv); frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; - err = vkCreateShaderModule(g_Device, &frag_info, g_Allocator, &frag_module); + err = vkCreateShaderModule(v->Device, &frag_info, v->Allocator, &frag_module); check_vk_result(err); } @@ -567,7 +563,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() info.minLod = -1000; info.maxLod = 1000; info.maxAnisotropy = 1.0f; - err = vkCreateSampler(g_Device, &info, g_Allocator, &g_FontSampler); + err = vkCreateSampler(v->Device, &info, v->Allocator, &g_FontSampler); check_vk_result(err); } @@ -583,7 +579,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; info.bindingCount = 1; info.pBindings = binding; - err = vkCreateDescriptorSetLayout(g_Device, &info, g_Allocator, &g_DescriptorSetLayout); + err = vkCreateDescriptorSetLayout(v->Device, &info, v->Allocator, &g_DescriptorSetLayout); check_vk_result(err); } @@ -591,10 +587,10 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() { VkDescriptorSetAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - alloc_info.descriptorPool = g_DescriptorPool; + alloc_info.descriptorPool = v->DescriptorPool; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = &g_DescriptorSetLayout; - err = vkAllocateDescriptorSets(g_Device, &alloc_info, &g_DescriptorSet); + err = vkAllocateDescriptorSets(v->Device, &alloc_info, &g_DescriptorSet); check_vk_result(err); } @@ -612,7 +608,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() layout_info.pSetLayouts = set_layout; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = push_constants; - err = vkCreatePipelineLayout(g_Device, &layout_info, g_Allocator, &g_PipelineLayout); + err = vkCreatePipelineLayout(v->Device, &layout_info, v->Allocator, &g_PipelineLayout); check_vk_result(err); } @@ -710,40 +706,42 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() info.pDynamicState = &dynamic_state; info.layout = g_PipelineLayout; info.renderPass = g_RenderPass; - err = vkCreateGraphicsPipelines(g_Device, g_PipelineCache, 1, &info, g_Allocator, &g_Pipeline); + err = vkCreateGraphicsPipelines(v->Device, v->PipelineCache, 1, &info, v->Allocator, &g_Pipeline); check_vk_result(err); - vkDestroyShaderModule(g_Device, vert_module, g_Allocator); - vkDestroyShaderModule(g_Device, frag_module, g_Allocator); + vkDestroyShaderModule(v->Device, vert_module, v->Allocator); + vkDestroyShaderModule(v->Device, frag_module, v->Allocator); return true; } void ImGui_ImplVulkan_DestroyFontUploadObjects() { + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; if (g_UploadBuffer) { - vkDestroyBuffer(g_Device, g_UploadBuffer, g_Allocator); + vkDestroyBuffer(v->Device, g_UploadBuffer, v->Allocator); g_UploadBuffer = VK_NULL_HANDLE; } if (g_UploadBufferMemory) { - vkFreeMemory(g_Device, g_UploadBufferMemory, g_Allocator); + vkFreeMemory(v->Device, g_UploadBufferMemory, v->Allocator); g_UploadBufferMemory = VK_NULL_HANDLE; } } void ImGui_ImplVulkan_DestroyDeviceObjects() { - ImGui_ImplVulkan_DestroyFontUploadObjects(); + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; - if (g_FontView) { vkDestroyImageView(g_Device, g_FontView, g_Allocator); g_FontView = VK_NULL_HANDLE; } - if (g_FontImage) { vkDestroyImage(g_Device, g_FontImage, g_Allocator); g_FontImage = VK_NULL_HANDLE; } - if (g_FontMemory) { vkFreeMemory(g_Device, g_FontMemory, g_Allocator); g_FontMemory = VK_NULL_HANDLE; } - if (g_FontSampler) { vkDestroySampler(g_Device, g_FontSampler, g_Allocator); g_FontSampler = VK_NULL_HANDLE; } - if (g_DescriptorSetLayout) { vkDestroyDescriptorSetLayout(g_Device, g_DescriptorSetLayout, g_Allocator); g_DescriptorSetLayout = VK_NULL_HANDLE; } - if (g_PipelineLayout) { vkDestroyPipelineLayout(g_Device, g_PipelineLayout, g_Allocator); g_PipelineLayout = VK_NULL_HANDLE; } - if (g_Pipeline) { vkDestroyPipeline(g_Device, g_Pipeline, g_Allocator); g_Pipeline = VK_NULL_HANDLE; } + ImGui_ImplVulkan_DestroyFontUploadObjects(); + if (g_FontView) { vkDestroyImageView(v->Device, g_FontView, v->Allocator); g_FontView = VK_NULL_HANDLE; } + if (g_FontImage) { vkDestroyImage(v->Device, g_FontImage, v->Allocator); g_FontImage = VK_NULL_HANDLE; } + if (g_FontMemory) { vkFreeMemory(v->Device, g_FontMemory, v->Allocator); g_FontMemory = VK_NULL_HANDLE; } + if (g_FontSampler) { vkDestroySampler(v->Device, g_FontSampler, v->Allocator); g_FontSampler = VK_NULL_HANDLE; } + if (g_DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, g_DescriptorSetLayout, v->Allocator); g_DescriptorSetLayout = VK_NULL_HANDLE; } + if (g_PipelineLayout) { vkDestroyPipelineLayout(v->Device, g_PipelineLayout, v->Allocator); g_PipelineLayout = VK_NULL_HANDLE; } + if (g_Pipeline) { vkDestroyPipeline(v->Device, g_Pipeline, v->Allocator); g_Pipeline = VK_NULL_HANDLE; } } bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) @@ -759,18 +757,8 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend IM_ASSERT(info->FramesQueueSize >= 2); IM_ASSERT(render_pass != VK_NULL_HANDLE); - g_Instance = info->Instance; - g_PhysicalDevice = info->PhysicalDevice; - g_Device = info->Device; - g_QueueFamily = info->QueueFamily; - g_Queue = info->Queue; + g_VulkanInitInfo = *info; g_RenderPass = render_pass; - g_PipelineCache = info->PipelineCache; - g_DescriptorPool = info->DescriptorPool; - g_FramesQueueSize = info->FramesQueueSize; - g_Allocator = info->Allocator; - g_CheckVkResultFn = info->CheckVkResultFn; - ImGui_ImplVulkan_CreateDeviceObjects(); return true; From 4f54a527ab047f7d668b978b2589c74cf66d2a24 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 4 Apr 2019 23:11:15 +0200 Subject: [PATCH 224/566] Vulkan: Renaming, we want InitInfo to source MinImageCount which is the "source" value (so viewport creation can use this). Made ImGui_ImplVulkan_DestroyFrameRenderBuffers public. (#2071) --- docs/CHANGELOG.txt | 4 +-- examples/example_glfw_vulkan/main.cpp | 21 ++++++++++----- examples/example_sdl_vulkan/main.cpp | 21 ++++++++++----- examples/imgui_impl_vulkan.cpp | 38 +++++++++++++++------------ examples/imgui_impl_vulkan.h | 5 ++-- 5 files changed, 56 insertions(+), 33 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0b3ed421..b4f17df9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,8 +37,8 @@ Breaking Changes: - Examples: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. (The demo helper ImGui_ImplVulkanH_WindowData structure carries them.) (#2461, #2348, #2378, #2097) -- Examples: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required during - initialization to specify the number of in-flight image required by the swap chain. +- Examples: Vulkan: Added MinImageCount field in ImGui_ImplVulkan_InitInfo, required during + initialization to specify the number of in-flight image requested by swap chains. (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071, #1677) [@nathanvoglsam] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 037d4791..ae6bb661 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -192,7 +192,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) } } -static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR surface, int width, int height) +static void SetupVulkanWindow(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; @@ -226,8 +226,6 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR static void CleanupVulkan() { - ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; - ImGui_ImplVulkanH_DestroyWindowData(g_Instance, g_Device, wd, g_Allocator); vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); #ifdef IMGUI_VULKAN_DEBUG_REPORT @@ -240,6 +238,15 @@ static void CleanupVulkan() vkDestroyInstance(g_Instance, g_Allocator); } +static void CleanupVulkanWindow() +{ + // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_WindowData helpers, + // however you would instead need to call ImGui_ImplVulkan_DestroyFrameRenderBuffers() on each + // ImGui_ImplVulkan_FrameRenderBuffers structure that you own. + ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; + ImGui_ImplVulkanH_DestroyWindowData(g_Instance, g_Device, wd, g_Allocator); +} + static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) { VkResult err; @@ -357,7 +364,7 @@ int main(int, char**) glfwGetFramebufferSize(window, &w, &h); glfwSetFramebufferSizeCallback(window, glfw_resize_callback); ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; - SetupVulkanWindowData(wd, surface, w, h); + SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context IMGUI_CHECKVERSION(); @@ -381,7 +388,7 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; - init_info.FramesQueueSize = wd->FramesQueueSize; + init_info.MinImageCount = g_MinImageCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); @@ -446,7 +453,7 @@ int main(int, char**) if (g_WantSwapChainRebuild) { ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); - ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); + ImGui_ImplVulkan_SetSwapChainMinImageCount(g_MinImageCount); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; } @@ -507,6 +514,8 @@ int main(int, char**) ImGui_ImplVulkan_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); + + CleanupVulkanWindow(); CleanupVulkan(); glfwDestroyWindow(window); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index e4721943..58d34448 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -183,7 +183,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) } } -static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR surface, int width, int height) +static void SetupVulkanWindow(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; @@ -217,8 +217,6 @@ static void SetupVulkanWindowData(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR static void CleanupVulkan() { - ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; - ImGui_ImplVulkanH_DestroyWindowData(g_Instance, g_Device, wd, g_Allocator); vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); #ifdef IMGUI_VULKAN_DEBUG_REPORT @@ -231,6 +229,15 @@ static void CleanupVulkan() vkDestroyInstance(g_Instance, g_Allocator); } +static void CleanupVulkanWindow() +{ + // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_WindowData helpers, + // however you would instead need to call ImGui_ImplVulkan_DestroyFrameRenderBuffers() on each + // ImGui_ImplVulkan_FrameRenderBuffers structure that you own. + ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; + ImGui_ImplVulkanH_DestroyWindowData(g_Instance, g_Device, wd, g_Allocator); +} + static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) { VkResult err; @@ -342,7 +349,7 @@ int main(int, char**) int w, h; SDL_GetWindowSize(window, &w, &h); ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; - SetupVulkanWindowData(wd, surface, w, h); + SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context ImGui::CreateContext(); @@ -364,7 +371,7 @@ int main(int, char**) init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; - init_info.FramesQueueSize = wd->FramesQueueSize; + init_info.MinImageCount = g_MinImageCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); @@ -443,7 +450,7 @@ int main(int, char**) if (g_WantSwapChainRebuild) { ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); - ImGui_ImplVulkan_SetFramesQueueSize(g_WindowData.FramesQueueSize); + ImGui_ImplVulkan_SetSwapChainMinImageCount(g_MinImageCount); g_WindowData.FrameIndex = 0; g_WantSwapChainRebuild = false; } @@ -504,6 +511,8 @@ int main(int, char**) ImGui_ImplVulkan_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); + + CleanupVulkanWindow(); CleanupVulkan(); SDL_DestroyWindow(window); diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 25b6428b..afe6dcef 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -21,7 +21,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. (The demo helper ImGui_ImplVulkanH_WindowData structure carries them.) -// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added FramesQueueSize field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetFramesQueueSize() to override FramesQueueSize while running. +// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added MinImageCount field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetSwapChainMinImageCount(). // 2019-XX-XX: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindowData() optional helper. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). @@ -64,7 +64,6 @@ static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; // Forward Declarations void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* frb, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); @@ -754,7 +753,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend IM_ASSERT(info->Device != VK_NULL_HANDLE); IM_ASSERT(info->Queue != VK_NULL_HANDLE); IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE); - IM_ASSERT(info->FramesQueueSize >= 2); + IM_ASSERT(info->MinImageCount >= 2); IM_ASSERT(render_pass != VK_NULL_HANDLE); g_VulkanInitInfo = *info; @@ -773,9 +772,24 @@ void ImGui_ImplVulkan_NewFrame() { } -void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size) +// Note: this has no effect in the 'master' branch, but multi-viewports needs this to recreate swap-chains. +void ImGui_ImplVulkan_SetSwapChainMinImageCount(int min_image_count) { - (void)frames_queue_size; + IM_ASSERT(min_image_count >= 2); + g_VulkanInitInfo.MinImageCount = min_image_count; +} + +// This is a public function because we require the user to pass a ImGui_ImplVulkan_FrameRenderBuffers +// structure to ImGui_ImplVulkan_RenderDrawData. +void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +{ + (void)instance; + if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } + if (buffers->VertexBufferMemory) { vkFreeMemory (device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } + if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } + if (buffers->IndexBufferMemory) { vkFreeMemory (device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; } + buffers->VertexBufferSize = 0; + buffers->IndexBufferSize = 0; } @@ -910,7 +924,6 @@ void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkInstance instance, VkPhy } } -// MinImageCount will usually turn into FramesQueueSize int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode) { if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR) @@ -984,6 +997,7 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysical err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->FramesQueueSize, NULL); check_vk_result(err); VkImage backbuffers[16] = {}; + IM_ASSERT(wd->FramesQueueSize >= min_image_count); IM_ASSERT(wd->FramesQueueSize < IM_ARRAYSIZE(backbuffers)); err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->FramesQueueSize, backbuffers); check_vk_result(err); @@ -1114,16 +1128,6 @@ void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, Im vkDestroyImageView(device, fd->BackbufferView, allocator); vkDestroyFramebuffer(device, fd->Framebuffer, allocator); - ImGui_ImplVulkanH_DestroyFrameRenderBuffers(instance, device, &fd->RenderBuffers, allocator); + ImGui_ImplVulkan_DestroyFrameRenderBuffers(instance, device, &fd->RenderBuffers, allocator); } -void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* frb, const VkAllocationCallbacks* allocator) -{ - (void)instance; - if (frb->VertexBuffer) { vkDestroyBuffer(device, frb->VertexBuffer, allocator); frb->VertexBuffer = VK_NULL_HANDLE; } - if (frb->VertexBufferMemory) { vkFreeMemory (device, frb->VertexBufferMemory, allocator); frb->VertexBufferMemory = VK_NULL_HANDLE; } - if (frb->IndexBuffer) { vkDestroyBuffer(device, frb->IndexBuffer, allocator); frb->IndexBuffer = VK_NULL_HANDLE; } - if (frb->IndexBufferMemory) { vkFreeMemory (device, frb->IndexBufferMemory, allocator); frb->IndexBufferMemory = VK_NULL_HANDLE; } - frb->VertexBufferSize = 0; - frb->IndexBufferSize = 0; -} diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 334910f6..4e62ec8a 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -33,7 +33,7 @@ struct ImGui_ImplVulkan_InitInfo VkQueue Queue; VkPipelineCache PipelineCache; VkDescriptorPool DescriptorPool; - int FramesQueueSize; // >= 2, generally matches the image count returned by vkGetSwapchainImagesKHR + int MinImageCount; // >= 2 const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); }; @@ -56,10 +56,11 @@ struct ImGui_ImplVulkan_FrameRenderBuffers IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); -IMGUI_IMPL_API void ImGui_ImplVulkan_SetFramesQueueSize(int frames_queue_size); // To override FramesQueueSize after initialization IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* buffers); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); +IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +IMGUI_IMPL_API void ImGui_ImplVulkan_SetSwapChainMinImageCount(int frames_queue_size); // To override MinImageCount after initialization // Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); From 0034e65c26204aee147ca130b5fe1b1052dea6fa Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 4 Apr 2019 23:28:29 +0200 Subject: [PATCH 225/566] Vulkan: Renaming demo/helper structures. Tidying up examples main.cpp. --- docs/CHANGELOG.txt | 4 +- examples/example_glfw_vulkan/main.cpp | 66 ++++++++++++++------------- examples/example_sdl_vulkan/main.cpp | 62 +++++++++++++------------ examples/imgui_impl_vulkan.cpp | 40 ++++++++-------- examples/imgui_impl_vulkan.h | 41 +++++++++-------- 5 files changed, 110 insertions(+), 103 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b4f17df9..7f038134 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,10 +36,12 @@ HOW TO UPDATE? Breaking Changes: - Examples: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. - (The demo helper ImGui_ImplVulkanH_WindowData structure carries them.) (#2461, #2348, #2378, #2097) + (The demo helper ImGui_ImplVulkanH_Window structure carries them.) (#2461, #2348, #2378, #2097) - Examples: Vulkan: Added MinImageCount field in ImGui_ImplVulkan_InitInfo, required during initialization to specify the number of in-flight image requested by swap chains. (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071, #1677) [@nathanvoglsam] +- Examples: Vulkan: Tidying up the demo/internals helpers (most engine/app should not rely + on them but it is possible you have!). Other Changes: diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ae6bb661..7a9a4502 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -30,20 +30,21 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif -static VkAllocationCallbacks* g_Allocator = NULL; -static VkInstance g_Instance = VK_NULL_HANDLE; -static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; -static VkDevice g_Device = VK_NULL_HANDLE; -static uint32_t g_QueueFamily = (uint32_t)-1; -static VkQueue g_Queue = VK_NULL_HANDLE; -static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; -static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; -static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; - -static ImGui_ImplVulkanH_WindowData g_WindowData; -static int g_MinImageCount = 2; -static bool g_WantSwapChainRebuild = false; -static int g_ResizeWidth = 0, g_ResizeHeight = 0; +static VkAllocationCallbacks* g_Allocator = NULL; +static VkInstance g_Instance = VK_NULL_HANDLE; +static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; +static VkDevice g_Device = VK_NULL_HANDLE; +static uint32_t g_QueueFamily = (uint32_t)-1; +static VkQueue g_Queue = VK_NULL_HANDLE; +static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; +static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; +static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; + +static ImGui_ImplVulkanH_Window g_WindowData; +static int g_MinImageCount = 2; +static bool g_SwapChainRebuild = false; +static int g_SwapChainResizeWidth = 0; +static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { @@ -192,7 +193,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) } } -static void SetupVulkanWindow(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR surface, int width, int height) +static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; @@ -220,8 +221,8 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR sur //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); - IM_ASSERT(wd->FramesQueueSize >= 2); + IM_ASSERT(g_MinImageCount >= 2); + ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } static void CleanupVulkan() @@ -240,14 +241,14 @@ static void CleanupVulkan() static void CleanupVulkanWindow() { - // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_WindowData helpers, + // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_Window helpers, // however you would instead need to call ImGui_ImplVulkan_DestroyFrameRenderBuffers() on each // ImGui_ImplVulkan_FrameRenderBuffers structure that you own. - ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; - ImGui_ImplVulkanH_DestroyWindowData(g_Instance, g_Device, wd, g_Allocator); + ImGui_ImplVulkanH_Window* wd = &g_WindowData; + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); } -static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) +static void FrameRender(ImGui_ImplVulkanH_Window* wd) { VkResult err; @@ -255,7 +256,7 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[wd->FrameIndex]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking check_vk_result(err); @@ -308,9 +309,9 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) } } -static void FramePresent(ImGui_ImplVulkanH_WindowData* wd) +static void FramePresent(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[wd->FrameIndex]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; @@ -329,14 +330,14 @@ static void glfw_error_callback(int error, const char* description) static void glfw_resize_callback(GLFWwindow*, int w, int h) { - g_WantSwapChainRebuild = true; - g_ResizeWidth = w; - g_ResizeHeight = h; + g_SwapChainRebuild = true; + g_SwapChainResizeWidth = w; + g_SwapChainResizeHeight = h; } int main(int, char**) { - // Setup window + // Setup GLFW window glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return 1; @@ -363,7 +364,7 @@ int main(int, char**) int w, h; glfwGetFramebufferSize(window, &w, &h); glfwSetFramebufferSizeCallback(window, glfw_resize_callback); - ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; + ImGui_ImplVulkanH_Window* wd = &g_WindowData; SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context @@ -450,12 +451,13 @@ int main(int, char**) // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); - if (g_WantSwapChainRebuild) + + if (g_SwapChainRebuild) { - ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_ResizeWidth, g_ResizeHeight, g_MinImageCount); + g_SwapChainRebuild = false; + ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); ImGui_ImplVulkan_SetSwapChainMinImageCount(g_MinImageCount); g_WindowData.FrameIndex = 0; - g_WantSwapChainRebuild = false; } // Start the Dear ImGui frame diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 58d34448..2e7e6c6e 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -22,19 +22,21 @@ #define IMGUI_VULKAN_DEBUG_REPORT #endif -static VkAllocationCallbacks* g_Allocator = NULL; -static VkInstance g_Instance = VK_NULL_HANDLE; -static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; -static VkDevice g_Device = VK_NULL_HANDLE; -static uint32_t g_QueueFamily = (uint32_t)-1; -static VkQueue g_Queue = VK_NULL_HANDLE; -static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; -static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; -static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; - -static ImGui_ImplVulkanH_WindowData g_WindowData; -static uint32_t g_MinImageCount = 2; -static bool g_WantSwapChainRebuild = false; +static VkAllocationCallbacks* g_Allocator = NULL; +static VkInstance g_Instance = VK_NULL_HANDLE; +static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; +static VkDevice g_Device = VK_NULL_HANDLE; +static uint32_t g_QueueFamily = (uint32_t)-1; +static VkQueue g_Queue = VK_NULL_HANDLE; +static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; +static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; +static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; + +static ImGui_ImplVulkanH_Window g_WindowData; +static uint32_t g_MinImageCount = 2; +static bool g_SwapChainRebuild = false; +static int g_SwapChainResizeWidth = 0; +static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { @@ -183,7 +185,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) } } -static void SetupVulkanWindow(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR surface, int width, int height) +static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; @@ -211,8 +213,8 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_WindowData* wd, VkSurfaceKHR sur //printf("[vulkan] Selected PresentMode = %d\n", wd->PresentMode); // Create SwapChain, RenderPass, Framebuffer, etc. - ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); - IM_ASSERT(wd->FramesQueueSize >= 2); + IM_ASSERT(g_MinImageCount >= 2); + ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } static void CleanupVulkan() @@ -231,14 +233,14 @@ static void CleanupVulkan() static void CleanupVulkanWindow() { - // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_WindowData helpers, + // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_Window helpers, // however you would instead need to call ImGui_ImplVulkan_DestroyFrameRenderBuffers() on each // ImGui_ImplVulkan_FrameRenderBuffers structure that you own. - ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; - ImGui_ImplVulkanH_DestroyWindowData(g_Instance, g_Device, wd, g_Allocator); + ImGui_ImplVulkanH_Window* wd = &g_WindowData; + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); } -static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) +static void FrameRender(ImGui_ImplVulkanH_Window* wd) { VkResult err; @@ -246,7 +248,7 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[wd->FrameIndex]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { err = vkWaitForFences(g_Device, 1, &fd->Fence, VK_TRUE, UINT64_MAX); // wait indefinitely instead of periodically checking check_vk_result(err); @@ -299,9 +301,9 @@ static void FrameRender(ImGui_ImplVulkanH_WindowData* wd) } } -static void FramePresent(ImGui_ImplVulkanH_WindowData* wd) +static void FramePresent(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[wd->FrameIndex]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; @@ -348,7 +350,7 @@ int main(int, char**) // Create Framebuffers int w, h; SDL_GetWindowSize(window, &w, &h); - ImGui_ImplVulkanH_WindowData* wd = &g_WindowData; + ImGui_ImplVulkanH_Window* wd = &g_WindowData; SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context @@ -441,18 +443,18 @@ int main(int, char**) done = true; if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) { - g_WindowData.Width = (int)event.window.data1; - g_WindowData.Height = (int)event.window.data2; - g_WantSwapChainRebuild = true; + g_SwapChainResizeWidth = (int)event.window.data1; + g_SwapChainResizeHeight = (int)event.window.data2; + g_SwapChainRebuild = true; } } - if (g_WantSwapChainRebuild) + if (g_SwapChainRebuild) { - ImGui_ImplVulkanH_CreateWindowData(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_WindowData.Width, g_WindowData.Height, g_MinImageCount); + g_SwapChainRebuild = false; + ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); ImGui_ImplVulkan_SetSwapChainMinImageCount(g_MinImageCount); g_WindowData.FrameIndex = 0; - g_WantSwapChainRebuild = false; } // Start the Dear ImGui frame diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index afe6dcef..edf4848b 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -20,9 +20,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. (The demo helper ImGui_ImplVulkanH_WindowData structure carries them.) +// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. (The demo helper ImGui_ImplVulkanH_Window structure carries them.) // 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added MinImageCount field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetSwapChainMinImageCount(). -// 2019-XX-XX: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindowData() optional helper. +// 2019-XX-XX: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. @@ -63,9 +63,9 @@ static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE; static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; // Forward Declarations -void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); -void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); //----------------------------------------------------------------------------- // SHADERS @@ -877,7 +877,7 @@ VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_d return VK_PRESENT_MODE_FIFO_KHR; // Always available } -void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) { IM_ASSERT(instance != VK_NULL_HANDLE && physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); (void)instance; @@ -888,7 +888,7 @@ void ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(VkInstance instance, VkPhy VkResult err; for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; { VkCommandPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -937,17 +937,17 @@ int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_m } // Also destroy old swap chain and in-flight frames data, if any. -void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; err = vkDeviceWaitIdle(device); check_vk_result(err); - // We don't use ImGui_ImplVulkanH_DestroyWindowData() because we want to preserve the old swapchain to create the new one. + // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. // Destroy old Framebuffer for (uint32_t i = 0; i < wd->FramesQueueSize; i++) - ImGui_ImplVulkanH_DestroyFrameData(instance, device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); delete[] wd->Frames; wd->Frames = NULL; wd->FramesQueueSize = 0; @@ -1003,7 +1003,7 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysical check_vk_result(err); IM_ASSERT(wd->Frames == NULL); - wd->Frames = new ImGui_ImplVulkanH_FrameData[wd->FramesQueueSize]; + wd->Frames = new ImGui_ImplVulkanH_Frame[wd->FramesQueueSize]; memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->FramesQueueSize); for (uint32_t i = 0; i < wd->FramesQueueSize; i++) wd->Frames[i].Backbuffer = backbuffers[i]; @@ -1062,7 +1062,7 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysical info.subresourceRange = image_range; for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; info.image = fd->Backbuffer; err = vkCreateImageView(device, &info, allocator, &fd->BackbufferView); check_vk_result(err); @@ -1082,7 +1082,7 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysical info.layers = 1; for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { - ImGui_ImplVulkanH_FrameData* fd = &wd->Frames[i]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; attachment[0] = fd->BackbufferView; err = vkCreateFramebuffer(device, &info, allocator, &fd->Framebuffer); check_vk_result(err); @@ -1090,29 +1090,29 @@ void ImGui_ImplVulkanH_CreateWindowDataSwapChain(VkInstance instance, VkPhysical } } -void ImGui_ImplVulkanH_CreateWindowData(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) +void ImGui_ImplVulkanH_CreateWindow(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) { - ImGui_ImplVulkanH_CreateWindowDataSwapChain(instance, physical_device, device, wd, allocator, width, height, min_image_count); - ImGui_ImplVulkanH_CreateWindowDataCommandBuffers(instance, physical_device, device, wd, queue_family, allocator); + ImGui_ImplVulkanH_CreateWindowSwapChain(instance, physical_device, device, wd, allocator, width, height, min_image_count); + ImGui_ImplVulkanH_CreateWindowCommandBuffers(instance, physical_device, device, wd, queue_family, allocator); } -void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) { vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(g_Queue); for (uint32_t i = 0; i < wd->FramesQueueSize; i++) - ImGui_ImplVulkanH_DestroyFrameData(instance, device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); delete[] wd->Frames; wd->Frames = NULL; vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); - *wd = ImGui_ImplVulkanH_WindowData(); + *wd = ImGui_ImplVulkanH_Window(); } -void ImGui_ImplVulkanH_DestroyFrameData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameData* fd, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) { (void)instance; vkDestroyFence(device, fd->Fence, allocator); diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 4e62ec8a..0a770afa 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -26,16 +26,16 @@ // [Please zero-clear before use!] struct ImGui_ImplVulkan_InitInfo { - VkInstance Instance; - VkPhysicalDevice PhysicalDevice; - VkDevice Device; - uint32_t QueueFamily; - VkQueue Queue; - VkPipelineCache PipelineCache; - VkDescriptorPool DescriptorPool; - int MinImageCount; // >= 2 - const VkAllocationCallbacks* Allocator; - void (*CheckVkResultFn)(VkResult err); + VkInstance Instance; + VkPhysicalDevice PhysicalDevice; + VkDevice Device; + uint32_t QueueFamily; + VkQueue Queue; + VkPipelineCache PipelineCache; + VkDescriptorPool DescriptorPool; + int MinImageCount; // >= 2 + const VkAllocationCallbacks* Allocator; + void (*CheckVkResultFn)(VkResult err); }; // Reusable buffers used for rendering by current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() @@ -83,19 +83,20 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyDeviceObjects(); // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- -struct ImGui_ImplVulkanH_FrameData; -struct ImGui_ImplVulkanH_WindowData; +struct ImGui_ImplVulkanH_Frame; +struct ImGui_ImplVulkanH_Window; -IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindowData(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); -IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindowData(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowData* wd, const VkAllocationCallbacks* allocator); +// Helpers +IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); // Helper structure to hold the data needed by one rendering frame -// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) +// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) // [Please zero-clear before use!] -struct ImGui_ImplVulkanH_FrameData +struct ImGui_ImplVulkanH_Frame { VkCommandPool CommandPool; VkCommandBuffer CommandBuffer; @@ -109,8 +110,8 @@ struct ImGui_ImplVulkanH_FrameData }; // Helper structure to hold the data needed by one rendering context into one OS window -// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own app.) -struct ImGui_ImplVulkanH_WindowData +// (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) +struct ImGui_ImplVulkanH_Window { int Width; int Height; @@ -123,9 +124,9 @@ struct ImGui_ImplVulkanH_WindowData VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) uint32_t FramesQueueSize; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) - ImGui_ImplVulkanH_FrameData* Frames; + ImGui_ImplVulkanH_Frame* Frames; - ImGui_ImplVulkanH_WindowData() + ImGui_ImplVulkanH_Window() { memset(this, 0, sizeof(*this)); PresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR; From 8ec24036d70d653a3eb8615c7dffc933acf483b8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 00:00:29 +0200 Subject: [PATCH 226/566] Vulkan: Viewports: Removed redundant field. --- examples/imgui_impl_vulkan.cpp | 20 ++++++++++---------- examples/imgui_impl_vulkan.h | 1 - 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index ae5a1737..5956571b 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -783,7 +783,7 @@ void ImGui_ImplVulkan_NewFrame() { } -// Note: this has no effect in the 'master' branch, but multi-viewports needs this to recreate swap-chains. +// FIXME-VIEWPORT: Need to recreate all swap chains? void ImGui_ImplVulkan_SetSwapChainMinImageCount(int min_image_count) { IM_ASSERT(min_image_count >= 2); @@ -1225,8 +1225,8 @@ static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; { - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; for (;;) { err = vkWaitForFences(v->Device, 1, &fd->Fence, VK_TRUE, 100); @@ -1235,10 +1235,10 @@ static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) check_vk_result(err); } { - err = vkAcquireNextImageKHR(v->Device, wd->Swapchain, UINT64_MAX, fd->ImageAcquiredSemaphore, VK_NULL_HANDLE, &fd->BackbufferCurrentIndex); + err = vkAcquireNextImageKHR(v->Device, wd->Swapchain, UINT64_MAX, fd->ImageAcquiredSemaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); + fd = &wd->Frames[wd->FrameIndex]; } - IM_ASSERT(wd->FrameIndex == fd->BackbufferCurrentIndex); // FIXME { err = vkResetCommandPool(v->Device, fd->CommandPool, 0); check_vk_result(err); @@ -1255,7 +1255,7 @@ static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) VkRenderPassBeginInfo info = {}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; info.renderPass = wd->RenderPass; - info.framebuffer = wd->Frames[fd->BackbufferCurrentIndex].Framebuffer; + info.framebuffer = fd->Framebuffer; info.renderArea.extent.width = wd->Width; info.renderArea.extent.height = wd->Height; info.clearValueCount = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? 0 : 1; @@ -1264,7 +1264,6 @@ static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) } } - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; ImGui_ImplVulkan_RenderDrawData(viewport->DrawData, fd->CommandBuffer, &fd->RenderBuffers); { @@ -1298,19 +1297,20 @@ static void ImGui_ImplVulkan_SwapBuffers(ImGuiViewport* viewport, void*) ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err; - uint32_t PresentIndex = wd->FrameIndex; + uint32_t present_index = wd->FrameIndex; - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[PresentIndex]; + ImGui_ImplVulkanH_Frame* fd = &wd->Frames[present_index]; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; info.pWaitSemaphores = &fd->RenderCompleteSemaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; - info.pImageIndices = &fd->BackbufferCurrentIndex; + info.pImageIndices = &present_index; err = vkQueuePresentKHR(v->Queue, &info); check_vk_result(err); - wd->FrameIndex = (wd->FrameIndex + 1) % wd->FramesQueueSize; + + wd->FrameIndex = (wd->FrameIndex + 1) % wd->FramesQueueSize; // This is for the next vkWaitForFences() } void ImGui_ImplVulkan_InitPlatformInterface() diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 56c237d6..c160b060 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -106,7 +106,6 @@ struct ImGui_ImplVulkanH_Frame VkSemaphore RenderCompleteSemaphore; VkImage Backbuffer; VkImageView BackbufferView; - uint32_t BackbufferCurrentIndex; VkFramebuffer Framebuffer; ImGui_ImplVulkan_FrameRenderBuffers RenderBuffers; }; From 01de69de366bac816328a112dce4ffcff59ddee8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 00:25:42 +0200 Subject: [PATCH 227/566] Vulkan: Note for unsupported feature with multi-viewports. (#2071) --- examples/imgui_impl_vulkan.cpp | 4 +++- examples/imgui_impl_vulkan.h | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 5956571b..43d8d4d9 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -783,10 +783,12 @@ void ImGui_ImplVulkan_NewFrame() { } -// FIXME-VIEWPORT: Need to recreate all swap chains? void ImGui_ImplVulkan_SetSwapChainMinImageCount(int min_image_count) { IM_ASSERT(min_image_count >= 2); + if (g_VulkanInitInfo.MinImageCount == min_image_count) + return; + IM_ASSERT(0); // FIXME-VIEWPORT: Need to recreate all swap chains? g_VulkanInitInfo.MinImageCount = min_image_count; } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index c160b060..1b156fec 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -61,7 +61,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, V IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); -IMGUI_IMPL_API void ImGui_ImplVulkan_SetSwapChainMinImageCount(int frames_queue_size); // To override MinImageCount after initialization +IMGUI_IMPL_API void ImGui_ImplVulkan_SetSwapChainMinImageCount(int min_image_count); // To override MinImageCount after initialization // Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); From 1ba79baab5888ce103be05d2270340841812a534 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 16:33:41 +0200 Subject: [PATCH 228/566] Vulkan, Viewports: Fixed ImGui_ImplVulkan_SetWindowSize() not recreating command-buffers, fence etc. (#2472, #2461, #2071) --- examples/imgui_impl_vulkan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 43d8d4d9..8767cb2f 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -1217,7 +1217,7 @@ static void ImGui_ImplVulkan_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) return; ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; data->Window.ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true; - ImGui_ImplVulkanH_CreateWindowSwapChain(v->Instance, v->PhysicalDevice, v->Device, &data->Window, v->Allocator, (int)size.x, (int)size.y, v->MinImageCount); + ImGui_ImplVulkanH_CreateWindow(v->Instance, v->PhysicalDevice, v->Device, &data->Window, v->QueueFamily, v->Allocator, (int)size.x, (int)size.y, v->MinImageCount); } static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) From 9acb158990ea32cb138801430423a9d0e715354b Mon Sep 17 00:00:00 2001 From: MindSpunk Date: Fri, 5 Apr 2019 15:50:21 +1100 Subject: [PATCH 229/566] Vulkan, Viewports: Fix for resizing viewport windows crashing. (#2472) --- examples/example_glfw_vulkan/main.cpp | 9 +++--- examples/example_sdl_vulkan/main.cpp | 9 +++--- examples/imgui_impl_vulkan.cpp | 41 ++++++++++++++++++++------- examples/imgui_impl_vulkan.h | 11 +++++-- 4 files changed, 50 insertions(+), 20 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 0b3bd955..bf5414aa 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -252,7 +252,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) { VkResult err; - VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; + VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); @@ -300,7 +301,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) info.commandBufferCount = 1; info.pCommandBuffers = &fd->CommandBuffer; info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &fd->RenderCompleteSemaphore; + info.pSignalSemaphores = &render_complete_semaphore; err = vkEndCommandBuffer(fd->CommandBuffer); check_vk_result(err); @@ -311,11 +312,11 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) static void FramePresent(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &fd->RenderCompleteSemaphore; + info.pWaitSemaphores = &render_complete_semaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 37d5ace2..837fc880 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -244,7 +244,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) { VkResult err; - VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; + VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); @@ -292,7 +293,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) info.commandBufferCount = 1; info.pCommandBuffers = &fd->CommandBuffer; info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &fd->RenderCompleteSemaphore; + info.pSignalSemaphores = &render_complete_semaphore; err = vkEndCommandBuffer(fd->CommandBuffer); check_vk_result(err); @@ -303,11 +304,11 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) static void FramePresent(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &fd->RenderCompleteSemaphore; + info.pWaitSemaphores = &render_complete_semaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 8767cb2f..88e7e0dc 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -65,6 +65,7 @@ static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; // Forward Declarations void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); @@ -902,6 +903,7 @@ void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysica for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; + ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i]; { VkCommandPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -929,9 +931,9 @@ void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysica { VkSemaphoreCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; - err = vkCreateSemaphore(device, &info, allocator, &fd->ImageAcquiredSemaphore); + err = vkCreateSemaphore(device, &info, allocator, &fsd->ImageAcquiredSemaphore); check_vk_result(err); - err = vkCreateSemaphore(device, &info, allocator, &fd->RenderCompleteSemaphore); + err = vkCreateSemaphore(device, &info, allocator, &fsd->RenderCompleteSemaphore); check_vk_result(err); } } @@ -960,9 +962,14 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. // Destroy old Framebuffer for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + { ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); + } delete[] wd->Frames; + delete[] wd->FrameSemaphores; wd->Frames = NULL; + wd->FrameSemaphores = NULL; wd->FramesQueueSize = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1017,7 +1024,9 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi IM_ASSERT(wd->Frames == NULL); wd->Frames = new ImGui_ImplVulkanH_Frame[wd->FramesQueueSize]; + wd->FrameSemaphores = new ImGui_ImplVulkanH_FrameSemaphores[wd->FramesQueueSize]; memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->FramesQueueSize); + memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->FramesQueueSize); for (uint32_t i = 0; i < wd->FramesQueueSize; i++) wd->Frames[i].Backbuffer = backbuffers[i]; } @@ -1115,9 +1124,14 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui //vkQueueWaitIdle(g_Queue); for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + { ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); + } delete[] wd->Frames; + delete[] wd->FrameSemaphores; wd->Frames = NULL; + wd->FrameSemaphores = NULL; vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); @@ -1125,18 +1139,23 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui *wd = ImGui_ImplVulkanH_Window(); } +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) +{ + (void)instance; + vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator); + vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator); + fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; +} + void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) { (void)instance; vkDestroyFence(device, fd->Fence, allocator); vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); vkDestroyCommandPool(device, fd->CommandPool, allocator); - vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); - vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); fd->Fence = VK_NULL_HANDLE; fd->CommandBuffer = VK_NULL_HANDLE; fd->CommandPool = VK_NULL_HANDLE; - fd->ImageAcquiredSemaphore = fd->RenderCompleteSemaphore = VK_NULL_HANDLE; vkDestroyImageView(device, fd->BackbufferView, allocator); vkDestroyFramebuffer(device, fd->Framebuffer, allocator); @@ -1228,6 +1247,7 @@ static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) VkResult err; ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; + ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[wd->SemaphoreIndex]; { for (;;) { @@ -1237,7 +1257,7 @@ static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) check_vk_result(err); } { - err = vkAcquireNextImageKHR(v->Device, wd->Swapchain, UINT64_MAX, fd->ImageAcquiredSemaphore, VK_NULL_HANDLE, &wd->FrameIndex); + err = vkAcquireNextImageKHR(v->Device, wd->Swapchain, UINT64_MAX, fsd->ImageAcquiredSemaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); fd = &wd->Frames[wd->FrameIndex]; } @@ -1275,12 +1295,12 @@ static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*) VkSubmitInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &fd->ImageAcquiredSemaphore; + info.pWaitSemaphores = &fsd->ImageAcquiredSemaphore; info.pWaitDstStageMask = &wait_stage; info.commandBufferCount = 1; info.pCommandBuffers = &fd->CommandBuffer; info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &fd->RenderCompleteSemaphore; + info.pSignalSemaphores = &fsd->RenderCompleteSemaphore; err = vkEndCommandBuffer(fd->CommandBuffer); check_vk_result(err); @@ -1301,11 +1321,11 @@ static void ImGui_ImplVulkan_SwapBuffers(ImGuiViewport* viewport, void*) VkResult err; uint32_t present_index = wd->FrameIndex; - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[present_index]; + ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[wd->SemaphoreIndex]; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &fd->RenderCompleteSemaphore; + info.pWaitSemaphores = &fsd->RenderCompleteSemaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; info.pImageIndices = &present_index; @@ -1313,6 +1333,7 @@ static void ImGui_ImplVulkan_SwapBuffers(ImGuiViewport* viewport, void*) check_vk_result(err); wd->FrameIndex = (wd->FrameIndex + 1) % wd->FramesQueueSize; // This is for the next vkWaitForFences() + wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->FramesQueueSize; // Now we can use the next set of semaphores } void ImGui_ImplVulkan_InitPlatformInterface() diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 1b156fec..c632d62c 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -102,14 +102,18 @@ struct ImGui_ImplVulkanH_Frame VkCommandPool CommandPool; VkCommandBuffer CommandBuffer; VkFence Fence; - VkSemaphore ImageAcquiredSemaphore; - VkSemaphore RenderCompleteSemaphore; VkImage Backbuffer; VkImageView BackbufferView; VkFramebuffer Framebuffer; ImGui_ImplVulkan_FrameRenderBuffers RenderBuffers; }; +struct ImGui_ImplVulkanH_FrameSemaphores +{ + VkSemaphore ImageAcquiredSemaphore; + VkSemaphore RenderCompleteSemaphore; +}; + // Helper structure to hold the data needed by one rendering context into one OS window // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) struct ImGui_ImplVulkanH_Window @@ -125,7 +129,10 @@ struct ImGui_ImplVulkanH_Window VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) uint32_t FramesQueueSize; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) + uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) ImGui_ImplVulkanH_Frame* Frames; + ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; + ImGui_ImplVulkanH_Window() { From a45840746e171b3e258f29a716d7634cfd832e1c Mon Sep 17 00:00:00 2001 From: MindSpunk Date: Fri, 5 Apr 2019 15:50:21 +1100 Subject: [PATCH 230/566] Vulkan, Viewports: Fix for resizing viewport windows crashing. (#2472) --- examples/example_glfw_vulkan/main.cpp | 9 ++++---- examples/example_sdl_vulkan/main.cpp | 9 ++++---- examples/imgui_impl_vulkan.cpp | 30 +++++++++++++++++++++------ examples/imgui_impl_vulkan.h | 11 ++++++++-- 4 files changed, 43 insertions(+), 16 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 7a9a4502..c8417391 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -252,7 +252,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) { VkResult err; - VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; + VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); @@ -300,7 +301,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) info.commandBufferCount = 1; info.pCommandBuffers = &fd->CommandBuffer; info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &fd->RenderCompleteSemaphore; + info.pSignalSemaphores = &render_complete_semaphore; err = vkEndCommandBuffer(fd->CommandBuffer); check_vk_result(err); @@ -311,11 +312,11 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) static void FramePresent(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &fd->RenderCompleteSemaphore; + info.pWaitSemaphores = &render_complete_semaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 2e7e6c6e..2124f613 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -244,7 +244,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) { VkResult err; - VkSemaphore& image_acquired_semaphore = wd->Frames[wd->FrameIndex].ImageAcquiredSemaphore; + VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); check_vk_result(err); @@ -292,7 +293,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) info.commandBufferCount = 1; info.pCommandBuffers = &fd->CommandBuffer; info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &fd->RenderCompleteSemaphore; + info.pSignalSemaphores = &render_complete_semaphore; err = vkEndCommandBuffer(fd->CommandBuffer); check_vk_result(err); @@ -303,11 +304,11 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) static void FramePresent(ImGui_ImplVulkanH_Window* wd) { - ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; + VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; - info.pWaitSemaphores = &fd->RenderCompleteSemaphore; + info.pWaitSemaphores = &render_complete_semaphore; info.swapchainCount = 1; info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index edf4848b..c8bb7ab9 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -64,6 +64,7 @@ static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; // Forward Declarations void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); @@ -889,6 +890,7 @@ void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysica for (uint32_t i = 0; i < wd->FramesQueueSize; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; + ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i]; { VkCommandPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -916,9 +918,9 @@ void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysica { VkSemaphoreCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; - err = vkCreateSemaphore(device, &info, allocator, &fd->ImageAcquiredSemaphore); + err = vkCreateSemaphore(device, &info, allocator, &fsd->ImageAcquiredSemaphore); check_vk_result(err); - err = vkCreateSemaphore(device, &info, allocator, &fd->RenderCompleteSemaphore); + err = vkCreateSemaphore(device, &info, allocator, &fsd->RenderCompleteSemaphore); check_vk_result(err); } } @@ -947,9 +949,14 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. // Destroy old Framebuffer for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + { ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); + } delete[] wd->Frames; + delete[] wd->FrameSemaphores; wd->Frames = NULL; + wd->FrameSemaphores = NULL; wd->FramesQueueSize = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1004,7 +1011,9 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi IM_ASSERT(wd->Frames == NULL); wd->Frames = new ImGui_ImplVulkanH_Frame[wd->FramesQueueSize]; + wd->FrameSemaphores = new ImGui_ImplVulkanH_FrameSemaphores[wd->FramesQueueSize]; memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->FramesQueueSize); + memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->FramesQueueSize); for (uint32_t i = 0; i < wd->FramesQueueSize; i++) wd->Frames[i].Backbuffer = backbuffers[i]; } @@ -1102,9 +1111,14 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui //vkQueueWaitIdle(g_Queue); for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + { ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); + } delete[] wd->Frames; + delete[] wd->FrameSemaphores; wd->Frames = NULL; + wd->FrameSemaphores = NULL; vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); @@ -1112,22 +1126,26 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui *wd = ImGui_ImplVulkanH_Window(); } +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) +{ + (void)instance; + vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator); + vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator); + fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; +} + void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) { (void)instance; vkDestroyFence(device, fd->Fence, allocator); vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); vkDestroyCommandPool(device, fd->CommandPool, allocator); - vkDestroySemaphore(device, fd->ImageAcquiredSemaphore, allocator); - vkDestroySemaphore(device, fd->RenderCompleteSemaphore, allocator); fd->Fence = VK_NULL_HANDLE; fd->CommandBuffer = VK_NULL_HANDLE; fd->CommandPool = VK_NULL_HANDLE; - fd->ImageAcquiredSemaphore = fd->RenderCompleteSemaphore = VK_NULL_HANDLE; vkDestroyImageView(device, fd->BackbufferView, allocator); vkDestroyFramebuffer(device, fd->Framebuffer, allocator); ImGui_ImplVulkan_DestroyFrameRenderBuffers(instance, device, &fd->RenderBuffers, allocator); } - diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 0a770afa..b872ae21 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -101,14 +101,18 @@ struct ImGui_ImplVulkanH_Frame VkCommandPool CommandPool; VkCommandBuffer CommandBuffer; VkFence Fence; - VkSemaphore ImageAcquiredSemaphore; - VkSemaphore RenderCompleteSemaphore; VkImage Backbuffer; VkImageView BackbufferView; VkFramebuffer Framebuffer; ImGui_ImplVulkan_FrameRenderBuffers RenderBuffers; }; +struct ImGui_ImplVulkanH_FrameSemaphores +{ + VkSemaphore ImageAcquiredSemaphore; + VkSemaphore RenderCompleteSemaphore; +}; + // Helper structure to hold the data needed by one rendering context into one OS window // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) struct ImGui_ImplVulkanH_Window @@ -124,7 +128,10 @@ struct ImGui_ImplVulkanH_Window VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) uint32_t FramesQueueSize; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) + uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) ImGui_ImplVulkanH_Frame* Frames; + ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; + ImGui_ImplVulkanH_Window() { From ec76722d2d7945d8b6bf7f152a7acc81e0a507e6 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 17:22:24 +0200 Subject: [PATCH 231/566] Vulkan: Added ImageCount to InitInfo structure (!= MinImageCount) will be needed for viewports. Renamed FramesQueueSize -> ImageCount. (#2472, #2071) --- docs/CHANGELOG.txt | 4 ++-- examples/example_glfw_vulkan/main.cpp | 1 + examples/example_sdl_vulkan/main.cpp | 1 + examples/imgui_impl_vulkan.cpp | 31 ++++++++++++++------------- examples/imgui_impl_vulkan.h | 14 ++++++------ 5 files changed, 27 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7f038134..a3283b1b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,8 +37,8 @@ Breaking Changes: - Examples: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. (The demo helper ImGui_ImplVulkanH_Window structure carries them.) (#2461, #2348, #2378, #2097) -- Examples: Vulkan: Added MinImageCount field in ImGui_ImplVulkan_InitInfo, required during - initialization to specify the number of in-flight image requested by swap chains. +- Examples: Vulkan: Added MinImageCount/ImageCount fields in ImGui_ImplVulkan_InitInfo, required + during initialization to specify the number of in-flight image requested by swap chains. (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071, #1677) [@nathanvoglsam] - Examples: Vulkan: Tidying up the demo/internals helpers (most engine/app should not rely on them but it is possible you have!). diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index c8417391..81630838 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -391,6 +391,7 @@ int main(int, char**) init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; init_info.MinImageCount = g_MinImageCount; + init_info.ImageCount = wd->ImageCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 2124f613..976d026e 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -375,6 +375,7 @@ int main(int, char**) init_info.DescriptorPool = g_DescriptorPool; init_info.Allocator = g_Allocator; init_info.MinImageCount = g_MinImageCount; + init_info.ImageCount = wd->ImageCount; init_info.CheckVkResultFn = check_vk_result; ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index c8bb7ab9..df8f84fc 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -755,6 +755,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend IM_ASSERT(info->Queue != VK_NULL_HANDLE); IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE); IM_ASSERT(info->MinImageCount >= 2); + IM_ASSERT(info->ImageCount >= info->MinImageCount); IM_ASSERT(render_pass != VK_NULL_HANDLE); g_VulkanInitInfo = *info; @@ -887,7 +888,7 @@ void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysica // Create Command Buffers VkResult err; - for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i]; @@ -948,7 +949,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. // Destroy old Framebuffer - for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); @@ -957,7 +958,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi delete[] wd->FrameSemaphores; wd->Frames = NULL; wd->FrameSemaphores = NULL; - wd->FramesQueueSize = 0; + wd->ImageCount = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1001,20 +1002,20 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi } err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain); check_vk_result(err); - err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->FramesQueueSize, NULL); + err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, NULL); check_vk_result(err); VkImage backbuffers[16] = {}; - IM_ASSERT(wd->FramesQueueSize >= min_image_count); - IM_ASSERT(wd->FramesQueueSize < IM_ARRAYSIZE(backbuffers)); - err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->FramesQueueSize, backbuffers); + IM_ASSERT(wd->ImageCount >= min_image_count); + IM_ASSERT(wd->ImageCount < IM_ARRAYSIZE(backbuffers)); + err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers); check_vk_result(err); IM_ASSERT(wd->Frames == NULL); - wd->Frames = new ImGui_ImplVulkanH_Frame[wd->FramesQueueSize]; - wd->FrameSemaphores = new ImGui_ImplVulkanH_FrameSemaphores[wd->FramesQueueSize]; - memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->FramesQueueSize); - memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->FramesQueueSize); - for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + wd->Frames = new ImGui_ImplVulkanH_Frame[wd->ImageCount]; + wd->FrameSemaphores = new ImGui_ImplVulkanH_FrameSemaphores[wd->ImageCount]; + memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount); + memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->ImageCount); + for (uint32_t i = 0; i < wd->ImageCount; i++) wd->Frames[i].Backbuffer = backbuffers[i]; } if (old_swapchain) @@ -1069,7 +1070,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi info.components.a = VK_COMPONENT_SWIZZLE_A; VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; info.subresourceRange = image_range; - for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; info.image = fd->Backbuffer; @@ -1089,7 +1090,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi info.width = wd->Width; info.height = wd->Height; info.layers = 1; - for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; attachment[0] = fd->BackbufferView; @@ -1110,7 +1111,7 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(g_Queue); - for (uint32_t i = 0; i < wd->FramesQueueSize; i++) + for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index b872ae21..55d72dfb 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -33,7 +33,8 @@ struct ImGui_ImplVulkan_InitInfo VkQueue Queue; VkPipelineCache PipelineCache; VkDescriptorPool DescriptorPool; - int MinImageCount; // >= 2 + uint32_t MinImageCount; // >= 2 + uint32_t ImageCount; // >= MinImageCount const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); }; @@ -60,7 +61,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, V IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); -IMGUI_IMPL_API void ImGui_ImplVulkan_SetSwapChainMinImageCount(int frames_queue_size); // To override MinImageCount after initialization +IMGUI_IMPL_API void ImGui_ImplVulkan_SetSwapChainMinImageCount(int min_image_count); // To override MinImageCount after initialization // Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); @@ -127,12 +128,11 @@ struct ImGui_ImplVulkanH_Window bool ClearEnable; VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) - uint32_t FramesQueueSize; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) + uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) - ImGui_ImplVulkanH_Frame* Frames; - ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; - - + ImGui_ImplVulkanH_Frame* Frames; + ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; + ImGui_ImplVulkanH_Window() { memset(this, 0, sizeof(*this)); From 452047c7cadb9e4c88537a4c0c2e1b9e571ceccd Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 17:48:47 +0200 Subject: [PATCH 232/566] Vulkan: Removed requirement for user to pass their own render buffer storage to ImGui_ImplVulkan_RenderDrawData(), this is managed internally. --- docs/CHANGELOG.txt | 6 +- examples/example_glfw_vulkan/main.cpp | 4 +- examples/example_sdl_vulkan/main.cpp | 4 +- examples/imgui_impl_vulkan.cpp | 134 ++++++++++++++++++-------- examples/imgui_impl_vulkan.h | 22 +---- 5 files changed, 102 insertions(+), 68 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a3283b1b..1822526f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -34,16 +34,12 @@ HOW TO UPDATE? ----------------------------------------------------------------------- Breaking Changes: -- Examples: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is - in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. - (The demo helper ImGui_ImplVulkanH_Window structure carries them.) (#2461, #2348, #2378, #2097) - Examples: Vulkan: Added MinImageCount/ImageCount fields in ImGui_ImplVulkan_InitInfo, required during initialization to specify the number of in-flight image requested by swap chains. (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071, #1677) [@nathanvoglsam] - Examples: Vulkan: Tidying up the demo/internals helpers (most engine/app should not rely on them but it is possible you have!). - Other Changes: - InputText: Fixed selection background starts rendering one frame after the cursor movement when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] @@ -56,8 +52,10 @@ Other Changes: - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. +- Examples: Vulkan: Fixed in-flight buffers issues when using multi-viewports. (#2461, #2348, #2378, #2097) - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. +- Examples: Vulkan: Added ImGui_ImplVulkan_SetMinImageCount() to change min image count at runtime. (#2071) [@nathanvoglsam] - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] - Examples: GLUT: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. (#2465) [@andrewwillmott] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 81630838..972c12b0 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -287,7 +287,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) } // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer, &fd->RenderBuffers); + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -457,8 +457,8 @@ int main(int, char**) if (g_SwapChainRebuild) { g_SwapChainRebuild = false; + ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); - ImGui_ImplVulkan_SetSwapChainMinImageCount(g_MinImageCount); g_WindowData.FrameIndex = 0; } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 976d026e..d2a829c4 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -279,7 +279,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) } // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer, &fd->RenderBuffers); + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -454,8 +454,8 @@ int main(int, char**) if (g_SwapChainRebuild) { g_SwapChainRebuild = false; + ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); - ImGui_ImplVulkan_SetSwapChainMinImageCount(g_MinImageCount); g_WindowData.FrameIndex = 0; } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index df8f84fc..fb54801f 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -20,8 +20,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added extra parameter to ImGui_ImplVulkan_RenderDrawData(). Engine/app is in charge of owning/storing 1 ImGui_ImplVulkan_FrameRenderBuffers per in-flight rendering frame. (The demo helper ImGui_ImplVulkanH_Window structure carries them.) -// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added MinImageCount field in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetSwapChainMinImageCount(). +// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). // 2019-XX-XX: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). @@ -44,6 +43,27 @@ #include "imgui_impl_vulkan.h" #include +// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() +// [Please zero-clear before use!] +struct ImGui_ImplVulkanH_FrameRenderBuffers +{ + VkDeviceMemory VertexBufferMemory; + VkDeviceMemory IndexBufferMemory; + VkDeviceSize VertexBufferSize; + VkDeviceSize IndexBufferSize; + VkBuffer VertexBuffer; + VkBuffer IndexBuffer; +}; + +// Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers +// [Please zero-clear before use!] +struct ImGui_ImplVulkanH_WindowRenderBuffers +{ + uint32_t Index; + uint32_t Count; + ImGui_ImplVulkanH_FrameRenderBuffers* FrameRenderBuffers; +}; + // Vulkan data static ImGui_ImplVulkan_InitInfo g_VulkanInitInfo = {}; static VkRenderPass g_RenderPass = VK_NULL_HANDLE; @@ -62,9 +82,14 @@ static VkImageView g_FontView = VK_NULL_HANDLE; static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE; static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; +// Render buffers +static ImGui_ImplVulkanH_WindowRenderBuffers g_MainWindowRenderBuffers; + // Forward Declarations void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); @@ -234,7 +259,7 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) -void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* fd) +void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer) { // 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); @@ -243,23 +268,37 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm return; ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; + + // Allocate array to store enough vertex/index buffers + ImGui_ImplVulkanH_WindowRenderBuffers* wrb = &g_MainWindowRenderBuffers; + if (wrb->FrameRenderBuffers == NULL) + { + wrb->Index = 0; + wrb->Count = v->ImageCount; + wrb->FrameRenderBuffers = new ImGui_ImplVulkanH_FrameRenderBuffers[wrb->Count]; + memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count); + } + IM_ASSERT(wrb->Count == v->ImageCount); + wrb->Index = (wrb->Index + 1) % wrb->Count; + ImGui_ImplVulkanH_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; + VkResult err; - // Create the Vertex and Index buffers: + // Create or resize the vertex/index buffers size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); - if (fd->VertexBuffer == VK_NULL_HANDLE || fd->VertexBufferSize < vertex_size) - CreateOrResizeBuffer(fd->VertexBuffer, fd->VertexBufferMemory, fd->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); - if (fd->IndexBuffer == VK_NULL_HANDLE || fd->IndexBufferSize < index_size) - CreateOrResizeBuffer(fd->IndexBuffer, fd->IndexBufferMemory, fd->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); + if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size) + CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); + if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size) + CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); // Upload vertex/index data into a single contiguous GPU buffer { ImDrawVert* vtx_dst = NULL; ImDrawIdx* idx_dst = NULL; - err = vkMapMemory(v->Device, fd->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); + err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); check_vk_result(err); - err = vkMapMemory(v->Device, fd->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst)); + err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst)); check_vk_result(err); for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -271,15 +310,15 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm } VkMappedMemoryRange range[2] = {}; range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; - range[0].memory = fd->VertexBufferMemory; + range[0].memory = rb->VertexBufferMemory; range[0].size = VK_WHOLE_SIZE; range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; - range[1].memory = fd->IndexBufferMemory; + range[1].memory = rb->IndexBufferMemory; range[1].size = VK_WHOLE_SIZE; err = vkFlushMappedMemoryRanges(v->Device, 2, range); check_vk_result(err); - vkUnmapMemory(v->Device, fd->VertexBufferMemory); - vkUnmapMemory(v->Device, fd->IndexBufferMemory); + vkUnmapMemory(v->Device, rb->VertexBufferMemory); + vkUnmapMemory(v->Device, rb->IndexBufferMemory); } // Bind pipeline and descriptor sets: @@ -291,10 +330,10 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Bind Vertex And Index Buffer: { - VkBuffer vertex_buffers[1] = { fd->VertexBuffer }; + VkBuffer vertex_buffers[1] = { rb->VertexBuffer }; VkDeviceSize vertex_offset[1] = { 0 }; vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset); - vkCmdBindIndexBuffer(command_buffer, fd->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); + vkCmdBindIndexBuffer(command_buffer, rb->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); } // Setup viewport: @@ -733,8 +772,9 @@ void ImGui_ImplVulkan_DestroyFontUploadObjects() void ImGui_ImplVulkan_DestroyDeviceObjects() { ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; - + ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Instance, v->Device, &g_MainWindowRenderBuffers, v->Allocator); ImGui_ImplVulkan_DestroyFontUploadObjects(); + if (g_FontView) { vkDestroyImageView(v->Device, g_FontView, v->Allocator); g_FontView = VK_NULL_HANDLE; } if (g_FontImage) { vkDestroyImage(v->Device, g_FontImage, v->Allocator); g_FontImage = VK_NULL_HANDLE; } if (g_FontMemory) { vkFreeMemory(v->Device, g_FontMemory, v->Allocator); g_FontMemory = VK_NULL_HANDLE; } @@ -774,24 +814,17 @@ void ImGui_ImplVulkan_NewFrame() { } -// Note: this has no effect in the 'master' branch, but multi-viewports needs this to recreate swap-chains. -void ImGui_ImplVulkan_SetSwapChainMinImageCount(int min_image_count) +void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) { IM_ASSERT(min_image_count >= 2); - g_VulkanInitInfo.MinImageCount = min_image_count; -} + if (g_VulkanInitInfo.MinImageCount == min_image_count) + return; -// This is a public function because we require the user to pass a ImGui_ImplVulkan_FrameRenderBuffers -// structure to ImGui_ImplVulkan_RenderDrawData. -void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) -{ - (void)instance; - if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } - if (buffers->VertexBufferMemory) { vkFreeMemory (device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } - if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } - if (buffers->IndexBufferMemory) { vkFreeMemory (device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; } - buffers->VertexBufferSize = 0; - buffers->IndexBufferSize = 0; + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; + VkResult err = vkDeviceWaitIdle(v->Device); + check_vk_result(err); + ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Instance, v->Device, &g_MainWindowRenderBuffers, v->Allocator); + g_VulkanInitInfo.MinImageCount = min_image_count; } @@ -1127,14 +1160,6 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui *wd = ImGui_ImplVulkanH_Window(); } -void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) -{ - (void)instance; - vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator); - vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator); - fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; -} - void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) { (void)instance; @@ -1147,6 +1172,33 @@ void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ vkDestroyImageView(device, fd->BackbufferView, allocator); vkDestroyFramebuffer(device, fd->Framebuffer, allocator); +} - ImGui_ImplVulkan_DestroyFrameRenderBuffers(instance, device, &fd->RenderBuffers, allocator); +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) +{ + (void)instance; + vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator); + vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator); + fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; +} + +void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +{ + (void)instance; + if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } + if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } + if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } + if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; } + buffers->VertexBufferSize = 0; + buffers->IndexBufferSize = 0; +} + +void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +{ + for (uint32_t n = 0; n < buffers->Count; n++) + ImGui_ImplVulkanH_DestroyFrameRenderBuffers(instance, device, &buffers->FrameRenderBuffers[n], allocator); + delete[] buffers->FrameRenderBuffers; + buffers->FrameRenderBuffers = NULL; + buffers->Index = 0; + buffers->Count = 0; } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 55d72dfb..8b5421cc 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -39,29 +39,14 @@ struct ImGui_ImplVulkan_InitInfo void (*CheckVkResultFn)(VkResult err); }; -// Reusable buffers used for rendering by current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() -// [Please zero-clear before use!] -// In the examples we store those in the helper ImGui_ImplVulkanH_FrameData structure, however as your own engine/app likely won't use the ImGui_Impl_VulkanH_XXXX helpers, -// you are expected to hold on as many ImGui_ImplVulkan_FrameRenderBuffers structures on your side as you have in-flight frames (== init_info.FramesQueueSize) -struct ImGui_ImplVulkan_FrameRenderBuffers -{ - VkDeviceMemory VertexBufferMemory; - VkDeviceMemory IndexBufferMemory; - VkDeviceSize VertexBufferSize; - VkDeviceSize IndexBufferSize; - VkBuffer VertexBuffer; - VkBuffer IndexBuffer; -}; - // Called by user code IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); -IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* buffers); +IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); -IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); -IMGUI_IMPL_API void ImGui_ImplVulkan_SetSwapChainMinImageCount(int min_image_count); // To override MinImageCount after initialization +IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) // Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); @@ -105,7 +90,6 @@ struct ImGui_ImplVulkanH_Frame VkImage Backbuffer; VkImageView BackbufferView; VkFramebuffer Framebuffer; - ImGui_ImplVulkan_FrameRenderBuffers RenderBuffers; }; struct ImGui_ImplVulkanH_FrameSemaphores @@ -132,7 +116,7 @@ struct ImGui_ImplVulkanH_Window uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) ImGui_ImplVulkanH_Frame* Frames; ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; - + ImGui_ImplVulkanH_Window() { memset(this, 0, sizeof(*this)); From 6bc47dfe48825b55c428e1ecb26910676ec7a007 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 17:54:16 +0200 Subject: [PATCH 233/566] Vulkan: Removed superfluous vkInstance parameters being passed along. --- examples/imgui_impl_vulkan.cpp | 49 ++++++++++++++++------------------ 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index fb54801f..48237139 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -86,12 +86,12 @@ static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; static ImGui_ImplVulkanH_WindowRenderBuffers g_MainWindowRenderBuffers; // Forward Declarations -void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); -void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); //----------------------------------------------------------------------------- // SHADERS @@ -772,7 +772,7 @@ void ImGui_ImplVulkan_DestroyFontUploadObjects() void ImGui_ImplVulkan_DestroyDeviceObjects() { ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; - ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Instance, v->Device, &g_MainWindowRenderBuffers, v->Allocator); + ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &g_MainWindowRenderBuffers, v->Allocator); ImGui_ImplVulkan_DestroyFontUploadObjects(); if (g_FontView) { vkDestroyImageView(v->Device, g_FontView, v->Allocator); g_FontView = VK_NULL_HANDLE; } @@ -823,7 +823,7 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err = vkDeviceWaitIdle(v->Device); check_vk_result(err); - ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Instance, v->Device, &g_MainWindowRenderBuffers, v->Allocator); + ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &g_MainWindowRenderBuffers, v->Allocator); g_VulkanInitInfo.MinImageCount = min_image_count; } @@ -912,10 +912,9 @@ VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_d return VK_PRESENT_MODE_FIFO_KHR; // Always available } -void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) { - IM_ASSERT(instance != VK_NULL_HANDLE && physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); - (void)instance; + IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); (void)physical_device; (void)allocator; @@ -973,7 +972,7 @@ int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_m } // Also destroy old swap chain and in-flight frames data, if any. -void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) +void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; @@ -984,8 +983,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi // Destroy old Framebuffer for (uint32_t i = 0; i < wd->ImageCount; i++) { - ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); - ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); + ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); } delete[] wd->Frames; delete[] wd->FrameSemaphores; @@ -1135,8 +1134,9 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkInstance instance, VkPhysicalDevi void ImGui_ImplVulkanH_CreateWindow(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) { - ImGui_ImplVulkanH_CreateWindowSwapChain(instance, physical_device, device, wd, allocator, width, height, min_image_count); - ImGui_ImplVulkanH_CreateWindowCommandBuffers(instance, physical_device, device, wd, queue_family, allocator); + (void)instance; + ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); + ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); } void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) @@ -1146,8 +1146,8 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui for (uint32_t i = 0; i < wd->ImageCount; i++) { - ImGui_ImplVulkanH_DestroyFrame(instance, device, &wd->Frames[i], allocator); - ImGui_ImplVulkanH_DestroyFrameSemaphores(instance, device, &wd->FrameSemaphores[i], allocator); + ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); + ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); } delete[] wd->Frames; delete[] wd->FrameSemaphores; @@ -1160,9 +1160,8 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui *wd = ImGui_ImplVulkanH_Window(); } -void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) { - (void)instance; vkDestroyFence(device, fd->Fence, allocator); vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); vkDestroyCommandPool(device, fd->CommandPool, allocator); @@ -1174,17 +1173,15 @@ void ImGui_ImplVulkanH_DestroyFrame(VkInstance instance, VkDevice device, ImGui_ vkDestroyFramebuffer(device, fd->Framebuffer, allocator); } -void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) { - (void)instance; vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator); vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator); fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; } -void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) { - (void)instance; if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } @@ -1193,10 +1190,10 @@ void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkInstance instance, VkDevice d buffers->IndexBufferSize = 0; } -void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) { for (uint32_t n = 0; n < buffers->Count; n++) - ImGui_ImplVulkanH_DestroyFrameRenderBuffers(instance, device, &buffers->FrameRenderBuffers[n], allocator); + ImGui_ImplVulkanH_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator); delete[] buffers->FrameRenderBuffers; buffers->FrameRenderBuffers = NULL; buffers->Index = 0; From d61caf57145294fe98445eff3f21e24c71bd58c4 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 18:52:40 +0200 Subject: [PATCH 234/566] Vulkan, Viewports: ImGui_ImplVulkan_RenderDrawData and renderer back-end automatically manage ImGui_ImplVulkanH_WindowRenderBuffers for each viewports so user doesn't have to do it. (#2461, #2348, #2378, #2097) --- examples/imgui_impl_vulkan.cpp | 59 ++++++++++++++++++++++------------ examples/imgui_impl_vulkan.h | 4 --- imgui.cpp | 1 + imgui.h | 3 +- 4 files changed, 42 insertions(+), 25 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 1c9e7b51..2dc93b3e 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -65,6 +65,17 @@ struct ImGui_ImplVulkanH_WindowRenderBuffers ImGui_ImplVulkanH_FrameRenderBuffers* FrameRenderBuffers; }; +// For multi-viewport support +struct ImGuiViewportDataVulkan +{ + bool WindowOwned; + ImGui_ImplVulkanH_Window Window; // Used by secondary viewports only + ImGui_ImplVulkanH_WindowRenderBuffers RenderBuffers; // Used by all viewports + + ImGuiViewportDataVulkan() { WindowOwned = false; memset(&RenderBuffers, 0, sizeof(RenderBuffers)); } + ~ImGuiViewportDataVulkan() { } +}; + // Vulkan data static ImGui_ImplVulkan_InitInfo g_VulkanInitInfo = {}; static VkRenderPass g_RenderPass = VK_NULL_HANDLE; @@ -83,14 +94,14 @@ static VkImageView g_FontView = VK_NULL_HANDLE; static VkDeviceMemory g_UploadBufferMemory = VK_NULL_HANDLE; static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; -// Render buffers -static ImGui_ImplVulkanH_WindowRenderBuffers g_MainWindowRenderBuffers; - // Forward Declarations +bool ImGui_ImplVulkan_CreateDeviceObjects(); +void ImGui_ImplVulkan_DestroyDeviceObjects(); void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(VkDevice device, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); @@ -274,8 +285,10 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; - // Allocate array to store enough vertex/index buffers - ImGui_ImplVulkanH_WindowRenderBuffers* wrb = &g_MainWindowRenderBuffers; + // Allocate array to store enough vertex/index buffers. Each unique viewport gets its own storage. + ImGuiViewportDataVulkan* viewport_renderer_data = (ImGuiViewportDataVulkan*)draw_data->OwnerViewport->RendererUserData; + IM_ASSERT(viewport_renderer_data != NULL); + ImGui_ImplVulkanH_WindowRenderBuffers* wrb = &viewport_renderer_data->RenderBuffers; if (wrb->FrameRenderBuffers == NULL) { wrb->Index = 0; @@ -777,7 +790,7 @@ void ImGui_ImplVulkan_DestroyFontUploadObjects() void ImGui_ImplVulkan_DestroyDeviceObjects() { ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; - ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &g_MainWindowRenderBuffers, v->Allocator); + ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(v->Device, v->Allocator); ImGui_ImplVulkan_DestroyFontUploadObjects(); if (g_FontView) { vkDestroyImageView(v->Device, g_FontView, v->Allocator); g_FontView = VK_NULL_HANDLE; } @@ -809,6 +822,10 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend g_RenderPass = render_pass; ImGui_ImplVulkan_CreateDeviceObjects(); + // Our render function expect RendererUserData to be storing the window render buffer we need (for the main viewport we won't use ->Window) + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->RendererUserData = IM_NEW(ImGuiViewportDataVulkan)(); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui_ImplVulkan_InitPlatformInterface(); @@ -830,11 +847,13 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) IM_ASSERT(min_image_count >= 2); if (g_VulkanInitInfo.MinImageCount == min_image_count) return; - IM_ASSERT(0); // FIXME-VIEWPORT: Need to recreate all swap chains? + + IM_ASSERT(0); // FIXME-VIEWPORT: Unsupported. Need to recreate all swap chains! ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err = vkDeviceWaitIdle(v->Device); check_vk_result(err); - ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &g_MainWindowRenderBuffers, v->Allocator); + + ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(v->Device, v->Allocator); g_VulkanInitInfo.MinImageCount = min_image_count; } @@ -1211,22 +1230,19 @@ void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVul buffers->Count = 0; } +void ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(VkDevice device, const VkAllocationCallbacks* allocator) +{ + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + for (int n = 0; n < platform_io.Viewports.Size; n++) + if (ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)platform_io.Viewports[n]->RendererUserData) + ImGui_ImplVulkanH_DestroyWindowRenderBuffers(device, &data->RenderBuffers, allocator); +} //-------------------------------------------------------------------------------------------------------- // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously. // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. //-------------------------------------------------------------------------------------------------------- -// FIXME-PLATFORM: Vulkan support unfinished -//-------------------------------------------------------------------------------------------------------- - -struct ImGuiViewportDataVulkan -{ - ImGui_ImplVulkanH_Window Window; - - ImGuiViewportDataVulkan() { } - ~ImGuiViewportDataVulkan() { } -}; static void ImGui_ImplVulkan_CreateWindow(ImGuiViewport* viewport) { @@ -1263,6 +1279,7 @@ static void ImGui_ImplVulkan_CreateWindow(ImGuiViewport* viewport) // Create SwapChain, RenderPass, Framebuffer, etc. wd->ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true; ImGui_ImplVulkanH_CreateWindow(v->Instance, v->PhysicalDevice, v->Device, wd, v->QueueFamily, v->Allocator, (int)viewport->Size.x, (int)viewport->Size.y, v->MinImageCount); + data->WindowOwned = true; } static void ImGui_ImplVulkan_DestroyWindow(ImGuiViewport* viewport) @@ -1271,7 +1288,9 @@ static void ImGui_ImplVulkan_DestroyWindow(ImGuiViewport* viewport) if (ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)viewport->RendererUserData) { ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; - ImGui_ImplVulkanH_DestroyWindow(v->Instance, v->Device, &data->Window, v->Allocator); + if (data->WindowOwned) + ImGui_ImplVulkanH_DestroyWindow(v->Instance, v->Device, &data->Window, v->Allocator); + ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &data->RenderBuffers, v->Allocator); IM_DELETE(data); } viewport->RendererUserData = NULL; @@ -1380,7 +1399,7 @@ static void ImGui_ImplVulkan_SwapBuffers(ImGuiViewport* viewport, void*) err = vkQueuePresentKHR(v->Queue, &info); check_vk_result(err); - wd->FrameIndex = (wd->FrameIndex + 1) % wd->ImageCount; // This is for the next vkWaitForFences() + wd->FrameIndex = (wd->FrameIndex + 1) % wd->ImageCount; // This is for the next vkWaitForFences() wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index eba29c42..9ff70c01 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -49,10 +49,6 @@ IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer comm IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) -// Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. -IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); -IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyDeviceObjects(); - //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers diff --git a/imgui.cpp b/imgui.cpp index c96b2d8a..51123a68 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4000,6 +4000,7 @@ static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVectorDisplayPos = viewport->Pos; draw_data->DisplaySize = viewport->Size; draw_data->FramebufferScale = ImGui::GetIO().DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis? + draw_data->OwnerViewport = viewport; for (int n = 0; n < draw_lists->Size; n++) { draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size; diff --git a/imgui.h b/imgui.h index f990e066..fc9d4146 100644 --- a/imgui.h +++ b/imgui.h @@ -2012,11 +2012,12 @@ struct ImDrawData ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use) ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use) ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. + ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). // Functions ImDrawData() { Valid = false; Clear(); } ~ImDrawData() { Clear(); } - void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext! + void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.f, 0.f); OwnerViewport = NULL; } // The ImDrawList are owned by ImGuiContext! IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; From bd351e9ac57fa0730d9407e8785996a6080f1f35 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 20:20:08 +0200 Subject: [PATCH 235/566] Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 20 ++++++++++--------- imgui.h | 33 +++++++++++++++++++------------- imgui_draw.cpp | 22 ++++++++++----------- imgui_widgets.cpp | 4 ++-- misc/freetype/imgui_freetype.cpp | 12 ++++++------ misc/freetype/imgui_freetype.h | 2 +- 7 files changed, 53 insertions(+), 42 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1822526f..ec24a20b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] +- Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert + to using the ImGui::MemAlloc()/MemFree() calls directly. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. diff --git a/imgui.cpp b/imgui.cpp index c0184541..4cb82e16 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1307,7 +1307,7 @@ void ImStrncpy(char* dst, const char* src, size_t count) char* ImStrdup(const char* str) { size_t len = strlen(str); - void* buf = ImGui::MemAlloc(len + 1); + void* buf = IM_ALLOC(len + 1); return (char*)memcpy(buf, (const void*)str, len + 1); } @@ -1317,8 +1317,8 @@ char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) size_t src_size = strlen(src) + 1; if (dst_buf_size < src_size) { - ImGui::MemFree(dst); - dst = (char*)ImGui::MemAlloc(src_size); + IM_FREE(dst); + dst = (char*)IM_ALLOC(src_size); if (p_dst_size) *p_dst_size = src_size; } @@ -1527,7 +1527,7 @@ FILE* ImFileOpen(const char* filename, const char* mode) } // Load file content into memory -// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() +// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes) { IM_ASSERT(filename && file_open_mode); @@ -1546,7 +1546,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_ } size_t file_size = (size_t)file_size_signed; - void* file_data = ImGui::MemAlloc(file_size + padding_bytes); + void* file_data = IM_ALLOC(file_size + padding_bytes); if (file_data == NULL) { fclose(f); @@ -1555,7 +1555,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_ if (fread(file_data, 1, file_size, f) != file_size) { fclose(f); - ImGui::MemFree(file_data); + IM_FREE(file_data); return NULL; } if (padding_bytes > 0) @@ -2962,6 +2962,7 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) return ImMax(wrap_pos_x - pos.x, 1.0f); } +// IM_ALLOC() == ImGui::MemAlloc() void* ImGui::MemAlloc(size_t size) { if (ImGuiContext* ctx = GImGui) @@ -2969,6 +2970,7 @@ void* ImGui::MemAlloc(size_t size) return GImAllocatorAllocFunc(size, GImAllocatorUserData); } +// IM_FREE() == ImGui::MemFree() void ImGui::MemFree(void* ptr) { if (ptr) @@ -9093,7 +9095,7 @@ void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) if (!file_data) return; LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); - ImGui::MemFree(file_data); + IM_FREE(file_data); } ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) @@ -9117,7 +9119,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. if (ini_size == 0) ini_size = strlen(ini_data); - char* buf = (char*)ImGui::MemAlloc(ini_size + 1); + char* buf = (char*)IM_ALLOC(ini_size + 1); char* buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); buf[ini_size] = 0; @@ -9164,7 +9166,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); } } - ImGui::MemFree(buf); + IM_FREE(buf); g.SettingsLoaded = true; } diff --git a/imgui.h b/imgui.h index 1d907b04..c4400d84 100644 --- a/imgui.h +++ b/imgui.h @@ -13,6 +13,7 @@ Index of this file: // Forward declarations and basic types // ImGui API (Dear ImGui end-user API) // Flags & Enumerations +// Memory allocations macros // ImVector<> // ImGuiStyle // ImGuiIO @@ -1185,6 +1186,22 @@ enum ImGuiCond_ #endif }; +//----------------------------------------------------------------------------- +// Helpers: Memory allocations macros +// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +//----------------------------------------------------------------------------- + +struct ImNewDummy {}; +inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symmetrical new() +#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) +#define IM_FREE(_PTR) ImGui::MemFree(_PTR) +#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) +#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } + //----------------------------------------------------------------------------- // Helper: ImVector<> // Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). @@ -1210,7 +1227,7 @@ struct ImVector inline ImVector() { Size = Capacity = 0; Data = NULL; } inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } - inline ~ImVector() { if (Data) ImGui::MemFree(Data); } + inline ~ImVector() { if (Data) IM_FREE(Data); } inline bool empty() const { return Size == 0; } inline int size() const { return Size; } @@ -1219,7 +1236,7 @@ struct ImVector inline T& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } inline const T& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } - inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } + inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } inline T* begin() { return Data; } inline const T* begin() const { return Data; } inline T* end() { return Data + Size; } @@ -1233,7 +1250,7 @@ struct ImVector inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } - inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)ImGui::MemAlloc((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); ImGui::MemFree(Data); } Data = new_data; Capacity = new_capacity; } + inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } @@ -1548,16 +1565,6 @@ typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; // Helpers //----------------------------------------------------------------------------- -// Helper: IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() macros to call MemAlloc + Placement New, Placement Delete + MemFree -// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. -// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. -struct ImNewDummy {}; -inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } -inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symmetrical new() -#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) -#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE -template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } - // Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. // Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); struct ImGuiOnceUponAFrame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 97f25bd4..290fadb8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -130,8 +130,8 @@ namespace IMGUI_STB_NAMESPACE #ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) #ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION -#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) -#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) +#define STBTT_malloc(x,u) ((void)(u), IM_ALLOC(x)) +#define STBTT_free(x,u) ((void)(u), IM_FREE(x)) #define STBTT_assert(x) IM_ASSERT(x) #define STBTT_fmod(x,y) ImFmod(x,y) #define STBTT_sqrt(x) ImSqrt(x) @@ -1459,7 +1459,7 @@ void ImFontAtlas::ClearInputData() for (int i = 0; i < ConfigData.Size; i++) if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) { - ImGui::MemFree(ConfigData[i].FontData); + IM_FREE(ConfigData[i].FontData); ConfigData[i].FontData = NULL; } @@ -1480,9 +1480,9 @@ void ImFontAtlas::ClearTexData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); if (TexPixelsAlpha8) - ImGui::MemFree(TexPixelsAlpha8); + IM_FREE(TexPixelsAlpha8); if (TexPixelsRGBA32) - ImGui::MemFree(TexPixelsRGBA32); + IM_FREE(TexPixelsRGBA32); TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; } @@ -1528,7 +1528,7 @@ void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_wid GetTexDataAsAlpha8(&pixels, NULL, NULL); if (pixels) { - TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)TexWidth * (size_t)TexHeight * 4); + TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4); const unsigned char* src = pixels; unsigned int* dst = TexPixelsRGBA32; for (int n = TexWidth * TexHeight; n > 0; n--) @@ -1560,7 +1560,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) new_font_cfg.DstFont = Fonts.back(); if (!new_font_cfg.FontDataOwnedByAtlas) { - new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); + new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize); new_font_cfg.FontDataOwnedByAtlas = true; memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); } @@ -1645,7 +1645,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float si ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data); - unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); + unsigned char* buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size); stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); @@ -1657,10 +1657,10 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_d ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; - void* compressed_ttf = ImGui::MemAlloc((size_t)compressed_ttf_size); + void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); - ImGui::MemFree(compressed_ttf); + IM_FREE(compressed_ttf); return font; } @@ -1960,7 +1960,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) // 7. Allocate texture atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight); + atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); spc.pixels = atlas->TexPixelsAlpha8; spc.height = atlas->TexHeight; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4ebbc1f5..d6d5ac84 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3540,7 +3540,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1; - char* clipboard_data = (char*)MemAlloc(clipboard_data_len * sizeof(char)); + char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char)); ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie); SetClipboardText(clipboard_data); MemFree(clipboard_data); @@ -3559,7 +3559,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Filter pasted buffer const int clipboard_len = (int)strlen(clipboard); - ImWchar* clipboard_filtered = (ImWchar*)MemAlloc((clipboard_len+1) * sizeof(ImWchar)); + ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) { diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 012eae75..4a579ed2 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -398,7 +398,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024; int buf_bitmap_current_used_bytes = 0; ImVector buf_bitmap_buffers; - buf_bitmap_buffers.push_back((unsigned char*)ImGui::MemAlloc(BITMAP_BUFFERS_CHUNK_SIZE)); + buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); // 4. Gather glyphs sizes so we can pack them in our virtual canvas. // 8. Render/rasterize font characters into the texture @@ -440,7 +440,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE) { buf_bitmap_current_used_bytes = 0; - buf_bitmap_buffers.push_back((unsigned char*)ImGui::MemAlloc(BITMAP_BUFFERS_CHUNK_SIZE)); + buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); } // Blit rasterized pixels to our temporary buffer and keep a pointer to it. @@ -493,7 +493,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns // 7. Allocate texture atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight); + atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); // 8. Copy rasterized font characters back into the main texture @@ -557,7 +557,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns // Cleanup for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++) - ImGui::MemFree(buf_bitmap_buffers[buf_i]); + IM_FREE(buf_bitmap_buffers[buf_i]); for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) src_tmp_array[src_i].~ImFontBuildSrcDataFT(); @@ -567,8 +567,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns } // Default memory allocators -static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return ImGui::MemAlloc(size); } -static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); ImGui::MemFree(ptr); } +static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); } +static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); } // Current memory allocators static void* (*GImFreeTypeAllocFunc)(size_t size, void* user_data) = ImFreeTypeDefaultAllocFunc; diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 9df5780e..b4b0fd66 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -29,7 +29,7 @@ namespace ImGuiFreeType IMGUI_API bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags = 0); - // By default ImGuiFreeType will use ImGui::MemAlloc()/MemFree(). + // By default ImGuiFreeType will use IM_ALLOC()/IM_FREE(). // However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired: IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL); } From c8fd4afd753f64d4bd24b3f4fe21a64afaec53a1 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 20:20:08 +0200 Subject: [PATCH 236/566] Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 20 ++++++++++--------- imgui.h | 33 +++++++++++++++++++------------- imgui_draw.cpp | 22 ++++++++++----------- imgui_widgets.cpp | 4 ++-- misc/freetype/imgui_freetype.cpp | 12 ++++++------ misc/freetype/imgui_freetype.h | 2 +- 7 files changed, 53 insertions(+), 42 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a4cbd4de..d753375e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,8 @@ Other Changes: - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] +- Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert + to using the ImGui::MemAlloc()/MemFree() calls directly. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. diff --git a/imgui.cpp b/imgui.cpp index c0184541..4cb82e16 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1307,7 +1307,7 @@ void ImStrncpy(char* dst, const char* src, size_t count) char* ImStrdup(const char* str) { size_t len = strlen(str); - void* buf = ImGui::MemAlloc(len + 1); + void* buf = IM_ALLOC(len + 1); return (char*)memcpy(buf, (const void*)str, len + 1); } @@ -1317,8 +1317,8 @@ char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) size_t src_size = strlen(src) + 1; if (dst_buf_size < src_size) { - ImGui::MemFree(dst); - dst = (char*)ImGui::MemAlloc(src_size); + IM_FREE(dst); + dst = (char*)IM_ALLOC(src_size); if (p_dst_size) *p_dst_size = src_size; } @@ -1527,7 +1527,7 @@ FILE* ImFileOpen(const char* filename, const char* mode) } // Load file content into memory -// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() +// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes) { IM_ASSERT(filename && file_open_mode); @@ -1546,7 +1546,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_ } size_t file_size = (size_t)file_size_signed; - void* file_data = ImGui::MemAlloc(file_size + padding_bytes); + void* file_data = IM_ALLOC(file_size + padding_bytes); if (file_data == NULL) { fclose(f); @@ -1555,7 +1555,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_ if (fread(file_data, 1, file_size, f) != file_size) { fclose(f); - ImGui::MemFree(file_data); + IM_FREE(file_data); return NULL; } if (padding_bytes > 0) @@ -2962,6 +2962,7 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) return ImMax(wrap_pos_x - pos.x, 1.0f); } +// IM_ALLOC() == ImGui::MemAlloc() void* ImGui::MemAlloc(size_t size) { if (ImGuiContext* ctx = GImGui) @@ -2969,6 +2970,7 @@ void* ImGui::MemAlloc(size_t size) return GImAllocatorAllocFunc(size, GImAllocatorUserData); } +// IM_FREE() == ImGui::MemFree() void ImGui::MemFree(void* ptr) { if (ptr) @@ -9093,7 +9095,7 @@ void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) if (!file_data) return; LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); - ImGui::MemFree(file_data); + IM_FREE(file_data); } ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) @@ -9117,7 +9119,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. if (ini_size == 0) ini_size = strlen(ini_data); - char* buf = (char*)ImGui::MemAlloc(ini_size + 1); + char* buf = (char*)IM_ALLOC(ini_size + 1); char* buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); buf[ini_size] = 0; @@ -9164,7 +9166,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); } } - ImGui::MemFree(buf); + IM_FREE(buf); g.SettingsLoaded = true; } diff --git a/imgui.h b/imgui.h index 1d907b04..c4400d84 100644 --- a/imgui.h +++ b/imgui.h @@ -13,6 +13,7 @@ Index of this file: // Forward declarations and basic types // ImGui API (Dear ImGui end-user API) // Flags & Enumerations +// Memory allocations macros // ImVector<> // ImGuiStyle // ImGuiIO @@ -1185,6 +1186,22 @@ enum ImGuiCond_ #endif }; +//----------------------------------------------------------------------------- +// Helpers: Memory allocations macros +// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +//----------------------------------------------------------------------------- + +struct ImNewDummy {}; +inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symmetrical new() +#define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) +#define IM_FREE(_PTR) ImGui::MemFree(_PTR) +#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) +#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } + //----------------------------------------------------------------------------- // Helper: ImVector<> // Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). @@ -1210,7 +1227,7 @@ struct ImVector inline ImVector() { Size = Capacity = 0; Data = NULL; } inline ImVector(const ImVector& src) { Size = Capacity = 0; Data = NULL; operator=(src); } inline ImVector& operator=(const ImVector& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; } - inline ~ImVector() { if (Data) ImGui::MemFree(Data); } + inline ~ImVector() { if (Data) IM_FREE(Data); } inline bool empty() const { return Size == 0; } inline int size() const { return Size; } @@ -1219,7 +1236,7 @@ struct ImVector inline T& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } inline const T& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } - inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } + inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } inline T* begin() { return Data; } inline const T* begin() const { return Data; } inline T* end() { return Data + Size; } @@ -1233,7 +1250,7 @@ struct ImVector inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } - inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)ImGui::MemAlloc((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); ImGui::MemFree(Data); } Data = new_data; Capacity = new_capacity; } + inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } @@ -1548,16 +1565,6 @@ typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; // Helpers //----------------------------------------------------------------------------- -// Helper: IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() macros to call MemAlloc + Placement New, Placement Delete + MemFree -// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. -// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. -struct ImNewDummy {}; -inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } -inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symmetrical new() -#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) -#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE -template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } - // Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. // Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); struct ImGuiOnceUponAFrame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 97f25bd4..290fadb8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -130,8 +130,8 @@ namespace IMGUI_STB_NAMESPACE #ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds) #ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION -#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) -#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) +#define STBTT_malloc(x,u) ((void)(u), IM_ALLOC(x)) +#define STBTT_free(x,u) ((void)(u), IM_FREE(x)) #define STBTT_assert(x) IM_ASSERT(x) #define STBTT_fmod(x,y) ImFmod(x,y) #define STBTT_sqrt(x) ImSqrt(x) @@ -1459,7 +1459,7 @@ void ImFontAtlas::ClearInputData() for (int i = 0; i < ConfigData.Size; i++) if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) { - ImGui::MemFree(ConfigData[i].FontData); + IM_FREE(ConfigData[i].FontData); ConfigData[i].FontData = NULL; } @@ -1480,9 +1480,9 @@ void ImFontAtlas::ClearTexData() { IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); if (TexPixelsAlpha8) - ImGui::MemFree(TexPixelsAlpha8); + IM_FREE(TexPixelsAlpha8); if (TexPixelsRGBA32) - ImGui::MemFree(TexPixelsRGBA32); + IM_FREE(TexPixelsRGBA32); TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; } @@ -1528,7 +1528,7 @@ void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_wid GetTexDataAsAlpha8(&pixels, NULL, NULL); if (pixels) { - TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)TexWidth * (size_t)TexHeight * 4); + TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4); const unsigned char* src = pixels; unsigned int* dst = TexPixelsRGBA32; for (int n = TexWidth * TexHeight; n > 0; n--) @@ -1560,7 +1560,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) new_font_cfg.DstFont = Fonts.back(); if (!new_font_cfg.FontDataOwnedByAtlas) { - new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); + new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize); new_font_cfg.FontDataOwnedByAtlas = true; memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); } @@ -1645,7 +1645,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float si ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data); - unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); + unsigned char* buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size); stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); @@ -1657,10 +1657,10 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_d ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; - void* compressed_ttf = ImGui::MemAlloc((size_t)compressed_ttf_size); + void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); - ImGui::MemFree(compressed_ttf); + IM_FREE(compressed_ttf); return font; } @@ -1960,7 +1960,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) // 7. Allocate texture atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight); + atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); spc.pixels = atlas->TexPixelsAlpha8; spc.height = atlas->TexHeight; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4ebbc1f5..d6d5ac84 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3540,7 +3540,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1; - char* clipboard_data = (char*)MemAlloc(clipboard_data_len * sizeof(char)); + char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char)); ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie); SetClipboardText(clipboard_data); MemFree(clipboard_data); @@ -3559,7 +3559,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Filter pasted buffer const int clipboard_len = (int)strlen(clipboard); - ImWchar* clipboard_filtered = (ImWchar*)MemAlloc((clipboard_len+1) * sizeof(ImWchar)); + ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) { diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 012eae75..4a579ed2 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -398,7 +398,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024; int buf_bitmap_current_used_bytes = 0; ImVector buf_bitmap_buffers; - buf_bitmap_buffers.push_back((unsigned char*)ImGui::MemAlloc(BITMAP_BUFFERS_CHUNK_SIZE)); + buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); // 4. Gather glyphs sizes so we can pack them in our virtual canvas. // 8. Render/rasterize font characters into the texture @@ -440,7 +440,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE) { buf_bitmap_current_used_bytes = 0; - buf_bitmap_buffers.push_back((unsigned char*)ImGui::MemAlloc(BITMAP_BUFFERS_CHUNK_SIZE)); + buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE)); } // Blit rasterized pixels to our temporary buffer and keep a pointer to it. @@ -493,7 +493,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns // 7. Allocate texture atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight); atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight); - atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight); + atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight); memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight); // 8. Copy rasterized font characters back into the main texture @@ -557,7 +557,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns // Cleanup for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++) - ImGui::MemFree(buf_bitmap_buffers[buf_i]); + IM_FREE(buf_bitmap_buffers[buf_i]); for (int src_i = 0; src_i < src_tmp_array.Size; src_i++) src_tmp_array[src_i].~ImFontBuildSrcDataFT(); @@ -567,8 +567,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns } // Default memory allocators -static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return ImGui::MemAlloc(size); } -static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); ImGui::MemFree(ptr); } +static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); } +static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); } // Current memory allocators static void* (*GImFreeTypeAllocFunc)(size_t size, void* user_data) = ImFreeTypeDefaultAllocFunc; diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index 9df5780e..b4b0fd66 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -29,7 +29,7 @@ namespace ImGuiFreeType IMGUI_API bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags = 0); - // By default ImGuiFreeType will use ImGui::MemAlloc()/MemFree(). + // By default ImGuiFreeType will use IM_ALLOC()/IM_FREE(). // However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired: IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL); } From e099a7dc7493ee8732df3e8e503112930dbfb645 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 5 Apr 2019 20:27:46 +0200 Subject: [PATCH 237/566] Vulkan: Bits. Using IM_ALLOC/IM_FREE instead of new[] / delete[]. --- examples/example_glfw_vulkan/main.cpp | 20 +++++++++----------- examples/example_sdl_vulkan/main.cpp | 20 +++++++++----------- examples/imgui_impl_vulkan.cpp | 26 +++++++++++++------------- examples/imgui_impl_vulkan.h | 8 ++------ 4 files changed, 33 insertions(+), 41 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 972c12b0..53c8aebd 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -2,9 +2,9 @@ // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. -// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering back-end in your engine/app. -// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. @@ -40,7 +40,7 @@ static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; -static ImGui_ImplVulkanH_Window g_WindowData; +static ImGui_ImplVulkanH_Window g_MainWindowData; static int g_MinImageCount = 2; static bool g_SwapChainRebuild = false; static int g_SwapChainResizeWidth = 0; @@ -193,6 +193,8 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) } } +// All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo. +// Your real engine/app may not use them. static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; @@ -241,11 +243,7 @@ static void CleanupVulkan() static void CleanupVulkanWindow() { - // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_Window helpers, - // however you would instead need to call ImGui_ImplVulkan_DestroyFrameRenderBuffers() on each - // ImGui_ImplVulkan_FrameRenderBuffers structure that you own. - ImGui_ImplVulkanH_Window* wd = &g_WindowData; - ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } static void FrameRender(ImGui_ImplVulkanH_Window* wd) @@ -365,7 +363,7 @@ int main(int, char**) int w, h; glfwGetFramebufferSize(window, &w, &h); glfwSetFramebufferSizeCallback(window, glfw_resize_callback); - ImGui_ImplVulkanH_Window* wd = &g_WindowData; + ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context @@ -458,8 +456,8 @@ int main(int, char**) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); - g_WindowData.FrameIndex = 0; + ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); + g_MainWindowData.FrameIndex = 0; } // Start the Dear ImGui frame diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index d2a829c4..45f4fce8 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -2,9 +2,9 @@ // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. -// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering back-end in your engine/app. -// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. @@ -32,7 +32,7 @@ static VkDebugReportCallbackEXT g_DebugReport = VK_NULL_HANDLE; static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE; static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; -static ImGui_ImplVulkanH_Window g_WindowData; +static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; static int g_SwapChainResizeWidth = 0; @@ -185,6 +185,8 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) } } +// All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo. +// Your real engine/app may not use them. static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface, int width, int height) { wd->Surface = surface; @@ -233,11 +235,7 @@ static void CleanupVulkan() static void CleanupVulkanWindow() { - // In a normal engine/app integration, you wouldn't use the ImGui_ImplVulkanH_Window helpers, - // however you would instead need to call ImGui_ImplVulkan_DestroyFrameRenderBuffers() on each - // ImGui_ImplVulkan_FrameRenderBuffers structure that you own. - ImGui_ImplVulkanH_Window* wd = &g_WindowData; - ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, wd, g_Allocator); + ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } static void FrameRender(ImGui_ImplVulkanH_Window* wd) @@ -351,7 +349,7 @@ int main(int, char**) // Create Framebuffers int w, h; SDL_GetWindowSize(window, &w, &h); - ImGui_ImplVulkanH_Window* wd = &g_WindowData; + ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context @@ -455,8 +453,8 @@ int main(int, char**) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_WindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); - g_WindowData.FrameIndex = 0; + ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); + g_MainWindowData.FrameIndex = 0; } // Start the Dear ImGui frame diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 48237139..e2da42ba 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -12,9 +12,9 @@ // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. -// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering back-end in your engine/app. -// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. @@ -86,6 +86,8 @@ static VkBuffer g_UploadBuffer = VK_NULL_HANDLE; static ImGui_ImplVulkanH_WindowRenderBuffers g_MainWindowRenderBuffers; // Forward Declarations +bool ImGui_ImplVulkan_CreateDeviceObjects(); +void ImGui_ImplVulkan_DestroyDeviceObjects(); void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); @@ -230,7 +232,7 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory VkResult err; if (buffer != VK_NULL_HANDLE) vkDestroyBuffer(v->Device, buffer, v->Allocator); - if (buffer_memory) + if (buffer_memory != VK_NULL_HANDLE) vkFreeMemory(v->Device, buffer_memory, v->Allocator); VkDeviceSize vertex_buffer_size_aligned = ((new_size - 1) / g_BufferMemoryAlignment + 1) * g_BufferMemoryAlignment; @@ -275,7 +277,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm { wrb->Index = 0; wrb->Count = v->ImageCount; - wrb->FrameRenderBuffers = new ImGui_ImplVulkanH_FrameRenderBuffers[wrb->Count]; + wrb->FrameRenderBuffers = (ImGui_ImplVulkanH_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count); memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count); } IM_ASSERT(wrb->Count == v->ImageCount); @@ -844,8 +846,6 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- -#include // malloc - VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space) { IM_ASSERT(request_formats != NULL); @@ -986,8 +986,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); } - delete[] wd->Frames; - delete[] wd->FrameSemaphores; + IM_FREE(wd->Frames); + IM_FREE(wd->FrameSemaphores); wd->Frames = NULL; wd->FrameSemaphores = NULL; wd->ImageCount = 0; @@ -1043,8 +1043,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V check_vk_result(err); IM_ASSERT(wd->Frames == NULL); - wd->Frames = new ImGui_ImplVulkanH_Frame[wd->ImageCount]; - wd->FrameSemaphores = new ImGui_ImplVulkanH_FrameSemaphores[wd->ImageCount]; + wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount); + wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->ImageCount); memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount); memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->ImageCount); for (uint32_t i = 0; i < wd->ImageCount; i++) @@ -1149,8 +1149,8 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); } - delete[] wd->Frames; - delete[] wd->FrameSemaphores; + IM_FREE(wd->Frames); + IM_FREE(wd->FrameSemaphores); wd->Frames = NULL; wd->FrameSemaphores = NULL; vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1194,7 +1194,7 @@ void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVul { for (uint32_t n = 0; n < buffers->Count; n++) ImGui_ImplVulkanH_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator); - delete[] buffers->FrameRenderBuffers; + IM_FREE(buffers->FrameRenderBuffers); buffers->FrameRenderBuffers = NULL; buffers->Index = 0; buffers->Count = 0; diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 8b5421cc..cff866d9 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -12,9 +12,9 @@ // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. -// - Common ImGui_ImplVulkan_XXXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. +// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering back-end in your engine/app. -// - Helper ImGui_ImplVulkanH_XXXX functions and structures are only used by this example (main.cpp) and by +// - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. @@ -48,10 +48,6 @@ IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer comm IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) -// Called by ImGui_ImplVulkan_Init(), might be useful elsewhere. -IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateDeviceObjects(); -IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyDeviceObjects(); - //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers From c43dab24147da9931f427934377b165e01084d0c Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 7 Apr 2019 15:57:07 +0200 Subject: [PATCH 238/566] Vulkan: Fix not incrementing semaphore index. (#2472, #2071) --- examples/example_glfw_vulkan/main.cpp | 1 + examples/example_sdl_vulkan/main.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 53c8aebd..43abd3e7 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -320,6 +320,7 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); check_vk_result(err); + wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } static void glfw_error_callback(int error, const char* description) diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 45f4fce8..ad789462 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -312,6 +312,7 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); check_vk_result(err); + wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } int main(int, char**) From 302af7b2c991d8a0857640358f6ee00f3464c995 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 7 Apr 2019 16:22:41 +0200 Subject: [PATCH 239/566] FAQ tweaks. Add missing entries in imgui.cpp (which until now where only in the README). --- docs/README.md | 23 +++++++++++++---------- docs/issue_template.md | 6 +++--- imgui.cpp | 42 ++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 56 insertions(+), 15 deletions(-) diff --git a/docs/README.md b/docs/README.md index febacf05..ba48517e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -219,29 +219,32 @@ Frequently Asked Question (FAQ) **Where is the documentation?** -- The documentation is at the top of imgui.cpp + effectively imgui.h. -- Example code is in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output. -- Standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder. -- We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort. -- Your programming IDE is your friend, find the type or function declaration to find comments associated to it. + This library is poorly documented at the moment and expects of the user to be acquainted with C/C++. + - Run the examples/ applications and explore them. + - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. + - The demo covers most features of Dear ImGui, so you can read the code and see its output. + - See documentation and comments at the top of imgui.cpp + effectively imgui.h. + - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder to explain how to integrate Dear ImGui with your own engine/application. + - Your programming IDE is your friend, find the type or function declaration to find comments associated to it. + - We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort. **Which version should I get?** I occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. -You may also peak at the [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features in the `docking` branch. Several projects are using this branch and it is kept in sync with master regularly. +You may also peak at the [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features in the `docking` branch. Many projects are using this branch and it is kept in sync with master regularly. **Who uses Dear ImGui?** -See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) and [Software using dear imgui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) pages for an (incomplete) list of games/software which are publicly known to use dear imgui. Please add yours if you can! +See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) and [Software using dear imgui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for a list of games/software which are publicly known to use dear imgui. Please add yours if you can! **Why the odd dual naming, "Dear ImGui" vs "ImGui"?** -The library started its life as "ImGui" due to the fact that I didn't give it a proper name when I released 1.0 and had no particular expectation that it would taker off. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations (e.g. Unity uses it own implementation of the IMGUI paradigm). It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "Dear ImGui" that people can use to refer to this specific library in ambiguous situations. Please try to refer to it as "Dear ImGui". +The library started its life as "ImGui" due to the fact that I didn't give it a proper name when I released 1.0 and had no particular expectation that it would take off. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations (e.g. Unity uses it own implementation of the IMGUI paradigm). To reduce this ambiguity without affecting existing codebases, I have decided on an alternate, longer name "Dear ImGui" that people can use to refer to this specific library. Please try to refer to this library as "Dear ImGui". **How can I tell whether to dispatch mouse/keyboard to imgui or to my application?**
**How can I display an image? What is ImTextureID, how does it works?** -
**How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack.** +
**Why are multiple widgets reacting when I interact with a single one? How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack...**
**How can I use my own math types instead of ImVec2/ImVec4?**
**How can I load a different font than the default?**
**How can I easily use icons in my application?** @@ -254,7 +257,7 @@ The library started its life as "ImGui" due to the fact that I didn't give it a
**I integrated Dear ImGui in my engine and some elements are disappearing when I move windows around..**
**How can I help?** -See the FAQ in imgui.cpp for answers. +See the FAQ in [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp) for answers. **Can you create elaborate/serious tools with Dear ImGui?** diff --git a/docs/issue_template.md b/docs/issue_template.md index 6d88b271..21f0c1a9 100644 --- a/docs/issue_template.md +++ b/docs/issue_template.md @@ -4,11 +4,11 @@ https://github.com/ocornut/imgui/issues/2261 2. IF YOU ARE HAVING AN ISSUE COMPILING/LINKING/RUNNING/LOADING FONTS, please post on the "Getting Started" Discourse forum: -https://discourse.dearimgui.org/c/getting-started +https://discourse.dearimgui.org -3. PLEASE MAKE SURE that you have: read the FAQ in imgui.cpp; explored the contents of ShowDemoWindow() including the Examples menu; searched among Issues; used your IDE to search for keywords in all sources and text files; and read the link provided in (1). +3. PLEASE MAKE SURE that you have: read the FAQ in imgui.cpp; explored the contents of `ShowDemoWindow()` including the Examples menu; searched among Issues; used your IDE to search for keywords in all sources and text files; and read the link provided in (1). -4. Be mindful that messages are being sent to the mailbox of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users, unless they browse the site. +4. Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. 5. Delete points 1-5 and PLEASE FILL THE TEMPLATE BELOW before submitting your issue. diff --git a/imgui.cpp b/imgui.cpp index 4cb82e16..5ee019df 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -37,9 +37,14 @@ DOCUMENTATION - Using gamepad/keyboard navigation controls. - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS + - Where is the documentation? + - Which version should I get? + - Who uses Dear ImGui? + - Why the odd dual naming, "Dear ImGui" vs "ImGui"? - How can I tell whether to dispatch mouse/keyboard to imgui or to my application? - How can I display an image? What is ImTextureID, how does it works? - - How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack. + - Why are multiple widgets reacting when I interact with a single one? How can I have + multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack... - How can I use my own math types instead of ImVec2/ImVec4? - How can I load a different font than the default? - How can I easily use icons in my application? @@ -552,6 +557,39 @@ CODE FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== + Q: Where is the documentation? + A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++. + - Run the examples/ and explore them. + - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. + - The demo covers most features of Dear ImGui, so you can read the code and see its output. + - See documentation and comments at the top of imgui.cpp + effectively imgui.h. + - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ + folder to explain how to integrate Dear ImGui with your own engine/application. + - Your programming IDE is your friend, find the type or function declaration to find comments + associated to it. + + Q: Which version should I get? + A: I occasionally tag Releases (https://github.com/ocornut/imgui/releases) but it is generally safe + and recommended to sync to master/latest. The library is fairly stable and regressions tend to be + fixed fast when reported. You may also peak at the 'docking' branch which includes: + - Docking/Merging features (https://github.com/ocornut/imgui/issues/2109) + - Multi-viewport features (https://github.com/ocornut/imgui/issues/1542) + Many projects are using this branch and it is kept in sync with master regularly. + + Q: Who uses Dear ImGui? + A: See "Quotes" (https://github.com/ocornut/imgui/wiki/Quotes) and + "Software using Dear ImGui" (https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages + for a list of games/software which are publicly known to use dear imgui. Please add yours if you can! + + Q: Why the odd dual naming, "Dear ImGui" vs "ImGui"? + A: The library started its life as "ImGui" due to the fact that I didn't give it a proper name when + when I released 1.0, and had no particular expectation that it would take off. However, the term IMGUI + (immediate-mode graphical user interface) was coined before and is being used in variety of other + situations (e.g. Unity uses it own implementation of the IMGUI paradigm). + To reduce the ambiguity without affecting existing code bases, I have decided on an alternate, + longer name "Dear ImGui" that people can use to refer to this specific library. + Please try to refer to this library as "Dear ImGui". + Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application? A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } ) - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application. @@ -653,8 +691,8 @@ CODE Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated. + Q: Why are multiple widgets reacting when I interact with a single one? Q: How can I have multiple widgets with the same label or with an empty label? - Q: I have multiple widgets with the same label, and only the first one works. Why is that? A: A primer on labels and the ID Stack... Dear ImGui internally need to uniquely identify UI elements. From 1295205cd4871b29eef8ae633ee7f19b18e92ac9 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 7 Apr 2019 22:27:45 +0200 Subject: [PATCH 240/566] Examples: Vulkan: Fixed warnings. (#2480) --- examples/example_glfw_vulkan/main.cpp | 3 ++- examples/example_sdl_vulkan/main.cpp | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 43abd3e7..e0c062af 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -108,6 +108,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) // Create Vulkan Instance without any debug feature err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); check_vk_result(err); + IM_UNUSED(g_DebugReport); #endif } @@ -142,7 +143,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) break; } free(queues); - IM_ASSERT(g_QueueFamily != -1); + IM_ASSERT(g_QueueFamily != (uint32_t)-1); } // Create Logical Device (with 1 queue) diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index ad789462..812d0988 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -100,6 +100,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) // Create Vulkan Instance without any debug feature err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); check_vk_result(err); + IM_UNUSED(g_DebugReport); #endif } @@ -134,7 +135,7 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) break; } free(queues); - IM_ASSERT(g_QueueFamily != -1); + IM_ASSERT(g_QueueFamily != (uint32_t)-1); } // Create Logical Device (with 1 queue) From 42423d5ea484898fde42e9703035ea5dfaabab50 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 7 Apr 2019 23:02:07 +0200 Subject: [PATCH 241/566] Examples: Makefile: Tweaks so they are more consistent with each others. Added -g./opt/local includes for MacPorts on Mac OS X. (#297) --- examples/example_glfw_opengl2/Makefile | 35 ++++++++++++++---------- examples/example_glfw_opengl3/Makefile | 30 +++++++++++---------- examples/example_glut_opengl2/Makefile | 37 ++++++++++++++------------ examples/example_sdl_opengl2/Makefile | 35 +++++++++++++++--------- examples/example_sdl_opengl3/Makefile | 25 +++++++++-------- 5 files changed, 93 insertions(+), 69 deletions(-) diff --git a/examples/example_glfw_opengl2/Makefile b/examples/example_glfw_opengl2/Makefile index 482b0e5d..3649b717 100644 --- a/examples/example_glfw_opengl2/Makefile +++ b/examples/example_glfw_opengl2/Makefile @@ -19,39 +19,46 @@ SOURCES = main.cpp SOURCES += ../imgui_impl_glfw.cpp ../imgui_impl_opengl2.cpp SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) - UNAME_S := $(shell uname -s) +CXXFLAGS = -I../ -I../../ +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" - LIBS = -lGL `pkg-config --static --libs glfw3` + LIBS += -lGL `pkg-config --static --libs glfw3` - CXXFLAGS = -I../ -I../../ `pkg-config --cflags glfw3` - CXXFLAGS += -Wall -Wformat + CXXFLAGS += `pkg-config --cflags glfw3` CFLAGS = $(CXXFLAGS) endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo - #LIBS += -L/usr/local/lib -lglfw3 - LIBS += -L/usr/local/lib -lglfw + LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo + LIBS += -L/usr/local/lib -L/opt/local/lib + #LIBS += -lglfw3 + LIBS += -lglfw - CXXFLAGS = -I../ -I../../ -I/usr/local/include - CXXFLAGS += -Wall -Wformat + CXXFLAGS += -I/usr/local/include -I/opt/local/include CFLAGS = $(CXXFLAGS) endif ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) - ECHO_MESSAGE = "Windows" - LIBS = -lglfw3 -lgdi32 -lopengl32 -limm32 + ECHO_MESSAGE = "MinGW" + LIBS += -lglfw3 -lgdi32 -lopengl32 -limm32 - CXXFLAGS = -I../ -I../../ -I../libs/gl3w `pkg-config --cflags glfw3` - CXXFLAGS += -Wall -Wformat - CFLAGS = $(CXXFLAGS) + CXXFLAGS += -I../libs/gl3w `pkg-config --cflags glfw3` + CFLAGS = $(CXXFLAGS) endif +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< diff --git a/examples/example_glfw_opengl3/Makefile b/examples/example_glfw_opengl3/Makefile index a9c7007f..e8cf4614 100644 --- a/examples/example_glfw_opengl3/Makefile +++ b/examples/example_glfw_opengl3/Makefile @@ -21,13 +21,17 @@ SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) +CXXFLAGS = -I../ -I../../ +CXXFLAGS += -g -Wall -Wformat +LIBS = + ##--------------------------------------------------------------------- ## OPENGL LOADER ##--------------------------------------------------------------------- ## Using OpenGL loader: gl3w [default] SOURCES += ../libs/gl3w/GL/gl3w.c -CXXFLAGS = -I../libs/gl3w +CXXFLAGS += -I../libs/gl3w ## Using OpenGL loader: glew ## (This assumes a system-wide installation) @@ -44,31 +48,29 @@ CXXFLAGS = -I../libs/gl3w ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" - LIBS = -lGL `pkg-config --static --libs glfw3` + LIBS += -lGL `pkg-config --static --libs glfw3` - CXXFLAGS += -I../ -I../../ `pkg-config --cflags glfw3` - CXXFLAGS += -Wall -Wformat + CXXFLAGS += `pkg-config --cflags glfw3` CFLAGS = $(CXXFLAGS) endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo - #LIBS += -L/usr/local/lib -lglfw3 - LIBS += -L/usr/local/lib -lglfw + LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo + LIBS += -L/usr/local/lib -L/opt/local/lib + #LIBS += -lglfw3 + LIBS += -lglfw - CXXFLAGS += -I../ -I../../ -I/usr/local/include - CXXFLAGS += -Wall -Wformat + CXXFLAGS += -I/usr/local/include -I/opt/local/include CFLAGS = $(CXXFLAGS) endif ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) - ECHO_MESSAGE = "Windows" - LIBS = -lglfw3 -lgdi32 -lopengl32 -limm32 + ECHO_MESSAGE = "MinGW" + LIBS += -lglfw3 -lgdi32 -lopengl32 -limm32 - CXXFLAGS += -I../ -I../../ `pkg-config --cflags glfw3` - CXXFLAGS += -Wall -Wformat - CFLAGS = $(CXXFLAGS) + CXXFLAGS += `pkg-config --cflags glfw3` + CFLAGS = $(CXXFLAGS) endif ##--------------------------------------------------------------------- diff --git a/examples/example_glut_opengl2/Makefile b/examples/example_glut_opengl2/Makefile index 25ddc43a..c381c0c9 100644 --- a/examples/example_glut_opengl2/Makefile +++ b/examples/example_glut_opengl2/Makefile @@ -1,6 +1,6 @@ # # Cross Platform Makefile -# Compatible with Ubuntu 14.04.1 and Mac OS X +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X # # Linux: # apt-get install freeglut3-dev @@ -10,41 +10,44 @@ #CXX = clang++ EXE = example_glut_opengl2 -SOURCES = main.cpp +SOURCES = main.cpp SOURCES += ../imgui_impl_glut.cpp ../imgui_impl_opengl2.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) - UNAME_S := $(shell uname -s) +CXXFLAGS = -I../ -I../../ +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" - LIBS = -lGL -lglut - - CXXFLAGS = -I ../ -I../.. - CXXFLAGS += -Wall -Wformat + LIBS += -lGL -lglut CFLAGS = $(CXXFLAGS) endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS = -framework OpenGL -framework GLUT + LIBS += -framework OpenGL -framework GLUT + LIBS += -L/usr/local/lib -L/opt/local/lib - CXXFLAGS = -I .. -I../.. - CXXFLAGS += -Wall -Wformat + CXXFLAGS += -I/usr/local/include -I/opt/local/include CFLAGS = $(CXXFLAGS) endif ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) - ECHO_MESSAGE = "Windows" - LIBS = -lgdi32 -lopengl32 -limm32 -lglut - - CXXFLAGS = -I ../ -I../../ - CXXFLAGS += -Wall -Wformat - CFLAGS = $(CXXFLAGS) + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 -lglut + CFLAGS = $(CXXFLAGS) endif +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< diff --git a/examples/example_sdl_opengl2/Makefile b/examples/example_sdl_opengl2/Makefile index 4a948aa4..ce29a249 100644 --- a/examples/example_sdl_opengl2/Makefile +++ b/examples/example_sdl_opengl2/Makefile @@ -15,40 +15,49 @@ #CXX = clang++ EXE = example_sdl_opengl2 -SOURCES = main.cpp ../imgui_impl_sdl.cpp ../imgui_impl_opengl2.cpp +SOURCES = main.cpp +SOURCES += ../imgui_impl_sdl.cpp ../imgui_impl_opengl2.cpp SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) - UNAME_S := $(shell uname -s) +CXXFLAGS = -I../ -I../../ +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" - LIBS = -lGL -ldl `sdl2-config --libs` + LIBS += -lGL -ldl `sdl2-config --libs` - CXXFLAGS = -I ../ -I../../ `sdl2-config --cflags` - CXXFLAGS += -Wall -Wformat + CXXFLAGS += `sdl2-config --cflags` CFLAGS = $(CXXFLAGS) endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl2-config --libs` + LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl2-config --libs` + LIBS += -L/usr/local/lib -L/opt/local/lib - CXXFLAGS = -I ../ -I../../ -I/usr/local/include `sdl2-config --cflags` - CXXFLAGS += -Wall -Wformat + CXXFLAGS += `sdl2-config --cflags` + CXXFLAGS += -I/usr/local/include -I/opt/local/include CFLAGS = $(CXXFLAGS) endif ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) - ECHO_MESSAGE = "Windows" - LIBS = -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl2` + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl2` - CXXFLAGS = -I ../ -I../../ `pkg-config --cflags sdl2` - CXXFLAGS += -Wall -Wformat - CFLAGS = $(CXXFLAGS) + CXXFLAGS += `pkg-config --cflags sdl2` + CFLAGS = $(CXXFLAGS) endif +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index 69874119..76601a1b 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -21,13 +21,17 @@ SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) +CXXFLAGS = -I../ -I../../ +CXXFLAGS += -g -Wall -Wformat +LIBS = + ##--------------------------------------------------------------------- ## OPENGL LOADER ##--------------------------------------------------------------------- ## Using OpenGL loader: gl3w [default] SOURCES += ../libs/gl3w/GL/gl3w.c -CXXFLAGS = -I../libs/gl3w +CXXFLAGS += -I../libs/gl3w ## Using OpenGL loader: glew ## (This assumes a system-wide installation) @@ -44,28 +48,27 @@ CXXFLAGS = -I../libs/gl3w ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" - LIBS = -lGL -ldl `sdl2-config --libs` + LIBS += -lGL -ldl `sdl2-config --libs` - CXXFLAGS = -I../ -I../../ -I../libs/gl3w `sdl2-config --cflags` - CXXFLAGS += -Wall -Wformat + CXXFLAGS += -I../libs/gl3w `sdl2-config --cflags` CFLAGS = $(CXXFLAGS) endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" - LIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl2-config --libs` + LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl2-config --libs` + LIBS += -L/usr/local/lib -L/opt/local/lib - CXXFLAGS = -I../ -I../../ -I../libs/gl3w -I/usr/local/include `sdl2-config --cflags` - CXXFLAGS += -Wall -Wformat + CXXFLAGS += -I../libs/gl3w `sdl2-config --cflags` + CXXFLAGS += -I/usr/local/include -I/opt/local/include CFLAGS = $(CXXFLAGS) endif ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) - ECHO_MESSAGE = "Windows" - LIBS = -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl2` + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl2` - CXXFLAGS = -I../ -I../../ -I../libs/gl3w `pkg-config --cflags sdl2` - CXXFLAGS += -Wall -Wformat + CXXFLAGS += -I../libs/gl3w `pkg-config --cflags sdl2` CFLAGS = $(CXXFLAGS) endif From b53630813ecaf7791045a63cb53b3034289427d0 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 7 Apr 2019 23:45:21 +0200 Subject: [PATCH 242/566] Internals: Tweak ItemSize calls. Added todo items. --- docs/TODO.txt | 1 + imgui_widgets.cpp | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 24525947..66fd9459 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -34,6 +34,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - scrolling/style: shadows on scrollable areas to denote that there is more contents - drawdata: make it easy to clone (or swap?) a ImDrawData so user can easily save that data if they use threaded rendering. + - drawlist: add calctextsize func to facilitate consistent code from user pov - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. - drawlist: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). - drawlist: primitives/helpers to manipulate vertices post submission, so e.g. a quad/rect can be resized to fit later submitted content, _without_ using the ChannelSplit api diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d6d5ac84..ec393963 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -642,7 +642,7 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu const ImGuiID id = window->GetID(str_id); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); const float default_size = GetFrameHeight(); - ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); + ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); if (!ItemAdd(bb, id)) return false; @@ -1040,8 +1040,9 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over const ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; - ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); - ItemSize(bb, style.FramePadding.y); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f); + ImRect bb(pos, pos + size); + ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, 0)) return; @@ -1114,7 +1115,7 @@ void ImGui::Dummy(const ImVec2& size) return; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); - ItemSize(bb); + ItemSize(size); ItemAdd(bb, 0); } @@ -5260,7 +5261,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ImVec2 pos = window->DC.CursorPos; pos.y += window->DC.CurrentLineTextBaseOffset; ImRect bb_inner(pos, pos + size); - ItemSize(bb_inner); + ItemSize(size); // Fill horizontal space. ImVec2 window_padding = window->WindowPadding; From 1391904fd23a4367ec80a042bd32044e63c2da84 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 8 Apr 2019 17:27:17 +0200 Subject: [PATCH 243/566] Internals: Selectable: Added ImGuiSelectableFlags_AllowItemOverlap in imgui_internal.h (~ #684, #2341) --- imgui_internal.h | 3 ++- imgui_widgets.cpp | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index bcbaec6a..4bf703d9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -344,7 +344,8 @@ enum ImGuiSelectableFlagsPrivate_ ImGuiSelectableFlags_NoHoldingActiveID = 1 << 10, ImGuiSelectableFlags_PressedOnClick = 1 << 11, ImGuiSelectableFlags_PressedOnRelease = 1 << 12, - ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 13 + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 13, + ImGuiSelectableFlags_AllowItemOverlap = 1 << 14 }; enum ImGuiSeparatorFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ec393963..ad3126cd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5308,6 +5308,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (flags & ImGuiSelectableFlags_PressedOnRelease) button_flags |= ImGuiButtonFlags_PressedOnRelease; if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; + if (flags & ImGuiSelectableFlags_AllowItemOverlap) button_flags |= ImGuiButtonFlags_AllowItemOverlap; + if (flags & ImGuiSelectableFlags_Disabled) selected = false; @@ -5323,6 +5325,9 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (pressed) MarkItemEdited(id); + if (flags & ImGuiSelectableFlags_AllowItemOverlap) + SetItemAllowOverlap(); + // Render if (hovered || selected) { From b8fe0df7df79dcf7560246f9c3510f5e54de6ff6 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 8 Apr 2019 19:16:45 +0200 Subject: [PATCH 244/566] Examples: Null: Added Makefile. --- examples/.gitignore | 3 +- examples/example_null/Makefile | 59 ++++++++++++++++++++++++++++++++++ examples/example_null/main.cpp | 5 +-- 3 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 examples/example_null/Makefile diff --git a/examples/.gitignore b/examples/.gitignore index 428ea446..ddfa5ead 100644 --- a/examples/.gitignore +++ b/examples/.gitignore @@ -31,9 +31,10 @@ xcuserdata ## Unix executables example_glfw_opengl2/example_glfw_opengl2 example_glfw_opengl3/example_glfw_opengl3 +example_glut_opengl2/example_glut_opengl2 +example_null/example_null example_sdl_opengl2/example_sdl_opengl2 example_sdl_opengl3/example_sdl_opengl3 -example_glut_opengl2/example_glut_opengl2 ## Dear ImGui Ini files imgui.ini diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile new file mode 100644 index 00000000..012758fe --- /dev/null +++ b/examples/example_null/Makefile @@ -0,0 +1,59 @@ +# +# Cross Platform Makefile +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# + +EXE = example_null +SOURCES = main.cpp +SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) + +CXXFLAGS = -I../ -I../../ +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) + ECHO_MESSAGE = "MinGW" + CFLAGS = $(CXXFLAGS) +endif + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../../%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../libs/gl3w/GL/%.c +# %.o:../libs/glad/src/%.c + $(CC) $(CFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index 90521f9b..81af0999 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -1,4 +1,5 @@ -// dear imgui: null/dummy example application (compile and link imgui with no inputs, no outputs) +// dear imgui: null/dummy example application (compile and link imgui with NO INPUTS, NO OUTPUTS) +// This is useful to test building, but you cannot interact with anything here! #include "imgui.h" #include @@ -13,7 +14,7 @@ int main(int, char**) int tex_w, tex_h; io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_w, &tex_h); - for (int n = 0; n < 50; n++) + for (int n = 0; n < 20; n++) { printf("NewFrame() %d\n", n); io.DisplaySize = ImVec2(1920, 1080); From f3110a57cd6f8870e8191f7938365fe03222e899 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 11 Apr 2019 14:51:01 +0200 Subject: [PATCH 245/566] Docking: Fixed an issue where newly created dock node override hosted window pos/size (#2109, #2386) --- imgui.cpp | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 63631846..03dc2e27 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11171,6 +11171,7 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc node->Pos = ImVec2(settings->Pos.x, settings->Pos.y); node->Size = ImVec2(settings->Size.x, settings->Size.y); node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y); + node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_DockNode; if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL) node->ParentNode->ChildNodes[0] = node; else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL) @@ -11792,7 +11793,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) node->LastFocusedNodeID = results.FirstNodeWithWindows->ID; // Copy the window class from of our first window so it can be used for proper dock filtering. - // When node has mixed windows, prioritize the class with the most constraint (CompatibleWithClassZero = false) as the reference to copy. + // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. if (ImGuiDockNode* first_node_with_windows = results.FirstNodeWithWindows) { @@ -11836,7 +11837,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) } DockNodeHideHostWindow(node); - node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto; + node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Window; node->WantCloseAll = false; node->WantCloseTabID = 0; node->HasCloseButton = node->HasCollapseButton = false; @@ -13516,18 +13517,13 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) if (node == NULL) { node = DockContextAddNode(ctx, window->DockId); + node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Window; if (auto_dock_node) node->LastFrameAlive = g.FrameCount; } DockNodeAddWindow(node, window, true); IM_ASSERT(node == window->DockNode); - - // Fix an edge case with auto-resizing windows: if they are created on the same frame they are creating their dock node, - // we don't want their initial zero-size to spread to the DockNode. We preserve their size. - SetNextWindowPos(window->Pos); - SetNextWindowSize(window->SizeFull); - g.NextWindowData.PosUndock = false; } #if 0 From 570d0bbbda957dfd3a473fb90a3fa6817f461c1b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 11 Apr 2019 15:12:18 +0200 Subject: [PATCH 246/566] Demo: Comments, tweaks, removed some uses of ImColor helpers. --- imgui_demo.cpp | 75 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 45 insertions(+), 30 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 423022c1..86e320ce 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -126,6 +126,7 @@ static void ShowExampleAppCustomRendering(bool* p_open); static void ShowExampleMenuFile(); // Helper to display a little (?) mark which shows a tooltip when hovered. +// In your own code you may want to display an actual icon if you are using a merged icon fonts (see misc/fonts/README.txt) static void HelpMarker(const char* desc) { ImGui::TextDisabled("(?)"); @@ -142,12 +143,13 @@ static void HelpMarker(const char* desc) // Helper to display basic user controls. void ImGui::ShowUserGuide() { + ImGuiIO& io = ImGui::GetIO(); ImGui::BulletText("Double-click on title bar to collapse window."); ImGui::BulletText("Click and drag on lower right corner to resize window\n(double-click to auto fit window to its contents)."); ImGui::BulletText("Click and drag on any empty space to move window."); ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text."); - if (ImGui::GetIO().FontAllowUserScaling) + if (io.FontAllowUserScaling) ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); ImGui::BulletText("Mouse Wheel to scroll."); ImGui::BulletText("While editing text:\n"); @@ -191,7 +193,7 @@ void ImGui::ShowDemoWindow(bool* p_open) static bool show_app_window_titles = false; static bool show_app_custom_rendering = false; - if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); // Process the Document app next, as it may also use a DockSpace() + if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); if (show_app_console) ShowExampleAppConsole(&show_app_console); if (show_app_log) ShowExampleAppLog(&show_app_log); @@ -254,7 +256,7 @@ void ImGui::ShowDemoWindow(bool* p_open) //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // Use 2/3 of the space for widgets and 1/3 for labels (default) ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // Use fixed width for labels (by passing a negative value), the rest goes to widgets. We choose a width proportional to our font size. - // Menu + // Menu Bar if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Menu")) @@ -341,7 +343,7 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Backend Flags")) { HelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities."); - ImGuiBackendFlags backend_flags = io.BackendFlags; // Make a local copy to avoid modifying the back-end flags. + ImGuiBackendFlags backend_flags = io.BackendFlags; // Make a local copy to avoid modifying actual back-end flags. ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasSetMousePos); @@ -576,7 +578,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Advanced, with Selectable nodes")) { - HelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); + HelpMarker("This is a more typical looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); static bool align_label_with_current_x_position = false; ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position); ImGui::Text("Hello!"); @@ -589,10 +591,12 @@ static void ShowDemoWindowWidgets() for (int i = 0; i < 6; i++) { // Disable the default open on single-click behavior and pass in Selected flag according to our selection state. - ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0); + ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; + if (selection_mask & (1 << i)) + node_flags |= ImGuiTreeNodeFlags_Selected; if (i < 3) { - // Node + // Items 0..2 are Tree Node bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); if (ImGui::IsItemClicked()) node_clicked = i; @@ -604,7 +608,9 @@ static void ShowDemoWindowWidgets() } else { - // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text(). + // Items 3..5 are Tree Leaves + // The only reason we use TreeNode at all is to allow selection of the leaf. + // Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text(). node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i); if (ImGui::IsItemClicked()) @@ -630,7 +636,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Collapsing Headers")) { static bool closable_group = true; - ImGui::Checkbox("Enable extra group", &closable_group); + ImGui::Checkbox("Show 2nd header", &closable_group); if (ImGui::CollapsingHeader("Header")) { ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered()); @@ -734,7 +740,7 @@ static void ShowDemoWindowWidgets() ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); ImVec2 pos = ImGui::GetCursorScreenPos(); - ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0,0), ImVec2(1,1), ImVec4(1.0f,1.0f,1.0f,1.0f), ImVec4(1.0f,1.0f,1.0f,0.5f)); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); @@ -746,7 +752,7 @@ static void ShowDemoWindowWidgets() ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); - ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), ImVec4(1.0f, 1.0f, 1.0f, 0.5f)); ImGui::EndTooltip(); } ImGui::TextWrapped("And now some textured buttons.."); @@ -755,7 +761,7 @@ static void ShowDemoWindowWidgets() { ImGui::PushID(i); int frame_padding = -1 + i; // -1 = uses default padding - if (ImGui::ImageButton(my_tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/my_tex_w,32/my_tex_h), frame_padding, ImColor(0,0,0,255))) + if (ImGui::ImageButton(my_tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/my_tex_w,32/my_tex_h), frame_padding, ImVec4(0.0f,0.0f,0.0f,1.0f))) pressed_count += 1; ImGui::PopID(); ImGui::SameLine(); @@ -986,7 +992,8 @@ static void ShowDemoWindowWidgets() return 0; } - // Tip: Because ImGui:: is a namespace you can add your own function into the namespace from your own source files. + // Tip: Because ImGui:: is a namespace you would typicall add your own function into the namespace in your own source files. + // For example, you may add a function called ImGui::InputText(const char* label, MyString* my_str). static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) { IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); @@ -2087,7 +2094,8 @@ static void ShowDemoWindowLayout() ImGui::PopID(); } } - float scroll_x = ImGui::GetScrollX(), scroll_max_x = ImGui::GetScrollMaxX(); + float scroll_x = ImGui::GetScrollX(); + float scroll_max_x = ImGui::GetScrollMaxX(); ImGui::EndChild(); ImGui::PopStyleVar(2); float scroll_x_delta = 0.0f; @@ -3061,7 +3069,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) } if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) { - ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128)); + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); + ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0, 0), ImVec2(1, 1), tint_col, border_col); ImGui::TreePop(); } @@ -3097,7 +3107,10 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) // [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() //----------------------------------------------------------------------------- -// Demonstrate creating a fullscreen menu bar and populating it. +// Demonstrate creating a "main" fullscreen menu bar and populating it. +// Note the difference between BeginMainMenuBar() and BeginMenuBar(): +// - BeginMenuBar() = menu-bar inside current window we Begin()-ed into (the window needs the ImGuiWindowFlags_MenuBar flag) +// - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it. static void ShowExampleAppMainMenuBar() { if (ImGui::BeginMainMenuBar()) @@ -3121,6 +3134,7 @@ static void ShowExampleAppMainMenuBar() } } +// Note that shortcuts are currently provided for display only (future version will add flags to BeginMenu to process shortcuts) static void ShowExampleMenuFile() { ImGui::MenuItem("(dummy menu)", NULL, false, false); @@ -3654,7 +3668,7 @@ static void ShowExampleAppLog(bool* p_open) static ExampleAppLog log; // For the demo: add a debug button _BEFORE_ the normal log window contents - // We take advantage of the fact that multiple calls to Begin()/End() are appending to the same window. + // We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window. // Most of the contents of the window will be added by the log.Draw() call. ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver); ImGui::Begin("Example: Log", p_open); @@ -3672,6 +3686,7 @@ static void ShowExampleAppLog(bool* p_open) } ImGui::End(); + // Actually call in the regular Log helper (which will Begin() into the same window as we just did) log.Draw("Example: Log", p_open); } @@ -3955,8 +3970,8 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); } - ImGui::SetNextWindowBgAlpha(0.3f); // Transparent background - if (ImGui::Begin("Example: Simple overlay", p_open, (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) + ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background + if (ImGui::Begin("Example: Simple overlay", p_open, (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) { ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)"); ImGui::Separator(); @@ -4047,27 +4062,27 @@ static void ShowExampleAppCustomRendering(bool* p_open) { // First line uses a thickness of 1.0, second line uses the configurable thickness float th = (n == 0) ? 1.0f : thickness; - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6, th); x += sz + spacing; // Hexagon - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 20, th); x += sz + spacing; // Circle - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 0.0f, ImDrawCornerFlags_All, th); x += sz + spacing; + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6, th); x += sz + spacing; // Hexagon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 20, th); x += sz + spacing; // Circle + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 0.0f, ImDrawCornerFlags_All, th); x += sz + spacing; draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_All, th); x += sz + spacing; draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight, th); x += sz + spacing; draw_list->AddTriangle(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32, th); x += sz + spacing; - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col32, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col32, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, th); x += sz + spacing; // Diagonal line + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col32, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col32, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, th); x += sz + spacing; // Diagonal line draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz*1.3f, y + sz*0.3f), ImVec2(x + sz - sz*1.3f, y + sz - sz*0.3f), ImVec2(x + sz, y + sz), col32, th); x = p.x + 4; y += sz + spacing; } - draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6); x += sz + spacing; // Hexagon - draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 32); x += sz + spacing; // Circle + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6); x += sz + spacing; // Hexagon + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 32); x += sz + spacing; // Circle draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32); x += sz + spacing; draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f); x += sz + spacing; draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight); x += sz + spacing; draw_list->AddTriangleFilled(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32); x += sz + spacing; - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col32); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col32); x += spacing + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col32); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col32); x += spacing + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col32); x += sz; // Pixel (faster than AddLine) 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)); ImGui::Dummy(ImVec2((sz + spacing) * 9.5f, (sz + spacing) * 3)); @@ -4135,7 +4150,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImVec2 window_size = ImGui::GetWindowSize(); ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); if (draw_bg) - ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 32, 10); + ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 32, 10+4); if (draw_fg) ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 32, 10); ImGui::EndTabItem(); From 07a70dc972dd34e9b8e973b51036b9210572722a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 11 Apr 2019 15:40:36 +0200 Subject: [PATCH 247/566] Internals: Merge minor things from range_select branch. Added ImGuiButtonFlags_NoHoveredOnNav. Added IsItemToggledSelected() - unused here. Renaming. --- imgui.cpp | 8 +++++++- imgui_internal.h | 11 +++++++---- imgui_widgets.cpp | 28 ++++++++++++++++++++-------- 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5ee019df..79fe1d48 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4352,6 +4352,12 @@ bool ImGui::IsItemClicked(int mouse_button) return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None); } +bool ImGui::IsItemToggledSelection() +{ + ImGuiContext& g = *GImGui; + return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false; +} + bool ImGui::IsAnyItemHovered() { ImGuiContext& g = *GImGui; @@ -7988,7 +7994,7 @@ static void ImGui::NavUpdateMoveResult() { // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId) g.NavJustMovedToId = result->ID; - g.NavJustMovedToSelectScopeId = result->SelectScopeId; + g.NavJustMovedToMultiSelectScopeId = result->SelectScopeId; } SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel); g.NavMoveFromClampedRefRect = false; diff --git a/imgui_internal.h b/imgui_internal.h index 4bf703d9..4093ce4c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -312,7 +312,8 @@ enum ImGuiButtonFlags_ ImGuiButtonFlags_NoKeyModifiers = 1 << 10, // disable interaction if a key modifier is held ImGuiButtonFlags_NoHoldingActiveID = 1 << 11, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) ImGuiButtonFlags_PressedOnDragDropHold = 1 << 12, // press when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) - ImGuiButtonFlags_NoNavFocus = 1 << 13 // don't override navigation focus when activated + ImGuiButtonFlags_NoNavFocus = 1 << 13, // don't override navigation focus when activated + ImGuiButtonFlags_NoHoveredOnNav = 1 << 14 // don't report as hovered when navigated on }; enum ImGuiSliderFlags_ @@ -374,7 +375,8 @@ enum ImGuiItemStatusFlags_ ImGuiItemStatusFlags_None = 0, ImGuiItemStatusFlags_HoveredRect = 1 << 0, ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, - ImGuiItemStatusFlags_Edited = 1 << 2 // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ImGuiItemStatusFlags_ToggledSelection = 1 << 3 // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues. #ifdef IMGUI_ENABLE_TEST_ENGINE , // [imgui-test only] @@ -861,7 +863,7 @@ struct ImGuiContext ImGuiID NavInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0 ImGuiID NavJustTabbedId; // Just tabbed to this id. ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). - ImGuiID NavJustMovedToSelectScopeId; // Just navigated to this select scope id (result of a successfully MoveRequest). + ImGuiID NavJustMovedToMultiSelectScopeId; // Just navigated to this select scope id (result of a successfully MoveRequest). ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard. ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring. @@ -1025,7 +1027,7 @@ struct ImGuiContext NavWindow = NULL; NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0; - NavJustTabbedId = NavJustMovedToId = NavJustMovedToSelectScopeId = NavNextActivateId = 0; + NavJustTabbedId = NavJustMovedToId = NavJustMovedToMultiSelectScopeId = NavNextActivateId = 0; NavInputSource = ImGuiInputSource_None; NavScoringRectScreen = ImRect(); NavScoringCount = 0; @@ -1441,6 +1443,7 @@ namespace ImGui IMGUI_API void PushMultiItemsWidths(int components, float width_full = 0.0f); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); + IMGUI_API bool IsItemToggledSelection(); // was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) // Logging/Capture IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ad3126cd..3faeb780 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -494,7 +494,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool // Gamepad/Keyboard navigation // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse. if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId)) - hovered = true; + if (!(flags & ImGuiButtonFlags_NoHoveredOnNav)) + hovered = true; if (g.NavActivateDownId == id) { @@ -5049,6 +5050,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; + const bool was_selected = selected; + bool hovered, held; bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); bool toggled = false; @@ -5085,6 +5088,10 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) SetItemAllowOverlap(); + // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger. + if (selected != was_selected) + window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; + // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y); @@ -5272,15 +5279,15 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) bb.Max.x += window_padding.x; - // Selectables are tightly packed together, we extend the box to cover spacing between selectable. - float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); - float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); - float spacing_R = style.ItemSpacing.x - spacing_L; - float spacing_D = style.ItemSpacing.y - spacing_U; + // Selectables are tightly packed together so we extend the box to cover spacing between selectable. + const float spacing_x = style.ItemSpacing.x; + const float spacing_y = style.ItemSpacing.y; + const float spacing_L = (float)(int)(spacing_x * 0.50f); + const float spacing_U = (float)(int)(spacing_y * 0.50f); bb.Min.x -= spacing_L; bb.Min.y -= spacing_U; - bb.Max.x += spacing_R; - bb.Max.y += spacing_D; + bb.Max.x += (spacing_x - spacing_L); + bb.Max.y += (spacing_y - spacing_U); bool item_add; if (flags & ImGuiSelectableFlags_Disabled) @@ -5313,6 +5320,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (flags & ImGuiSelectableFlags_Disabled) selected = false; + const bool was_selected = selected; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets) @@ -5328,6 +5336,10 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (flags & ImGuiSelectableFlags_AllowItemOverlap) SetItemAllowOverlap(); + // In this branch, Selectable() cannot toggle the selection so this will never trigger. + if (selected != was_selected) + window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; + // Render if (hovered || selected) { From ee02cdbf0377d07abf1692c2404afd91d962df9a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Apr 2019 17:43:50 +0200 Subject: [PATCH 248/566] Internals, Docs: Added a bunch of clarification about ButtonBehavior in the form of a table (and to facilitate writing tests) --- imgui_demo.cpp | 12 ++++++++-- imgui_internal.h | 2 +- imgui_widgets.cpp | 56 ++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 86e320ce..d8707f42 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -179,6 +179,8 @@ static void ShowDemoWindowMisc(); // You may execute this function to experiment with the UI and understand what it does. You may then search for keywords in the code when you are interested by a specific feature. void ImGui::ShowDemoWindow(bool* p_open) { + IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); // Exceptionally add an extra assert here for people confused with initial dear imgui setup + // Examples Apps (accessible from the "Examples" menu) static bool show_app_documents = false; static bool show_app_main_menu_bar = false; @@ -1531,7 +1533,9 @@ static void ShowDemoWindowWidgets() ImGui::RadioButton("SliderFloat", &item_type, 3); ImGui::RadioButton("InputText", &item_type, 4); ImGui::RadioButton("ColorEdit4", &item_type, 5); - ImGui::RadioButton("ListBox", &item_type, 6); + ImGui::RadioButton("MenuItem", &item_type, 6); + ImGui::RadioButton("TreeNode (w/ double-click)", &item_type, 7); + ImGui::RadioButton("ListBox", &item_type, 8); ImGui::Separator(); bool ret = false; if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction @@ -1540,7 +1544,9 @@ static void ShowDemoWindowWidgets() if (item_type == 3) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item if (item_type == 4) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) if (item_type == 5) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) - if (item_type == 6) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } + if (item_type == 6) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) + if (item_type == 7) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. + if (item_type == 8) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } ImGui::BulletText( "Return value = %d\n" "IsItemFocused() = %d\n" @@ -1555,6 +1561,7 @@ static void ShowDemoWindowWidgets() "IsItemDeactivated() = %d\n" "IsItemDeactivatedAfterEdit() = %d\n" "IsItemVisible() = %d\n" + "IsItemClicked() = %d\n" "GetItemRectMin() = (%.1f, %.1f)\n" "GetItemRectMax() = (%.1f, %.1f)\n" "GetItemRectSize() = (%.1f, %.1f)", @@ -1571,6 +1578,7 @@ static void ShowDemoWindowWidgets() ImGui::IsItemDeactivated(), ImGui::IsItemDeactivatedAfterEdit(), ImGui::IsItemVisible(), + ImGui::IsItemClicked(), ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y, ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y, ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y diff --git a/imgui_internal.h b/imgui_internal.h index 4093ce4c..426301d3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -300,7 +300,7 @@ enum ImGuiButtonFlags_ { ImGuiButtonFlags_None = 0, ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat - ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // return true on click + release on same item [DEFAULT if no PressedOn* flag is set] + ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // [Default] return true on click + release on same item ImGuiButtonFlags_PressedOnClick = 1 << 2, // return true on click (default requires click+release) ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return true on release (default requires click+release) ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return true on double-click (default requires click+release) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3faeb780..dcb91195 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -394,6 +394,56 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // - Bullet() //------------------------------------------------------------------------- +// The ButtonBehavior() function is key to many interactions and used by many/most widgets. +// Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_), +// this code is a little complex. +// By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior. +// See the series of events below and the corresponding state reported by dear imgui: +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+0 (mouse is outside bb) - - - - - - +// Frame N+1 (mouse moves inside bb) - true - - - - +// Frame N+2 (mouse button is down) - true true true - true +// Frame N+3 (mouse button is down) - true true - - - +// Frame N+4 (mouse moves outside bb) - - true - - - +// Frame N+5 (mouse moves inside bb) - true true - - - +// Frame N+6 (mouse button is released) true true - - true - +// Frame N+7 (mouse button is released) - true - - - - +// Frame N+8 (mouse moves outside bb) - - - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+2 (mouse button is down) true true true true - true +// Frame N+3 (mouse button is down) - true true - - - +// Frame N+6 (mouse button is released) - true - - true - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+2 (mouse button is down) - true - - - true +// Frame N+3 (mouse button is down) - true - - - - +// Frame N+6 (mouse button is released) true true - - - - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +// Frame N+0 (mouse button is down) - true - - - true +// Frame N+1 (mouse button is down) - true - - - - +// Frame N+2 (mouse button is released) - true - - - - +// Frame N+3 (mouse button is released) - true - - - - +// Frame N+4 (mouse button is down) true true true true - true +// Frame N+5 (mouse button is down) - true true - - - +// Frame N+6 (mouse button is released) - true - - true - +// Frame N+7 (mouse button is released) - true - - - - +//------------------------------------------------------------------------------------------------------------------------------------------------ +// The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set: +// Repeat+ Repeat+ Repeat+ Repeat+ +// PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick +//------------------------------------------------------------------------------------------------------------------------------------------------- +// Frame N+0 (mouse button is down) - true - true +// ... - - - - +// Frame N + RepeatDelay true true - true +// ... - - - - +// Frame N + RepeatDelay + RepeatRate*N true true - true +//------------------------------------------------------------------------------------------------------------------------------------------------- + bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; @@ -452,12 +502,6 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool { if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { - // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat - // PressedOnClickRelease | * | .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds - // PressedOnClick | | .. - // PressedOnRelease | | .. (NOT on release) - // PressedOnDoubleClick | | .. - // FIXME-NAV: We don't honor those different behaviors. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) { SetActiveID(id, window); From 30d81f53cbdb73f88ab049d21fc7a00cf548c8c8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Apr 2019 22:16:59 +0200 Subject: [PATCH 249/566] PlotLines, PlotHistogram: Ignore NaN values when calculating min/max bounds. (#2485) --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ec24a20b..f80d0329 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,7 @@ Other Changes: - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] +- PlotLines, PlotHistogram: Ignore NaN values when calculating min/max bounds. (#2485) - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dcb91195..4008fa21 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5577,6 +5577,8 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge for (int i = 0; i < values_count; i++) { const float v = values_getter(data, i); + if (v != v) // Ignore NaN values + continue; v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } From c6f1b7b92aa499d508a0ca825da7dbbe6ae7b105 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Apr 2019 19:44:29 +0200 Subject: [PATCH 250/566] Tests: Added hook/tweaks for imgui-test engine. + Fixed warnings. --- imgui.cpp | 7 ++++++- imgui_internal.h | 2 ++ imgui_widgets.cpp | 7 +++++-- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 704ffc1d..d4d80d0b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2899,7 +2899,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) #ifdef IMGUI_ENABLE_TEST_ENGINE if (id != 0) - ImGuiTestEngineHook_ItemAdd(&g, nav_bb_arg ? *nav_bb_arg : bb, id); + IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id); #endif // Clipping test @@ -6099,6 +6099,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; window->DC.LastItemRect = title_bar_rect; } + +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId); +#endif } else { diff --git a/imgui_internal.h b/imgui_internal.h index b077bc65..5e64623f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1808,8 +1808,10 @@ extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); +#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register status flags #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register status flags #else +#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) do { } while (0) #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) #endif diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d75b4184..136eb8e0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5123,7 +5123,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l SetItemAllowOverlap(); // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger. - if (selected != was_selected) + if (selected != was_selected) //-V547 window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render @@ -5371,7 +5371,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl SetItemAllowOverlap(); // In this branch, Selectable() cannot toggle the selection so this will never trigger. - if (selected != was_selected) + if (selected != was_selected) //-V547 window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render @@ -5395,6 +5395,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Automatically close popups if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup)) CloseCurrentPopup(); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags); return pressed; } @@ -5744,6 +5746,7 @@ ImGuiMenuColumns::ImGuiMenuColumns() void ImGuiMenuColumns::Update(int count, float spacing, bool clear) { IM_ASSERT(count == IM_ARRAYSIZE(Pos)); + IM_UNUSED(count); Width = NextWidth = 0.0f; Spacing = spacing; if (clear) From 092426bed26dffef59243b2f255ff65b38dc2ece Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Apr 2019 19:44:54 +0200 Subject: [PATCH 251/566] Docking: Hold Shift to force disable docking. (#2109) --- imgui.cpp | 4 ++-- imgui_internal.h | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d4d80d0b..0fd6d2ec 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6073,7 +6073,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginAsDockableDragDropSource() also overwrites it. - if ((g.ActiveId == window->MoveId) && ((g.IO.ConfigDockingWithShift && g.IO.KeyShift) || (!g.IO.ConfigDockingWithShift))) + if ((g.ActiveId == window->MoveId) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift)) if ((window->Flags & ImGuiWindowFlags_NoMove) == 0) if ((window->RootWindow->Flags & (ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking)) == 0) BeginAsDockableDragDropSource(window); @@ -10862,7 +10862,6 @@ namespace ImGui static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id); static ImGuiID DockContextGenNodeID(ImGuiContext* ctx); static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node); - static void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node); static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req); static void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true); @@ -13635,6 +13634,7 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; + //IM_ASSERT(window->RootWindow == window); // May also be a DockSpace IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); if (!g.DragDropActive) return; diff --git a/imgui_internal.h b/imgui_internal.h index 5e64623f..94858877 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1674,6 +1674,7 @@ namespace ImGui IMGUI_API void DockContextRebuild(ImGuiContext* ctx); IMGUI_API void DockContextNewFrameUpdateUndocking(ImGuiContext* ctx); IMGUI_API void DockContextNewFrameUpdateDocking(ImGuiContext* ctx); + IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } @@ -1809,10 +1810,10 @@ extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register status flags -#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register status flags +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register status flags #else #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) do { } while (0) -#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) #endif #ifdef __clang__ From fb2626c21b88d3ff1d053f9da0b3602207301ecc Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Apr 2019 19:44:29 +0200 Subject: [PATCH 252/566] Tests: Added hook/tweaks for imgui-test engine. + Fixed warnings. --- imgui.cpp | 6 +++++- imgui_internal.h | 2 ++ imgui_widgets.cpp | 7 +++++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 79fe1d48..3e882ab9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2837,7 +2837,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) #ifdef IMGUI_ENABLE_TEST_ENGINE if (id != 0) - ImGuiTestEngineHook_ItemAdd(&g, nav_bb_arg ? *nav_bb_arg : bb, id); + IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id); #endif // Clipping test @@ -5544,6 +5544,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.LastItemId = window->MoveId; window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; window->DC.LastItemRect = title_bar_rect; +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId); +#endif } PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); diff --git a/imgui_internal.h b/imgui_internal.h index 426301d3..7e7ffb44 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1584,8 +1584,10 @@ extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); +#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register status flags #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register status flags #else +#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) do { } while (0) #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) #endif diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4008fa21..82696d5a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5133,7 +5133,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l SetItemAllowOverlap(); // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger. - if (selected != was_selected) + if (selected != was_selected) //-V547 window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render @@ -5381,7 +5381,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl SetItemAllowOverlap(); // In this branch, Selectable() cannot toggle the selection so this will never trigger. - if (selected != was_selected) + if (selected != was_selected) //-V547 window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render @@ -5405,6 +5405,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Automatically close popups if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup)) CloseCurrentPopup(); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags); return pressed; } @@ -5756,6 +5758,7 @@ ImGuiMenuColumns::ImGuiMenuColumns() void ImGuiMenuColumns::Update(int count, float spacing, bool clear) { IM_ASSERT(count == IM_ARRAYSIZE(Pos)); + IM_UNUSED(count); Width = NextWidth = 0.0f; Spacing = spacing; if (clear) From 224f087a5f354393f2a4502869fe4b59a1469625 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Apr 2019 23:26:46 +0200 Subject: [PATCH 253/566] Docking: Rename typo Autority -> Authority + Rename DockContextNewFrameUpdateDocking -> DockContextUpdateDocking. --- imgui.cpp | 64 ++++++++++++++++++++++++------------------------ imgui_internal.h | 21 ++++++++-------- 2 files changed, 43 insertions(+), 42 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0fd6d2ec..3b543b90 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3734,7 +3734,7 @@ void ImGui::NewFrame() // Undocking // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) - DockContextNewFrameUpdateUndocking(&g); + DockContextUpdateUndocking(&g); // Find hovered window // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame) @@ -3810,7 +3810,7 @@ void ImGui::NewFrame() ClosePopupsOverWindow(g.NavWindow); // Docking - DockContextNewFrameUpdateDocking(&g); + DockContextUpdateDocking(&g); // Create implicit/fallback window - which we will only render it if the user has added something to it. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. @@ -10979,7 +10979,7 @@ void ImGui::DockContextRebuild(ImGuiContext* ctx) } // Docking context update function, called by NewFrame() -void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx) +void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; ImGuiDockContext* dc = ctx->DockContext; @@ -11023,7 +11023,7 @@ void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx) } // Docking context update function, called by NewFrame() -void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx) +void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; ImGuiDockContext* dc = ctx->DockContext; @@ -11181,7 +11181,7 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc node->Pos = ImVec2(settings->Pos.x, settings->Pos.y); node->Size = ImVec2(settings->Size.x, settings->Size.y); node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y); - node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_DockNode; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode; if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL) node->ParentNode->ChildNodes[0] = node; else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL) @@ -11423,9 +11423,9 @@ void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1; node->ParentNode->ChildNodes[index_in_parent] = NULL; DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]); - node->ParentNode->AutorityForViewport = ImGuiDataAutority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport + node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport node->ParentNode = NULL; - node->AutorityForPos = node->AutorityForSize = ImGuiDataAutority_Window; + node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_Window; node->WantMouseMove = true; } MarkIniSettingsDirty(); @@ -11449,8 +11449,8 @@ ImGuiDockNode::ImGuiDockNode(ImGuiID id) LastFocusedNodeID = 0; SelectedTabID = 0; WantCloseTabID = 0; - AutorityForPos = AutorityForSize = ImGuiDataAutority_DockNode; - AutorityForViewport = ImGuiDataAutority_Auto; + AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode; + AuthorityForViewport = ImGuiDataAuthority_Auto; IsVisible = true; IsFocused = HasCloseButton = HasCollapseButton = false; WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; @@ -11502,12 +11502,12 @@ static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, b // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. if (node->HostWindow == NULL && !node->IsDockSpace() && node->IsRootNode()) { - if (node->AutorityForPos == ImGuiDataAutority_Auto) - node->AutorityForPos = ImGuiDataAutority_Window; - if (node->AutorityForSize == ImGuiDataAutority_Auto) - node->AutorityForSize = ImGuiDataAutority_Window; - if (node->AutorityForViewport == ImGuiDataAutority_Auto) - node->AutorityForViewport = ImGuiDataAutority_Window; + if (node->AuthorityForPos == ImGuiDataAuthority_Auto) + node->AuthorityForPos = ImGuiDataAuthority_Window; + if (node->AuthorityForSize == ImGuiDataAuthority_Auto) + node->AuthorityForSize = ImGuiDataAuthority_Window; + if (node->AuthorityForViewport == ImGuiDataAuthority_Auto) + node->AuthorityForViewport = ImGuiDataAuthority_Window; } // Add to tab bar if requested @@ -11847,7 +11847,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) } DockNodeHideHostWindow(node); - node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Window; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; node->WantCloseAll = false; node->WantCloseTabID = 0; node->HasCloseButton = node->HasCollapseButton = false; @@ -11886,23 +11886,23 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL; // Sync Pos - if (node->AutorityForPos == ImGuiDataAutority_Window && ref_window) + if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window) SetNextWindowPos(ref_window->Pos); - else if (node->AutorityForPos == ImGuiDataAutority_DockNode) + else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode) SetNextWindowPos(node->Pos); // Sync Size - if (node->AutorityForSize == ImGuiDataAutority_Window && ref_window) + if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) SetNextWindowSize(ref_window->SizeFull); - else if (node->AutorityForSize == ImGuiDataAutority_DockNode) + else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode) SetNextWindowSize(node->Size); // Sync Collapsed - if (node->AutorityForSize == ImGuiDataAutority_Window && ref_window) + if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) SetNextWindowCollapsed(ref_window->Collapsed); // Sync Viewport - if (node->AutorityForViewport == ImGuiDataAutority_Window && ref_window) + if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window) SetNextWindowViewport(ref_window->ViewportId); SetNextWindowClass(&node->WindowClass); @@ -11935,12 +11935,12 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) if (node->HostWindow->Appearing) BringWindowToDisplayFront(node->HostWindow); - node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; } else if (node->ParentNode) { node->HostWindow = host_window = node->ParentNode->HostWindow; - node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; } if (node->WantMouseMove && node->HostWindow) DockNodeStartMouseMovingWindow(node, node->HostWindow); @@ -12700,7 +12700,7 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID); } DockNodeApplyPosSizeToWindows(parent_node); - parent_node->AutorityForPos = parent_node->AutorityForSize = parent_node->AutorityForViewport = ImGuiDataAutority_Auto; + parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto; parent_node->VisibleWindow = merge_lead_child->VisibleWindow; parent_node->SizeRef = backup_last_explicit_size; @@ -13141,7 +13141,7 @@ void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos) if (node == NULL) return; node->Pos = pos; - node->AutorityForPos = ImGuiDataAutority_DockNode; + node->AuthorityForPos = ImGuiDataAuthority_DockNode; } void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) @@ -13151,7 +13151,7 @@ void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) if (node == NULL) return; node->Size = node->SizeRef = size; - node->AutorityForSize = ImGuiDataAutority_DockNode; + node->AuthorityForSize = ImGuiDataAuthority_DockNode; } // If you create a regular node, both ref_pos/ref_size will position the window. @@ -13200,8 +13200,8 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) return; bool has_central_node = false; - ImGuiDataAutority backup_root_node_autority_for_pos = root_node ? root_node->AutorityForPos : ImGuiDataAutority_Auto; - ImGuiDataAutority backup_root_node_autority_for_size = root_node ? root_node->AutorityForSize : ImGuiDataAutority_Auto; + ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto; + ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto; // Process active windows ImVector nodes_to_remove; @@ -13225,8 +13225,8 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) if (root_node) { - root_node->AutorityForPos = backup_root_node_autority_for_pos; - root_node->AutorityForSize = backup_root_node_autority_for_size; + root_node->AuthorityForPos = backup_root_node_authority_for_pos; + root_node->AuthorityForSize = backup_root_node_authority_for_size; } // Apply to settings @@ -13527,7 +13527,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) if (node == NULL) { node = DockContextAddNode(ctx, window->DockId); - node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Window; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; if (auto_dock_node) node->LastFrameAlive = g.FrameCount; } diff --git a/imgui_internal.h b/imgui_internal.h index 94858877..635d2081 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -84,8 +84,8 @@ struct ImGuiWindowTempData; // Temporary storage for one window (that's struct ImGuiWindowSettings; // Storage for window settings stored in .ini file (we keep one of those even if the actual window wasn't instanced during this session) // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. +typedef int ImGuiDataAuthority; // -> enum ImGuiDataAuthority_ // Enum: for storing the source authority (dock node vs window) of a field typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical -typedef int ImGuiDataAutority; // -> enum ImGuiDataAutority_ // Enum: for storing the source autority (dock node vs window) of a field typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() @@ -865,11 +865,12 @@ enum ImGuiDockNodeFlagsPrivate_ ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace // When splitting those flags are moved to the inheriting child, never duplicated }; -enum ImGuiDataAutority_ +// Store the source authority (dock node vs window) of a field +enum ImGuiDataAuthority_ { - ImGuiDataAutority_Auto, - ImGuiDataAutority_DockNode, - ImGuiDataAutority_Window + ImGuiDataAuthority_Auto, + ImGuiDataAuthority_DockNode, + ImGuiDataAuthority_Window }; // sizeof() 116~160 @@ -898,9 +899,9 @@ struct ImGuiDockNode ImGuiID LastFocusedNodeID; // [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. ImGuiID SelectedTabID; // [Tab node only] Which of our tab is selected. ImGuiID WantCloseTabID; // [Tab node only] Set when closing a specific tab. - ImGuiDataAutority AutorityForPos :3; - ImGuiDataAutority AutorityForSize :3; - ImGuiDataAutority AutorityForViewport :3; + ImGuiDataAuthority AuthorityForPos :3; + ImGuiDataAuthority AuthorityForSize :3; + ImGuiDataAuthority AuthorityForViewport :3; bool IsVisible :1; // Set to false when the node is hidden (usually disabled as it has no active window) bool IsFocused :1; bool HasCloseButton :1; @@ -1672,8 +1673,8 @@ namespace ImGui IMGUI_API void DockContextShutdown(ImGuiContext* ctx); IMGUI_API void DockContextOnLoadSettings(ImGuiContext* ctx); IMGUI_API void DockContextRebuild(ImGuiContext* ctx); - IMGUI_API void DockContextNewFrameUpdateUndocking(ImGuiContext* ctx); - IMGUI_API void DockContextNewFrameUpdateDocking(ImGuiContext* ctx); + IMGUI_API void DockContextUpdateUndocking(ImGuiContext* ctx); + IMGUI_API void DockContextUpdateDocking(ImGuiContext* ctx); IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); From 800fb26606fc6abd7b1a92ad10b1b6876f757a59 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Apr 2019 00:26:40 +0200 Subject: [PATCH 254/566] Docking: Renamed target_node > node in some functions to facilitate debugger watch use across functions. --- imgui.cpp | 91 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 46 insertions(+), 45 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3b543b90..15bba324 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11272,7 +11272,7 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) ImGuiContext& g = *ctx; ImGuiWindow* payload_window = req->DockPayload; // Optional ImGuiWindow* target_window = req->DockTargetWindow; - ImGuiDockNode* target_node = req->DockTargetNode; + ImGuiDockNode* node = req->DockTargetNode; // Decide which Tab will be selected at the end of the operation ImGuiID next_selected_id = 0; @@ -11289,21 +11289,21 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. - if (target_node) - IM_ASSERT(target_node->LastFrameAlive <= g.FrameCount); - if (target_node && target_window && target_node == target_window->DockNodeAsHost) - IM_ASSERT(target_node->Windows.Size > 0 || target_node->IsSplitNode() || target_node->IsCentralNode()); + if (node) + IM_ASSERT(node->LastFrameAlive <= g.FrameCount); + if (node && target_window && node == target_window->DockNodeAsHost) + IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode()); // Create new node and add existing window to it - if (target_node == NULL) + if (node == NULL) { - target_node = DockContextAddNode(ctx, 0); - target_node->Pos = target_window->Pos; - target_node->Size = target_window->Size; + node = DockContextAddNode(ctx, 0); + node->Pos = target_window->Pos; + node->Size = target_window->Size; if (target_window->DockNodeAsHost == NULL) { - DockNodeAddWindow(target_node, target_window, true); - target_node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted; + DockNodeAddWindow(node, target_window, true); + node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted; target_window->DockIsActive = true; } } @@ -11315,21 +11315,21 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side const float split_ratio = req->DockSplitRatio; - DockNodeTreeSplit(ctx, target_node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here! - ImGuiDockNode* new_node = target_node->ChildNodes[split_inheritor_child_idx ^ 1]; - new_node->HostWindow = target_node->HostWindow; - target_node = new_node; + DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here! + ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1]; + new_node->HostWindow = node->HostWindow; + node = new_node; } - target_node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar; + node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar; - if (target_node != payload_node) + if (node != payload_node) { // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) - if (target_node->Windows.Size > 0 && target_node->TabBar == NULL) + if (node->Windows.Size > 0 && node->TabBar == NULL) { - DockNodeAddTabBar(target_node); - for (int n = 0; n < target_node->Windows.Size; n++) - TabBarAddTab(target_node->TabBar, ImGuiTabItemFlags_None, target_node->Windows[n]); + DockNodeAddTabBar(node); + for (int n = 0; n < node->Windows.Size; n++) + TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); } if (payload_node != NULL) @@ -11337,7 +11337,7 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) // Transfer full payload node (with 1+ child windows or child nodes) if (payload_node->IsSplitNode()) { - if (target_node->Windows.Size > 0) + if (node->Windows.Size > 0) { // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. // In this situation, we move the windows of the target node into the currently visible node of the payload. @@ -11346,28 +11346,28 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows; if (visible_node->TabBar) IM_ASSERT(visible_node->TabBar->Tabs.Size > 0); - DockNodeMoveWindows(target_node, visible_node); - DockNodeMoveWindows(visible_node, target_node); - DockSettingsRenameNodeReferences(target_node->ID, visible_node->ID); + DockNodeMoveWindows(node, visible_node); + DockNodeMoveWindows(visible_node, node); + DockSettingsRenameNodeReferences(node->ID, visible_node->ID); } - if (target_node->IsCentralNode()) + if (node->IsCentralNode()) { // Central node property needs to be moved to a leaf node, pick the last focused one. // FIXME-DOCKING: If we had to transfer other flags here, what would the policy be? ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeID); IM_ASSERT(last_focused_node != NULL && DockNodeGetRootNode(last_focused_node) == DockNodeGetRootNode(payload_node)); last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; - target_node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode; + node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode; } - IM_ASSERT(target_node->Windows.Size == 0); - DockNodeMoveChildNodes(target_node, payload_node); + IM_ASSERT(node->Windows.Size == 0); + DockNodeMoveChildNodes(node, payload_node); } else { const ImGuiID payload_dock_id = payload_node->ID; - DockNodeMoveWindows(target_node, payload_node); - DockSettingsRenameNodeReferences(payload_dock_id, target_node->ID); + DockNodeMoveWindows(node, payload_node); + DockSettingsRenameNodeReferences(payload_dock_id, node->ID); } DockContextRemoveNode(ctx, payload_node, true); } @@ -11375,15 +11375,15 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) { // Transfer single window const ImGuiID payload_dock_id = payload_window->DockId; - target_node->VisibleWindow = payload_window; - DockNodeAddWindow(target_node, payload_window, true); + node->VisibleWindow = payload_window; + DockNodeAddWindow(node, payload_window, true); if (payload_dock_id != 0) - DockSettingsRenameNodeReferences(payload_dock_id, target_node->ID); + DockSettingsRenameNodeReferences(payload_dock_id, node->ID); } } // Update selection immediately - if (ImGuiTabBar* tab_bar = target_node->TabBar) + if (ImGuiTabBar* tab_bar = node->TabBar) tab_bar->NextSelectedTabId = next_selected_id; MarkIniSettingsDirty(); } @@ -13653,36 +13653,37 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data; if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { + // Select target node + ImGuiDockNode* node = NULL; bool allow_null_target_node = false; - ImGuiDockNode* target_node = NULL; if (window->DockNodeAsHost) - target_node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos); else if (window->DockNode) // && window->DockIsActive) - target_node = window->DockNode; + node = window->DockNode; else allow_null_target_node = true; // Dock into a regular window - const ImRect explicit_target_rect = (target_node && target_node->TabBar && !target_node->IsHiddenTabBar() && !target_node->IsNoTabBar()) ? target_node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); + const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); // Preview docking request and find out split direction/ratio //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. const bool do_preview = payload->IsPreview() || payload->IsDelivery(); - if (do_preview && (target_node != NULL || allow_null_target_node)) + if (do_preview && (node != NULL || allow_null_target_node)) { ImGuiDockPreviewData split_inner, split_outer; ImGuiDockPreviewData* split_data = &split_inner; - if (target_node && (target_node->ParentNode || target_node->IsCentralNode())) - if (ImGuiDockNode* root_node = DockNodeGetRootNode(target_node)) + if (node && (node->ParentNode || node->IsCentralNode())) + if (ImGuiDockNode* root_node = DockNodeGetRootNode(node)) if (DockNodePreviewDockCalc(window, root_node, payload_window, &split_outer, is_explicit_target, true)) split_data = &split_outer; - DockNodePreviewDockCalc(window, target_node, payload_window, &split_inner, is_explicit_target, false); + DockNodePreviewDockCalc(window, node, payload_window, &split_inner, is_explicit_target, false); if (split_data == &split_outer) split_inner.IsDropAllowed = false; // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes - DockNodePreviewDockRender(window, target_node, payload_window, &split_inner); - DockNodePreviewDockRender(window, target_node, payload_window, &split_outer); + DockNodePreviewDockRender(window, node, payload_window, &split_inner); + DockNodePreviewDockRender(window, node, payload_window, &split_outer); // Queue docking request if (split_data->IsDropAllowed && payload->IsDelivery()) From e805ca29d859dc817e29797d0be83adeb2af1bb8 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Apr 2019 18:51:18 +0200 Subject: [PATCH 255/566] Internals: Moved resize grips and borders to nav layer 1 so that testing system doesn't attempt to scroll to get them inside the InnerRect. --- imgui.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 3e882ab9..d46de350 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4815,6 +4815,10 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au ImVec2 pos_target(FLT_MAX, FLT_MAX); ImVec2 size_target(FLT_MAX, FLT_MAX); + // Resize grips and borders are on layer 1 + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); + // Manual resize grips PushID("#RESIZE"); for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) @@ -4905,6 +4909,10 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au MarkIniSettingsDirty(window); } + // Resize nav layer + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); + window->Size = window->SizeFull; } From 433a7556c7ea3440dd8eba7c0837829b6f493ec3 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Apr 2019 19:19:56 +0200 Subject: [PATCH 256/566] Docking: Fixed another issue where the resulting node of a split would sometimes recall the pos/size of previous host window. Spent a whole day adding framework for testing more of docking so hopefully we'll heading toward the magical world of less regressions. (#2109) --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 2fa44628..cc715503 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11838,6 +11838,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) ImGuiWindow* single_window = node->Windows[0]; node->Pos = single_window->Pos; node->Size = single_window->SizeFull; + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; // Transfer focus immediately so when we revert to a regular window it is immediately selected if (node->HostWindow && g.NavWindow == node->HostWindow) @@ -11855,7 +11856,6 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) } DockNodeHideHostWindow(node); - node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; node->WantCloseAll = false; node->WantCloseTabID = 0; node->HasCloseButton = node->HasCollapseButton = false; @@ -12664,6 +12664,7 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow; parent_node->SplitAxis = split_axis; parent_node->VisibleWindow = NULL; + parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode; float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE); size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f); From f70eacee8e4b95571e636cc72874453e2a7d49b3 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Apr 2019 19:50:30 +0200 Subject: [PATCH 257/566] Docking: Internal: Added helper for automation to process docking at the mouse level. --- imgui.cpp | 45 ++++++++++++++++++++++++++++++++++----------- imgui_internal.h | 1 + 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cc715503..67812dd6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10896,11 +10896,11 @@ namespace ImGui static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node); static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window); static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window); - static bool DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking); + static void DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking); static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data); static ImRect DockNodeCalcTabBarRect(const ImGuiDockNode* node); static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired); - static bool DockNodeCalcDropRects(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking); + static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos); static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; } static int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } static int DockNodeGetTabOrder(ImGuiWindow* window); @@ -11439,6 +11439,25 @@ void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) MarkIniSettingsDirty(); } +// This is mostly used for automation. +bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos) +{ + if (split_outer) + { + IM_ASSERT(0); + } + else + { + ImGuiDockPreviewData split_data; + DockNodePreviewDockCalc(target, target_node, payload, &split_data, false, split_outer); + if (split_data.DropRectsDraw[split_dir+1].IsInverted()) + return false; + *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter(); + return true; + } + return false; +} + //----------------------------------------------------------------------------- // Docking: ImGuiDockNode //----------------------------------------------------------------------------- @@ -12408,7 +12427,7 @@ void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& po } // Retrieve the drop rectangles for a given direction or for the center + perform hit testing. -bool ImGui::DockNodeCalcDropRects(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking) +bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos) { ImGuiContext& g = *GImGui; @@ -12440,12 +12459,15 @@ bool ImGui::DockNodeCalcDropRects(const ImRect& parent, ImGuiDir dir, ImRect& ou else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); } else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); } + if (test_mouse_pos == NULL) + return false; + ImRect hit_r = out_r; if (!outer_docking) { // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides hit_r.Expand(ImFloor(hs_w * 0.30f)); - ImVec2 mouse_delta = (g.IO.MousePos - c); + ImVec2 mouse_delta = (*test_mouse_pos - c); float mouse_delta_len2 = ImLengthSqr(mouse_delta); float r_threshold_center = hs_w * 1.4f; float r_threshold_sides = hs_w * (1.4f + 1.2f); @@ -12454,14 +12476,13 @@ bool ImGui::DockNodeCalcDropRects(const ImRect& parent, ImGuiDir dir, ImRect& ou if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides) return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y)); } - return hit_r.Contains(g.IO.MousePos); + return hit_r.Contains(*test_mouse_pos); } // host_node may be NULL if the window doesn't have a DockNode already. -static bool ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking) +static void ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking) { ImGuiContext& g = *GImGui; - IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes // There is an edge case when docking into a dockspace which only has inactive nodes. // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. @@ -12503,7 +12524,7 @@ static bool ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNo continue; if (dir != ImGuiDir_None && !data->IsSidesAvailable) continue; - if (DockNodeCalcDropRects(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking)) + if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos)) { data->SplitDir = (ImGuiDir)dir; data->IsSplitDirExplicit = true; @@ -12531,13 +12552,12 @@ static bool ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNo data->FutureNode.Size = size_new; data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio); } - - return data->IsSplitDirExplicit; } static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data) { ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. @@ -13684,8 +13704,11 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) ImGuiDockPreviewData* split_data = &split_inner; if (node && (node->ParentNode || node->IsCentralNode())) if (ImGuiDockNode* root_node = DockNodeGetRootNode(node)) - if (DockNodePreviewDockCalc(window, root_node, payload_window, &split_outer, is_explicit_target, true)) + { + DockNodePreviewDockCalc(window, root_node, payload_window, &split_outer, is_explicit_target, true); + if (split_outer.IsSplitDirExplicit) split_data = &split_outer; + } DockNodePreviewDockCalc(window, node, payload_window, &split_inner, is_explicit_target, false); if (split_data == &split_outer) split_inner.IsDropAllowed = false; diff --git a/imgui_internal.h b/imgui_internal.h index 86736088..d4692d4e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1678,6 +1678,7 @@ namespace ImGui IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); + IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos); inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } IMGUI_API void BeginDocked(ImGuiWindow* window, bool* p_open); IMGUI_API void BeginAsDockableDragDropSource(ImGuiWindow* window); From a936d0669cb3378559f973899f6c59a2f4bec4c0 Mon Sep 17 00:00:00 2001 From: "Nicolas \"Pixel\" Noble" Date: Sat, 13 Apr 2019 17:25:06 +0200 Subject: [PATCH 258/566] Adding standalone Emscripten example. --- examples/example_emscripten/Makefile | 58 ++++++ examples/example_emscripten/README.md | 8 + examples/example_emscripten/main.cpp | 165 ++++++++++++++++++ .../example_emscripten/shell_minimal.html | 153 ++++++++++++++++ 4 files changed, 384 insertions(+) create mode 100644 examples/example_emscripten/Makefile create mode 100644 examples/example_emscripten/README.md create mode 100644 examples/example_emscripten/main.cpp create mode 100644 examples/example_emscripten/shell_minimal.html diff --git a/examples/example_emscripten/Makefile b/examples/example_emscripten/Makefile new file mode 100644 index 00000000..b97933d6 --- /dev/null +++ b/examples/example_emscripten/Makefile @@ -0,0 +1,58 @@ +# +# Makefile to use with emscripten +# See https://emscripten.org/docs/getting_started/downloads.html +# for installation instructions. This Makefile assumes you have +# loaded emscripten's environment. +# +# Running `make` will produce three files: +# - example_emscripten.html +# - example_emscripten.js +# - example_emscripten.wasm +# +# All three are needed to run the demo. + +CC = emcc +CXX = em++ + +EXE = example_emscripten.html +SOURCES = main.cpp +SOURCES += ../imgui_impl_sdl.cpp ../imgui_impl_opengl3.cpp +SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) + +EMS = -s USE_SDL=2 -s USE_WEBGL2=1 -s WASM=1 -s FULL_ES3=1 +EMS += -s ALLOW_MEMORY_GROWTH=1 -s BINARYEN_TRAP_MODE=clamp +EMS += -s DISABLE_EXCEPTION_CATCHING=1 -s EXIT_RUNTIME=1 +EMS += -s ASSERTIONS=1 -s SAFE_HEAP=1 + +CPPFLAGS = -I../ -I../../ +CPPFLAGS += -g -Wall -Wformat -O3 +CPPFLAGS += $(EMS) +LIBS = $(EMS) +LDFLAGS = --shell-file shell_minimal.html + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:../%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:../../%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:../libs/gl3w/GL/%.c + $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(EXE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(LIBS) $(LDFLAGS) + +clean: + rm -f $(EXE) $(OBJS) *.js *.wasm diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten/README.md new file mode 100644 index 00000000..c607ed73 --- /dev/null +++ b/examples/example_emscripten/README.md @@ -0,0 +1,8 @@ + +# How to Build + +- You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions + +``` +em++ -I.. -I../.. main.cpp ../imgui_impl_sdl.cpp ../imgui_impl_opengl3.cpp ../../imgui*.cpp -s USE_SDL=2 -s USE_WEBGL2=1 -s WASM=1 -s FULL_ES3=1 -s ALLOW_MEMORY_GROWTH=1 -s BINARYEN_TRAP_MODE=clamp --shell-file shell_minimal.html -o example-emscripten.html +``` diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp new file mode 100644 index 00000000..dd31e7b7 --- /dev/null +++ b/examples/example_emscripten/main.cpp @@ -0,0 +1,165 @@ +// dear imgui: standalone example application for Emscripten, using SDL2 + OpenGL3 +// This is mostly the same code as the SDL2 + OpenGL3 example, simply with the modifications needed to run on Emscripten. +// It is possible to combine both code into a single source file that will compile properly on Desktop and using Emscripten. +// See https://github.com/ocornut/imgui/pull/2492 as an example on how to do just that. +// +// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// (Emscripten is a C++-to-javascript compiler, used to publish executables for the web. See https://emscripten.org/) + +#include "imgui.h" +#include "imgui_impl_sdl.h" +#include "imgui_impl_opengl3.h" +#include +#include +#include +#include + +// Emscripten requires to have full control over the main loop. We're going to store variables from main() to main_loop() here. +// This will also hold some of our persistent data across loops. Remember: imgui is immediate mode, and doesn't store state. +// Having a single function that acts as a loop prevents us to store state in the stack of said function. So we need some location for this. +struct MainLoopVars { + SDL_Window* window = NULL; + SDL_GLContext gl_context = NULL; + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); +}; + +// For clarity, our main loop code is declared at the end. +void main_loop(void*); + +int main(int, char**) +{ + MainLoopVars vars; + + // Setup SDL + if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) + { + printf("Error: %s\n", SDL_GetError()); + return -1; + } + + // For the browser using emscripten, we are going to use WebGL2 with GLES3. See the Makefile.emscripten for requirement details. + // It is very likely the generated file won't work in many browsers. Firefox is the only sure bet, but I have successfully + // run this code on Chrome for Android for example. + const char* glsl_version = "#version 300 es"; + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); + + // Create window with graphics context + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); + SDL_DisplayMode current; + SDL_GetCurrentDisplayMode(0, ¤t); + SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + vars.window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + vars.gl_context = SDL_GL_CreateContext(vars.window); + if (!vars.gl_context) { + fprintf(stderr, "Failed to initialize WebGL context!\n"); + return 1; + } + SDL_GL_SetSwapInterval(1); // Enable vsync + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + + // Setup Platform/Renderer bindings + ImGui_ImplSDL2_InitForOpenGL(vars.window, vars.gl_context); + ImGui_ImplOpenGL3_Init(glsl_version); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Read 'misc/fonts/README.txt' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != NULL); + + // This function call won't return, and will engage in an infinite loop, processing events from the browser, and dispatching them. + emscripten_set_main_loop_arg(main_loop, &vars, 0, true); +} + +void main_loop(void* arg) { + MainLoopVars* vars = (MainLoopVars*) arg; + ImGuiIO& io = ImGui::GetIO(); + + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL2_ProcessEvent(&event); + // Capture events here, based on io.WantCaptureMouse and io.WantCaptureKeyboard + } + + // Start the Dear ImGui frame + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplSDL2_NewFrame(vars->window); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (vars->show_demo_window) + ImGui::ShowDemoWindow(&vars->show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &vars->show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &vars->show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&vars->clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (vars->show_another_window) + { + ImGui::Begin("Another Window", &vars->show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + vars->show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + SDL_GL_MakeCurrent(vars->window, vars->gl_context); + glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); + glClearColor(vars->clear_color.x, vars->clear_color.y, vars->clear_color.z, vars->clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + SDL_GL_SwapWindow(vars->window); +} diff --git a/examples/example_emscripten/shell_minimal.html b/examples/example_emscripten/shell_minimal.html new file mode 100644 index 00000000..3c5ef8ca --- /dev/null +++ b/examples/example_emscripten/shell_minimal.html @@ -0,0 +1,153 @@ + + + + + + Emscripten-Generated Code + + + +
+
emscripten
+
Downloading...
+
+ +
+
+ +
+
+
+ Resize canvas + Lock/hide mouse pointer +     + +
+ +
+ +
+ + {{{ SCRIPT }}} + + From 882d480b5e479898c26971ebdaecece5ae543649 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 15 Apr 2019 01:01:39 +0200 Subject: [PATCH 259/566] Examples: Removed unused variable (will be used in docking branch tho, undo when merging!) --- examples/imgui_impl_sdl.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 528dbba3..10f49493 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -51,9 +51,6 @@ #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE SDL_VERSION_ATLEAST(2,0,4) #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) -#if !SDL_HAS_VULKAN -static const Uint32 SDL_WINDOW_VULKAN = 0x10000000; -#endif // Data static SDL_Window* g_Window = NULL; From c1848b185cd9dff997bb0e52981f78b8492f7a17 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 15 Apr 2019 01:01:44 +0200 Subject: [PATCH 260/566] Examples: Emscripten: Switched to WebGL1/ES2, Added Changelog, Updated links, Added ignore list, Fixed warning with older versions. Removed reliance on C++11 (would warn on some compiler). Improved html template, removed undesirable options, reduced log size. Tweaked main.cpp. (#2494) --- docs/CHANGELOG.txt | 1 + docs/README.md | 7 +- docs/TODO.txt | 3 +- examples/.gitignore | 1 + examples/README.txt | 12 +++- examples/example_emscripten/Makefile | 6 +- examples/example_emscripten/main.cpp | 66 +++++++++---------- .../example_emscripten/shell_minimal.html | 30 ++++----- 8 files changed, 67 insertions(+), 59 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f80d0329..889ca66c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Other Changes: to using the ImGui::MemAlloc()/MemFree() calls directly. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) +- Examples: Emscripten: Added Emscripten+SDL+GLES2 example. (#2494, #2492, #2351, #336) [@nicolasnoble] - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Fixed in-flight buffers issues when using multi-viewports. (#2461, #2348, #2378, #2097) - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). diff --git a/docs/README.md b/docs/README.md index ba48517e..1b00d2fb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -135,8 +135,7 @@ Languages: (third-party bindings) Frameworks: - Renderers: DirectX 9/10/11/12, Metal, OpenGL2, OpenGL3+/ES2/ES3, Vulkan: [examples/](https://github.com/ocornut/imgui/tree/master/examples) - Platform: GLFW, SDL, Win32, OSX, GLUT: [examples/](https://github.com/ocornut/imgui/tree/master/examples) -- Framework: Allegro 5, Marmalade: [examples/](https://github.com/ocornut/imgui/tree/master/examples) -- Unmerged PR: SDL2 + OpenGLES + Emscripten: [#336](https://github.com/ocornut/imgui/pull/336) +- Framework: Allegro 5, Emscripten, Marmalade: [examples/](https://github.com/ocornut/imgui/tree/master/examples) - Unmerged PR: Android: [#421](https://github.com/ocornut/imgui/pull/421) - Cinder: [Cinder-ImGui](https://github.com/simongeilfus/Cinder-ImGui) - Cocos2d-x: [imguix](https://github.com/c0i/imguix), [#551](https://github.com/ocornut/imgui/issues/551) @@ -221,8 +220,8 @@ Frequently Asked Question (FAQ) This library is poorly documented at the moment and expects of the user to be acquainted with C/C++. - Run the examples/ applications and explore them. - - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. - - The demo covers most features of Dear ImGui, so you can read the code and see its output. + - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. + - The demo covers most features of Dear ImGui, so you can read the code and see its output. - See documentation and comments at the top of imgui.cpp + effectively imgui.h. - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder to explain how to integrate Dear ImGui with your own engine/application. - Your programming IDE is your friend, find the type or function declaration to find comments associated to it. diff --git a/docs/TODO.txt b/docs/TODO.txt index 66fd9459..a837b8b5 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -316,8 +316,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - misc: possible compile-time support for wchar_t instead of char*? - backend: bgfx? https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - - web/emscriptem: refactor some examples to facilitate integration with emscripten main loop system. (#1713, #336) - - web/emscriptem: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) + - emscriptem: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) - remote: make a system like RemoteImGui first-class citizen/project (#75) diff --git a/examples/.gitignore b/examples/.gitignore index ddfa5ead..54c0a118 100644 --- a/examples/.gitignore +++ b/examples/.gitignore @@ -27,6 +27,7 @@ xcuserdata ## Emscripten output *.out.js *.out.wasm +example_emscripten/example_emscripten.* ## Unix executables example_glfw_opengl2/example_glfw_opengl2 diff --git a/examples/README.txt b/examples/README.txt index 03974745..cd60733c 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -122,13 +122,15 @@ List of high-level Frameworks Bindings in this repository: (combine Platform + R imgui_impl_allegro5.cpp imgui_impl_marmalade.cpp +Note that Dear ImGui works with Emscripten. +The examples_emscripten/ app uses sdl.cpp + opengl3.cpp but other combinations are possible. Third-party framework, graphics API and languages bindings are listed at: https://github.com/ocornut/imgui/wiki/Bindings Languages: C, C#, ChaiScript, D, Go, Haxe, Java, Lua, Odin, Pascal, PureBasic, Python, Rust, Swift... - Frameworks: Cinder, Cocoa (OSX), Cocos2d-x, Emscripten, SFML, GML/GameMaker Studio, Irrlicht, Ogre, - OpenSceneGraph, openFrameworks, LOVE, NanoRT, Nim Game Lib, Qt3d, SFML, Unreal Engine 4... + Frameworks: Cinder, Cocoa (OSX), Cocos2d-x, SFML, GML/GameMaker Studio, Irrlicht, Ogre, OpenSceneGraph, + openFrameworks, LOVE, NanoRT, Nim Game Lib, Qt3d, SFML, Unreal Engine 4... Miscellaneous: Software Renderer, RemoteImgui, etc. @@ -177,6 +179,12 @@ example_apple_opengl2/ = main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp (NB: you may still want to use GLFW or SDL which will also support Windows, Linux along with OSX.) +example_empscripten: + Emcripten + SDL2 + OpenGL3+/ES2/ES3 example. + = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp + Note that other examples based on SDL or GLFW + GL could easily be modified to work with Emscripten. + We provide this to make the Emscripten differences obvious, and have them not pollute all other examples. + example_glfw_opengl2/ GLFW + OpenGL2 example (legacy, fixed pipeline). = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp diff --git a/examples/example_emscripten/Makefile b/examples/example_emscripten/Makefile index b97933d6..6c9865ff 100644 --- a/examples/example_emscripten/Makefile +++ b/examples/example_emscripten/Makefile @@ -21,9 +21,9 @@ SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -EMS = -s USE_SDL=2 -s USE_WEBGL2=1 -s WASM=1 -s FULL_ES3=1 +EMS = -s USE_SDL=2 -s WASM=1 EMS += -s ALLOW_MEMORY_GROWTH=1 -s BINARYEN_TRAP_MODE=clamp -EMS += -s DISABLE_EXCEPTION_CATCHING=1 -s EXIT_RUNTIME=1 +EMS += -s DISABLE_EXCEPTION_CATCHING=1 -s NO_EXIT_RUNTIME=0 EMS += -s ASSERTIONS=1 -s SAFE_HEAP=1 CPPFLAGS = -I../ -I../../ @@ -55,4 +55,4 @@ $(EXE): $(OBJS) $(CXX) -o $@ $^ $(LIBS) $(LDFLAGS) clean: - rm -f $(EXE) $(OBJS) *.js *.wasm + rm -f $(EXE) $(OBJS) *.js *.wasm *.wasm.pre diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index dd31e7b7..847b505a 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -14,24 +14,16 @@ #include #include -// Emscripten requires to have full control over the main loop. We're going to store variables from main() to main_loop() here. -// This will also hold some of our persistent data across loops. Remember: imgui is immediate mode, and doesn't store state. +// Emscripten requires to have full control over the main loop. We're going to store our SDL book-keeping variables globally. // Having a single function that acts as a loop prevents us to store state in the stack of said function. So we need some location for this. -struct MainLoopVars { - SDL_Window* window = NULL; - SDL_GLContext gl_context = NULL; - bool show_demo_window = true; - bool show_another_window = false; - ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); -}; +SDL_Window* g_Window = NULL; +SDL_GLContext g_GLContext = NULL; // For clarity, our main loop code is declared at the end. void main_loop(void*); int main(int, char**) { - MainLoopVars vars; - // Setup SDL if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) { @@ -39,13 +31,14 @@ int main(int, char**) return -1; } - // For the browser using emscripten, we are going to use WebGL2 with GLES3. See the Makefile.emscripten for requirement details. + // For the browser using Emscripten, we are going to use WebGL1 with GL ES2. See the Makefile. for requirement details. // It is very likely the generated file won't work in many browsers. Firefox is the only sure bet, but I have successfully // run this code on Chrome for Android for example. - const char* glsl_version = "#version 300 es"; + const char* glsl_version = "#version 100"; + //const char* glsl_version = "#version 300 es"; SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); // Create window with graphics context @@ -55,9 +48,10 @@ int main(int, char**) SDL_DisplayMode current; SDL_GetCurrentDisplayMode(0, ¤t); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - vars.window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); - vars.gl_context = SDL_GL_CreateContext(vars.window); - if (!vars.gl_context) { + g_Window = SDL_CreateWindow("Dear ImGui Emscripten example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + g_GLContext = SDL_GL_CreateContext(g_Window); + if (!g_GLContext) + { fprintf(stderr, "Failed to initialize WebGL context!\n"); return 1; } @@ -74,7 +68,7 @@ int main(int, char**) //ImGui::StyleColorsClassic(); // Setup Platform/Renderer bindings - ImGui_ImplSDL2_InitForOpenGL(vars.window, vars.gl_context); + ImGui_ImplSDL2_InitForOpenGL(g_Window, g_GLContext); ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts @@ -93,12 +87,18 @@ int main(int, char**) //IM_ASSERT(font != NULL); // This function call won't return, and will engage in an infinite loop, processing events from the browser, and dispatching them. - emscripten_set_main_loop_arg(main_loop, &vars, 0, true); + emscripten_set_main_loop_arg(main_loop, NULL, 0, true); } -void main_loop(void* arg) { - MainLoopVars* vars = (MainLoopVars*) arg; +void main_loop(void* arg) +{ ImGuiIO& io = ImGui::GetIO(); + IM_UNUSED(arg); // We can pass this argument as the second parameter of emscripten_set_main_loop_arg(), but we don't use that. + + // Our state (make them static = more or less global) as a convenience to keep the example terse. + static bool show_demo_window = true; + static bool show_another_window = false; + static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. @@ -114,12 +114,12 @@ void main_loop(void* arg) { // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplSDL2_NewFrame(vars->window); + ImGui_ImplSDL2_NewFrame(g_Window); ImGui::NewFrame(); // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). - if (vars->show_demo_window) - ImGui::ShowDemoWindow(&vars->show_demo_window); + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. { @@ -129,11 +129,11 @@ void main_loop(void* arg) { ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) - ImGui::Checkbox("Demo Window", &vars->show_demo_window); // Edit bools storing our window open/close state - ImGui::Checkbox("Another Window", &vars->show_another_window); + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&vars->clear_color); // Edit 3 floats representing a color + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) counter++; @@ -145,21 +145,21 @@ void main_loop(void* arg) { } // 3. Show another simple window. - if (vars->show_another_window) + if (show_another_window) { - ImGui::Begin("Another Window", &vars->show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) - vars->show_another_window = false; + show_another_window = false; ImGui::End(); } // Rendering ImGui::Render(); - SDL_GL_MakeCurrent(vars->window, vars->gl_context); + SDL_GL_MakeCurrent(g_Window, g_GLContext); glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); - glClearColor(vars->clear_color.x, vars->clear_color.y, vars->clear_color.z, vars->clear_color.w); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - SDL_GL_SwapWindow(vars->window); + SDL_GL_SwapWindow(g_Window); } diff --git a/examples/example_emscripten/shell_minimal.html b/examples/example_emscripten/shell_minimal.html index 3c5ef8ca..b967b04b 100644 --- a/examples/example_emscripten/shell_minimal.html +++ b/examples/example_emscripten/shell_minimal.html @@ -3,15 +3,19 @@ - Emscripten-Generated Code + Dear ImGui Emscripten example -
emscripten
Downloading...
- +
-
+
+ Example compiled from https://github.com/ocornut/imgui
-
+
- Resize canvas - Lock/hide mouse pointer -     - + +
- -
- -
+
+ + {{{ SCRIPT }}} From 1d3ebef364ebec80a3e9b70cc46071f65382339d Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Apr 2019 21:50:15 +0200 Subject: [PATCH 270/566] Columns: Fixed boundary of clipping being off by 1 pixel within the left column. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 16681c6e..c5ecdfe3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] - PlotLines, PlotHistogram: Ignore NaN values when calculating min/max bounds. (#2485) - Window: Window close button is horizontally aligned with style.FramePadding.x. +- Columns: Fixed boundary of clipping being off by 1 pixel within the left column. - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. diff --git a/imgui.cpp b/imgui.cpp index 23e3c8ef..e12c466c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8542,7 +8542,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag { // Compute clipping rectangle ImGuiColumnData* column = &columns->Columns[n]; - float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f); + float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n)); float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); column->ClipRect.ClipWith(window->ClipRect); From 1aeee9d40f7e057230d22f1c5c4b476a00e9dbe7 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Apr 2019 12:26:51 +0200 Subject: [PATCH 271/566] Internals: Columns: Tweaks, renaming. Metrics: Show rectangles for child windows. Renamed SameLine() first parameter. --- imgui.cpp | 68 ++++++++++++++++++++++------------------------- imgui.h | 2 +- imgui_demo.cpp | 3 ++- imgui_internal.h | 12 ++++----- imgui_widgets.cpp | 3 ++- 5 files changed, 43 insertions(+), 45 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e12c466c..18b368d5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6740,21 +6740,21 @@ void ImGui::EndGroup() } // Gets back to previous line and continue with horizontal layout -// pos_x == 0 : follow right after previous item -// pos_x != 0 : align to specified x position (relative to window/group left) -// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 -// spacing_w >= 0 : enforce spacing amount -void ImGui::SameLine(float pos_x, float spacing_w) +// offset_from_start_x == 0 : follow right after previous item +// offset_from_start_x != 0 : align to specified x position (relative to window/group left) +// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 +// spacing_w >= 0 : enforce spacing amount +void ImGui::SameLine(float offset_from_start_x, float spacing_w) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; - if (pos_x != 0.0f) + if (offset_from_start_x != 0.0f) { if (spacing_w < 0.0f) spacing_w = 0.0f; - window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } else @@ -8322,13 +8322,13 @@ void ImGui::NextColumn() columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); if (++columns->Current < columns->Count) { - // Columns 1+ cancel out IndentX + // New column (columns 1+ cancels out IndentX) window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; window->DrawList->ChannelsSetCurrent(columns->Current); } else { - // New line + // New row/line window->DC.ColumnsOffset.x = 0.0f; window->DrawList->ChannelsSetCurrent(0); columns->Current = 0; @@ -8340,7 +8340,7 @@ void ImGui::NextColumn() window->DC.CurrentLineTextBaseOffset = 0.0f; PushColumnClipRect(); - PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup + PushItemWidth(GetColumnWidth() * 0.65f); // FIXME-COLUMNS: Move on columns setup } int ImGui::GetColumnIndex() @@ -8365,7 +8365,7 @@ static float PixelsToOffsetNorm(const ImGuiColumns* columns, float offset) return offset / (columns->MaxX - columns->MinX); } -static inline float GetColumnsRectHalfWidth() { return 4.0f; } +static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) { @@ -8376,7 +8376,7 @@ static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); - float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x; + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); @@ -8515,8 +8515,8 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x); columns->MinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f); - columns->StartPosY = window->DC.CursorPos.y; - columns->StartMaxPosX = window->DC.CursorMaxPos.x; + columns->BackupCursorPosY = window->DC.CursorPos.y; + columns->BackupCursorMaxPosX = window->DC.CursorMaxPos.x; columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -8573,39 +8573,41 @@ void ImGui::EndColumns() columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = columns->LineMaxY; if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize)) - window->DC.CursorMaxPos.x = columns->StartMaxPosX; // Restore cursor max pos, as columns don't grow parent + window->DC.CursorMaxPos.x = columns->BackupCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent // Draw columns borders and handle resize bool is_being_resized = false; if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) { - const float y1 = columns->StartPosY; - const float y2 = window->DC.CursorPos.y; + // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. + const float y1 = ImMax(columns->BackupCursorPosY, window->ClipRect.Min.y); + const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); int dragging_column = -1; for (int n = 1; n < columns->Count; n++) { + ImGuiColumnData* column = &columns->Columns[n]; float x = window->Pos.x + GetColumnOffset(n); const ImGuiID column_id = columns->ID + ImGuiID(n); - const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction - const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2)); + const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; + const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); KeepAliveID(column_id); - if (IsClippedEx(column_rect, column_id, false)) + if (IsClippedEx(column_hit_rect, column_id, false)) continue; bool hovered = false, held = false; if (!(columns->Flags & ImGuiColumnsFlags_NoResize)) { - ButtonBehavior(column_rect, column_id, &hovered, &held); + ButtonBehavior(column_hit_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; - if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize)) + if (held && !(column->Flags & ImGuiColumnsFlags_NoResize)) dragging_column = n; } - // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.) + // Draw column const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); const float xi = (float)(int)x; - window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col); + window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); } // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. @@ -8634,10 +8636,11 @@ void ImGui::Columns(int columns_count, const char* id, bool border) ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior - if (window->DC.CurrentColumns != NULL && window->DC.CurrentColumns->Count == columns_count && window->DC.CurrentColumns->Flags == flags) + ImGuiColumns* columns = window->DC.CurrentColumns; + if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) return; - if (window->DC.CurrentColumns != NULL) + if (columns != NULL) EndColumns(); if (columns_count != 1) @@ -9608,15 +9611,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) static void NodeWindow(ImGuiWindow* window, const char* label) { - bool node_open = ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window); - if (show_windows_rects && ImGui::IsItemHovered()) - if (ImDrawList* fg_draw_list = GetForegroundDrawList(window)) - { - } - - if (!node_open) + if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) return; - ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->DrawList, "DrawList"); ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); @@ -9733,7 +9729,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) for (int n = 0; n < g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; - if ((window->Flags & ImGuiWindowFlags_ChildWindow) || !window->WasActive) + if (!window->WasActive) continue; ImDrawList* draw_list = GetForegroundDrawList(window); if (show_windows_rects) @@ -9746,7 +9742,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) else if (show_windows_rect_type == RT_ContentsRegionRect) { r = window->ContentsRegionRect; } draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } - if (show_windows_begin_order) + if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow)) { char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); diff --git a/imgui.h b/imgui.h index c4400d84..f11a3a50 100644 --- a/imgui.h +++ b/imgui.h @@ -332,7 +332,7 @@ namespace ImGui // - By "cursor" we mean the current output position. // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. - IMGUI_API void SameLine(float local_pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. + IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context. IMGUI_API void Spacing(); // add vertical spacing. IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9b732c3f..443c3c23 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -252,7 +252,6 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::End(); return; } - ImGui::Text("dear imgui says hello. (%s)", IMGUI_VERSION); // Most "big" widgets share a common width settings by default. //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // Use 2/3 of the space for widgets and 1/3 for labels (default) @@ -292,7 +291,9 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::EndMenuBar(); } + ImGui::Text("dear imgui says hello. (%s)", IMGUI_VERSION); ImGui::Spacing(); + if (ImGui::CollapsingHeader("Help")) { ImGui::Text("PROGRAMMER GUIDE:"); diff --git a/imgui_internal.h b/imgui_internal.h index 1b0fd35c..7ed26cfd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -658,7 +658,7 @@ struct ImGuiColumnData ImGuiColumnsFlags Flags; // Not exposed ImRect ClipRect; - ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = 0; } + ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; } }; struct ImGuiColumns @@ -671,23 +671,23 @@ struct ImGuiColumns int Count; float MinX, MaxX; float LineMinY, LineMaxY; - float StartPosY; // Copy of CursorPos - float StartMaxPosX; // Copy of CursorMaxPos + float BackupCursorPosY; // Backup of CursorPos at the time of BeginColumns() + float BackupCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() ImVector Columns; ImGuiColumns() { Clear(); } void Clear() { ID = 0; - Flags = 0; + Flags = ImGuiColumnsFlags_None; IsFirstFrame = false; IsBeingResized = false; Current = 0; Count = 1; MinX = MaxX = 0.0f; LineMinY = LineMaxY = 0.0f; - StartPosY = 0.0f; - StartMaxPosX = 0.0f; + BackupCursorPosY = 0.0f; + BackupCursorMaxPosX = 0.0f; Columns.clear(); } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c9a47b14..dd821ef5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -299,7 +299,8 @@ void ImGui::TextWrapped(const char* fmt, ...) void ImGui::TextWrappedV(const char* fmt, va_list args) { - bool need_backup = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set + ImGuiWindow* window = GetCurrentWindow(); + bool need_backup = (window->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set if (need_backup) PushTextWrapPos(0.0f); TextV(fmt, args); From 240dddff87326abb9990fc938dfe9ced6ad79d9e Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Apr 2019 15:00:40 +0200 Subject: [PATCH 272/566] Combo, Slider: Improve rendering in situation when there's there's very little space available. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 64 +++++++++++++++++++++++++++------------------- 2 files changed, 39 insertions(+), 26 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c5ecdfe3..c9401b3a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,7 @@ Other Changes: - PlotLines, PlotHistogram: Ignore NaN values when calculating min/max bounds. (#2485) - Window: Window close button is horizontally aligned with style.FramePadding.x. - Columns: Fixed boundary of clipping being off by 1 pixel within the left column. +- Combo, Slider, Scrollbar: Improve rendering in situation when there's only a few pixels available (<3 pixels). - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index dd821ef5..2e93b853 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -788,16 +788,19 @@ void ImGui::Scrollbar(ImGuiAxis axis) // Render background bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; - const ImRect window_rect = window->Rect(); + const ImRect host_rect = window->Rect(); const float border_size = window->WindowBorderSize; ImRect bb = horizontal - ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) - : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); + ? ImRect(host_rect.Min.x + border_size, host_rect.Max.y - style.ScrollbarSize, host_rect.Max.x - other_scrollbar_size_w - border_size, host_rect.Max.y - border_size) + : ImRect(host_rect.Max.x - style.ScrollbarSize, host_rect.Min.y + border_size, host_rect.Max.x - border_size, host_rect.Max.y - other_scrollbar_size_w - border_size); + bb.Min.x = ImMax(host_rect.Min.x, bb.Min.x); // Handle case where the host rectangle is smaller than the scrollbar + bb.Min.y = ImMax(host_rect.Min.y, bb.Min.y); if (!horizontal) bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); // FIXME: InnerRect? + const float bb_width = bb.GetWidth(); const float bb_height = bb.GetHeight(); - if (bb.GetWidth() <= 0.0f || bb_height <= 0.0f) + if (bb_width <= 0.0f || bb_height <= 0.0f) return; // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab) @@ -816,7 +819,7 @@ void ImGui::Scrollbar(ImGuiAxis axis) else window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners); - bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); + bb.Expand(ImVec2(-ImClamp((float)(int)((bb_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb_height - 2.0f) * 0.5f), 0.0f, 3.0f))); // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); @@ -887,9 +890,9 @@ void ImGui::Scrollbar(ImGuiAxis axis) const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha); ImRect grab_rect; if (horizontal) - grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y); + grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, host_rect.Max.x), bb.Max.y); else - grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y)); + grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, host_rect.Max.y)); window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); } @@ -1361,19 +1364,19 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); bool popup_open = IsPopupOpen(id); - const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + const float value_x2 = ImMax(frame_bb.Min.x, frame_bb.Max.x - arrow_size); RenderNavHighlight(frame_bb, id); if (!(flags & ImGuiComboFlags_NoPreview)) - window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left); + window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(value_x2, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left); if (!(flags & ImGuiComboFlags_NoArrowButton)) { - window->DrawList->AddRectFilled(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); - RenderArrow(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down); + window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); + RenderArrow(ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down); } RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding); if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) - RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f)); + RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), preview_value, NULL, NULL, ImVec2(0.0f,0.0f)); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -2223,16 +2226,16 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit grab_sz = ImMin(grab_sz, slider_sz); const float slider_usable_sz = slider_sz - grab_sz; - const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz*0.5f; - const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz*0.5f; + const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f; + const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; // For power curve sliders that cross over sign boundary we want the curve to be symmetric around 0.0f float linear_zero_pos; // 0.0->1.0f if (is_power && v_min * v_max < 0.0f) { // Different sign - const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f/power); - const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f/power); + const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f / power); + const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f / power); linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0)); } else @@ -2355,15 +2358,22 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } } - // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); - if (axis == ImGuiAxis_Y) - grab_t = 1.0f - grab_t; - const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); - if (axis == ImGuiAxis_X) - *out_grab_bb = ImRect(grab_pos - grab_sz*0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz*0.5f, bb.Max.y - grab_padding); + if (slider_sz < 1.0f) + { + *out_grab_bb = ImRect(bb.Min, bb.Min); + } else - *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f); + { + // Output grab position so it can be displayed by the caller + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + if (axis == ImGuiAxis_Y) + grab_t = 1.0f - grab_t; + const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); + if (axis == ImGuiAxis_X) + *out_grab_bb = ImRect(grab_pos - grab_sz * 0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5f, bb.Max.y - grab_padding); + else + *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5f); + } return value_changed; } @@ -2465,7 +2475,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co MarkItemEdited(id); // Render grab - window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + if (grab_bb.Max.x > grab_bb.Min.x) + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; @@ -2605,7 +2616,8 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d MarkItemEdited(id); // Render grab - window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + if (grab_bb.Max.y > grab_bb.Min.y) + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding From 9d4a893a774603fb2fa0c19ba063d9df46baa1a5 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Apr 2019 13:46:45 +0200 Subject: [PATCH 273/566] Internals: Moved CalcItemSize next to CalcItemWidth, added comments to clarify their respective intent. Should have no side effect. --- imgui.cpp | 31 +++++++++++++++++-------------- imgui_internal.h | 2 +- imgui_widgets.cpp | 3 +++ 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 18b368d5..d08f9d5a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2973,19 +2973,6 @@ void ImGui::FocusableItemUnregister(ImGuiWindow* window) window->DC.FocusCounterTab--; } -ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) -{ - ImGuiContext& g = *GImGui; - ImVec2 content_max; - if (size.x < 0.0f || size.y < 0.0f) - content_max = g.CurrentWindow->Pos + GetContentRegionMax(); - if (size.x <= 0.0f) - size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; - if (size.y <= 0.0f) - size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; - return size; -} - float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) @@ -5785,13 +5772,13 @@ void ImGui::PopItemWidth() window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } +// Calculate default item width given value passed to PushItemWidth() float ImGui::CalcItemWidth() { ImGuiWindow* window = GetCurrentWindowRead(); float w = window->DC.ItemWidth; if (w < 0.0f) { - // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. float width_to_right_edge = GetContentRegionAvail().x; w = ImMax(1.0f, width_to_right_edge + w); } @@ -5799,6 +5786,22 @@ float ImGui::CalcItemWidth() return w; } +// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). +// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. +// Note that only CalcItemWidth() is publicly exposed. +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImVec2 content_max; + if (size.x < 0.0f || size.y < 0.0f) + content_max = window->Pos + GetContentRegionMax(); + if (size.x <= 0.0f) + size.x = (size.x == 0.0f) ? default_w : ImMax(content_max.x - window->DC.CursorPos.x, 4.0f) + size.x; + if (size.y <= 0.0f) + size.y = (size.y == 0.0f) ? default_h : ImMax(content_max.y - window->DC.CursorPos.y, 4.0f) + size.y; + return size; +} + void ImGui::SetCurrentFont(ImFont* font) { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index 7ed26cfd..843eaa44 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1438,7 +1438,7 @@ namespace ImGui IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); - IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full = 0.0f); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2e93b853..060c8a32 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5440,6 +5440,9 @@ bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags // - ListBoxHeader() // - ListBoxFooter() //------------------------------------------------------------------------- +// FIXME: This is an old API. We should redesign some of it, rename ListBoxHeader->BeginListBox, ListBoxFooter->EndListBox +// and promote using them over existing ListBox() functions, similarly to change with combo boxes. +//------------------------------------------------------------------------- // FIXME: In principle this function should be called BeginListBox(). We should rename it after re-evaluating if we want to keep the same signature. // Helper to calculate the size of a listbox and display a label on the right. From f355a403675c75ec88d0c53322c41fe2d12fa0de Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Apr 2019 14:10:01 +0200 Subject: [PATCH 274/566] Added commentary about ContentRegion functions. Added internal GetContentRegionMaxScreen() to facilitate internal code at the moment. --- imgui.cpp | 26 ++++++++++++++++++-------- imgui.h | 17 ++++++++++------- imgui_internal.h | 1 + imgui_widgets.cpp | 2 +- 4 files changed, 30 insertions(+), 16 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d08f9d5a..20ecf03c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2978,9 +2978,9 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) if (wrap_pos_x < 0.0f) return 0.0f; - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiWindow* window = GImGui->CurrentWindow; if (wrap_pos_x == 0.0f) - wrap_pos_x = GetContentRegionMax().x + window->Pos.x; + wrap_pos_x = GetContentRegionMaxScreen().x; else if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space @@ -5775,7 +5775,7 @@ void ImGui::PopItemWidth() // Calculate default item width given value passed to PushItemWidth() float ImGui::CalcItemWidth() { - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiWindow* window = GImGui->CurrentWindow; float w = window->DC.ItemWidth; if (w < 0.0f) { @@ -5791,10 +5791,10 @@ float ImGui::CalcItemWidth() // Note that only CalcItemWidth() is publicly exposed. ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 content_max; if (size.x < 0.0f || size.y < 0.0f) - content_max = window->Pos + GetContentRegionMax(); + content_max = GetContentRegionMaxScreen(); if (size.x <= 0.0f) size.x = (size.x == 0.0f) ? default_w : ImMax(content_max.x - window->DC.CursorPos.x, 4.0f) + size.x; if (size.y <= 0.0f) @@ -6367,17 +6367,27 @@ void ImGui::SetNextWindowBgAlpha(float alpha) // FIXME: This is in window space (not screen space!) ImVec2 ImGui::GetContentRegionMax() { - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max - window->Pos; if (window->DC.CurrentColumns) mx.x = GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x; return mx; } +// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. +ImVec2 ImGui::GetContentRegionMaxScreen() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + ImVec2 mx = window->ContentsRegionRect.Max; + if (window->DC.CurrentColumns) + mx.x = window->Pos.x + GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x; + return mx; +} + ImVec2 ImGui::GetContentRegionAvail() { - ImGuiWindow* window = GetCurrentWindowRead(); - return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); + ImGuiWindow* window = GImGui->CurrentWindow; + return GetContentRegionMaxScreen() - window->DC.CursorPos; } float ImGui::GetContentRegionAvailWidth() diff --git a/imgui.h b/imgui.h index f11a3a50..f597e07b 100644 --- a/imgui.h +++ b/imgui.h @@ -261,18 +261,12 @@ namespace ImGui IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives - IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API) IMGUI_API ImVec2 GetWindowSize(); // get current window size IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) - IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates - IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() - IMGUI_API float GetContentRegionAvailWidth(); // == GetContentRegionAvail().x - IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates - IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates - IMGUI_API float GetWindowContentRegionWidth(); // + // Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. @@ -290,6 +284,15 @@ namespace ImGui IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. + // Content region + // - Those functions are bound to be redesigned soon (they are confusing, incomplete and return values in local window coordinates which increases confusion) + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API float GetContentRegionAvailWidth(); // == GetContentRegionAvail().x + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates + IMGUI_API float GetWindowContentRegionWidth(); // + // Windows Scrolling IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] diff --git a/imgui_internal.h b/imgui_internal.h index 843eaa44..b399becd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1444,6 +1444,7 @@ namespace ImGui IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); IMGUI_API bool IsItemToggledSelection(); // was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) + IMGUI_API ImVec2 GetContentRegionMaxScreen(); // Logging/Capture IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 060c8a32..6812808e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5057,7 +5057,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // We vertically grow up to current line height up the typical widget height. const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it const float frame_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); - ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); + ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(GetContentRegionMaxScreen().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding From a1cf7d636d5dca6005a7af0af12da8564e61f723 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Apr 2019 14:48:36 +0200 Subject: [PATCH 275/566] Internals: Rework CalcItemWidth / CalcItemSize but make their similarities and their differences more obvious. (#2449) --- imgui.cpp | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 20ecf03c..02d7ad9f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5779,8 +5779,8 @@ float ImGui::CalcItemWidth() float w = window->DC.ItemWidth; if (w < 0.0f) { - float width_to_right_edge = GetContentRegionAvail().x; - w = ImMax(1.0f, width_to_right_edge + w); + float region_max_x = GetContentRegionMaxScreen().x; + w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); } w = (float)(int)w; return w; @@ -5792,13 +5792,21 @@ float ImGui::CalcItemWidth() ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { ImGuiWindow* window = GImGui->CurrentWindow; - ImVec2 content_max; + + ImVec2 region_max; if (size.x < 0.0f || size.y < 0.0f) - content_max = GetContentRegionMaxScreen(); - if (size.x <= 0.0f) - size.x = (size.x == 0.0f) ? default_w : ImMax(content_max.x - window->DC.CursorPos.x, 4.0f) + size.x; - if (size.y <= 0.0f) - size.y = (size.y == 0.0f) ? default_h : ImMax(content_max.y - window->DC.CursorPos.y, 4.0f) + size.y; + region_max = GetContentRegionMaxScreen(); + + if (size.x == 0.0f) + size.x = default_w; + else if (size.x < 0.0f) + size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x) + size.x; + + if (size.y == 0.0f) + size.y = default_h; + else if (size.y < 0.0f) + size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y) + size.y; + return size; } From 0e46d65b031ea796439d9df2c43215d51b625d44 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Apr 2019 15:35:20 +0200 Subject: [PATCH 276/566] Misc: Fixed PushItemWidth(-width) (for right-side alignment) laying out certain items (button, listbox, etc.) with negative sizes if the 'width' argument was smaller than the available width at the time of item submission, --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c9401b3a..511e381c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,8 @@ Other Changes: - Window: Window close button is horizontally aligned with style.FramePadding.x. - Columns: Fixed boundary of clipping being off by 1 pixel within the left column. - Combo, Slider, Scrollbar: Improve rendering in situation when there's only a few pixels available (<3 pixels). +- Misc: Fixed PushItemWidth(-width) (for right-side alignment) laying out certain items (button, listbox, etc.) + with negative sizes if the 'width' argument was smaller than the available width at the time of item submission, - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. diff --git a/imgui.cpp b/imgui.cpp index 02d7ad9f..2b4b7a83 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5789,6 +5789,7 @@ float ImGui::CalcItemWidth() // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. // Note that only CalcItemWidth() is publicly exposed. +// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { ImGuiWindow* window = GImGui->CurrentWindow; @@ -5800,12 +5801,12 @@ ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) if (size.x == 0.0f) size.x = default_w; else if (size.x < 0.0f) - size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x) + size.x; + size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x); if (size.y == 0.0f) size.y = default_h; else if (size.y < 0.0f) - size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y) + size.y; + size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y); return size; } From 8d53f834ee1a5ae965fa8562e44039db59aeb199 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Apr 2019 18:24:51 +0200 Subject: [PATCH 277/566] Demo: Documents: Fix misusage of ListBoxHeader(). --- imgui_demo.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 443c3c23..6dd69bd3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4402,11 +4402,13 @@ void ShowExampleAppDocuments(bool* p_open) { ImGui::Text("Save change to the following items?"); ImGui::PushItemWidth(-1.0f); - ImGui::ListBoxHeader("##", close_queue_unsaved_documents, 6); - for (int n = 0; n < close_queue.Size; n++) - if (close_queue[n]->Dirty) - ImGui::Text("%s", close_queue[n]->Name); - ImGui::ListBoxFooter(); + if (ImGui::ListBoxHeader("##", close_queue_unsaved_documents, 6)) + { + for (int n = 0; n < close_queue.Size; n++) + if (close_queue[n]->Dirty) + ImGui::Text("%s", close_queue[n]->Name); + ImGui::ListBoxFooter(); + } if (ImGui::Button("Yes", ImVec2(80, 0))) { From 5078fa208b2dcfa130fcbaa4260f958894ef16b5 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Apr 2019 18:29:28 +0200 Subject: [PATCH 278/566] Added SetNextItemWidth() helper to avoid using PushItemWidth/PopItemWidth() for single items. --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 49 ++++++++++++++++++++++++++++++------------- imgui.h | 3 ++- imgui_demo.cpp | 52 ++++++++++++++++++++++------------------------ imgui_internal.h | 5 ++++- imgui_widgets.cpp | 46 ++++++++++++++++++---------------------- 6 files changed, 90 insertions(+), 69 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 511e381c..39f0da96 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,10 @@ Other Changes: - InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) - InputText: Fixed ImGuiInputTextFlags_AllowTabInput leading to two tabs characters being inserted if the back-end provided both Key and Character input. (#2467, #1336) +- Added SetNextItemWidth() helper to avoid using PushItemWidth/PopItemWidth() for single items. + Note that SetNextItemWidth() currently only affect the same subset of items as PushItemWidth(), + generally referred to as the large framed+labeled items. + Because the new SetNextItemWidth() function is explicit - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] diff --git a/imgui.cpp b/imgui.cpp index 2b4b7a83..8f56ab6c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2068,10 +2068,8 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) - ImGui::PushItemWidth(width); + ImGui::SetNextItemWidth(width); bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); - if (width != 0.0f) - ImGui::PopItemWidth(); if (value_changed) Build(); return value_changed; @@ -5744,6 +5742,12 @@ void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window) } } +void ImGui::SetNextItemWidth(float item_width) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.NextItemWidth = item_width; +} + void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); @@ -5755,8 +5759,6 @@ void ImGui::PushMultiItemsWidths(int components, float w_full) { ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = GImGui->Style; - if (w_full <= 0.0f) - w_full = CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); window->DC.ItemWidthStack.push_back(w_item_last); @@ -5772,11 +5774,21 @@ void ImGui::PopItemWidth() window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } -// Calculate default item width given value passed to PushItemWidth() -float ImGui::CalcItemWidth() +// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(), +// Then consume the +float ImGui::GetNextItemWidth() { ImGuiWindow* window = GImGui->CurrentWindow; - float w = window->DC.ItemWidth; + float w; + if (window->DC.NextItemWidth != FLT_MAX) + { + w = window->DC.NextItemWidth; + window->DC.NextItemWidth = FLT_MAX; + } + else + { + w = window->DC.ItemWidth; + } if (w < 0.0f) { float region_max_x = GetContentRegionMaxScreen().x; @@ -5786,10 +5798,21 @@ float ImGui::CalcItemWidth() return w; } -// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). +// Calculate item width *without* popping/consuming NextItemWidth if it was set. +// (rarely used, which is why we avoid calling this from GetNextItemWidth() and instead do a backup/restore here) +float ImGui::CalcItemWidth() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + float backup_next_item_width = window->DC.NextItemWidth; + float w = GetNextItemWidth(); + window->DC.NextItemWidth = backup_next_item_width; + return w; +} + +// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == GetNextItemWidth(). // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. // Note that only CalcItemWidth() is publicly exposed. -// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) +// The 4.0f here may be changed to match GetNextItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { ImGuiWindow* window = GImGui->CurrentWindow; @@ -9147,11 +9170,10 @@ void ImGui::LogButtons() const bool log_to_tty = Button("Log To TTY"); SameLine(); const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); - PushItemWidth(80.0f); PushAllowKeyboardFocus(false); + SetNextItemWidth(80.0f); SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); PopAllowKeyboardFocus(); - PopItemWidth(); PopID(); // Start logging at the end of the function so that the buttons don't appear in the log @@ -9739,9 +9761,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Checkbox("Show windows begin order", &show_windows_begin_order); ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); - ImGui::PushItemWidth(ImGui::GetFontSize() * 12); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerMainRect\0" "InnerClipRect\0" "ContentsRegionRect\0"); - ImGui::PopItemWidth(); ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects); ImGui::TreePop(); } diff --git a/imgui.h b/imgui.h index f597e07b..53e17253 100644 --- a/imgui.h +++ b/imgui.h @@ -321,8 +321,9 @@ namespace ImGui IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied // Parameters stacks (current window) - IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) + IMGUI_API void PushItemWidth(float item_width); // set width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side). 0.0f = default to ~2/3 of windows width, IMGUI_API void PopItemWidth(); + IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6dd69bd3..2233eab7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -550,9 +550,8 @@ static void ShowDemoWindowWidgets() ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); //static int listbox_item_current2 = 2; - //ImGui::PushItemWidth(-1); + //ImGui::SetNextItemWidth(-1); //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); - //ImGui::PopItemWidth(); } ImGui::TreePop(); @@ -1052,7 +1051,8 @@ static void ShowDemoWindowWidgets() }; static int func_type = 0, display_count = 70; ImGui::Separator(); - ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth(); + ImGui::SetNextItemWidth(100); + ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::SameLine(); ImGui::SliderInt("Sample count", &display_count, 1, 400); float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; @@ -1667,9 +1667,8 @@ static void ShowDemoWindowLayout() static int line = 50; bool goto_line = ImGui::Button("Goto"); ImGui::SameLine(); - ImGui::PushItemWidth(100); + ImGui::SetNextItemWidth(100); goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); - ImGui::PopItemWidth(); // Child 1: no border, enable horizontal scrollbar { @@ -1740,35 +1739,36 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Widgets Width")) { + // Use SetNextItemWidth() to set the width of a single upcoming item. + // Use PushItemWidth()/PopItemWidth() to set the width of a group of items. static float f = 0.0f; - ImGui::Text("PushItemWidth(100)"); + ImGui::Text("SetNextItemWidth/PushItemWidth(100)"); ImGui::SameLine(); HelpMarker("Fixed width."); - ImGui::PushItemWidth(100); + ImGui::SetNextItemWidth(100); ImGui::DragFloat("float##1", &f); - ImGui::PopItemWidth(); - ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)"); + ImGui::Text("SetNextItemWidth/PushItemWidth(GetWindowWidth() * 0.5f)"); ImGui::SameLine(); HelpMarker("Half of window width."); - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); + ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::DragFloat("float##2", &f); - ImGui::PopItemWidth(); - ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); + ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); - ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); ImGui::DragFloat("float##3", &f); - ImGui::PopItemWidth(); - ImGui::Text("PushItemWidth(-100)"); + ImGui::Text("SetNextItemWidth/PushItemWidth(-100)"); ImGui::SameLine(); HelpMarker("Align to right edge minus 100"); - ImGui::PushItemWidth(-100); + ImGui::SetNextItemWidth(-100); ImGui::DragFloat("float##4", &f); - ImGui::PopItemWidth(); - ImGui::Text("PushItemWidth(-1)"); + // Demonstrate using PushItemWidth to surround three items. Calling SetNextItemWidth() before each of them would have the same effect. + ImGui::Text("SetNextItemWidth/PushItemWidth(-1)"); ImGui::SameLine(); HelpMarker("Align to right edge"); ImGui::PushItemWidth(-1); - ImGui::DragFloat("float##5", &f); + ImGui::DragFloat("float##5a", &f); + ImGui::DragFloat("float##5b", &f); + ImGui::DragFloat("float##5c", &f); ImGui::PopItemWidth(); ImGui::TreePop(); @@ -2241,9 +2241,8 @@ static void ShowDemoWindowPopups() { if (ImGui::Selectable("Set to zero")) value = 0.0f; if (ImGui::Selectable("Set to PI")) value = 3.1415f; - ImGui::PushItemWidth(-1); + ImGui::SetNextItemWidth(-1); ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f); - ImGui::PopItemWidth(); ImGui::EndPopup(); } @@ -2968,7 +2967,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) } ImGui::LogFinish(); } - ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified); static ImGuiTextFilter filter; @@ -3807,12 +3806,11 @@ static void ShowExampleAppPropertyEditor(bool* p_open) ImGui::AlignTextToFramePadding(); ImGui::TreeNodeEx("Field", ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet, "Field_%d", i); ImGui::NextColumn(); - ImGui::PushItemWidth(-1); + ImGui::SetNextItemWidth(-1); if (i >= 5) ImGui::InputFloat("##value", &dummy_members[i], 1.0f); else ImGui::DragFloat("##value", &dummy_members[i], 0.01f); - ImGui::PopItemWidth(); ImGui::NextColumn(); } ImGui::PopID(); @@ -3952,10 +3950,10 @@ static void ShowExampleAppConstrainedResize(bool* p_open) if (ImGui::Button("200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine(); if (ImGui::Button("500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine(); if (ImGui::Button("800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); } - ImGui::PushItemWidth(200); + ImGui::SetNextItemWidth(200); ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); + ImGui::SetNextItemWidth(200); ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100); - ImGui::PopItemWidth(); ImGui::Checkbox("Auto-resize", &auto_resize); for (int i = 0; i < display_lines; i++) ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, ""); @@ -4401,7 +4399,7 @@ void ShowExampleAppDocuments(bool* p_open) if (ImGui::BeginPopupModal("Save?")) { ImGui::Text("Save change to the following items?"); - ImGui::PushItemWidth(-1.0f); + ImGui::SetNextItemWidth(-1.0f); if (ImGui::ListBoxHeader("##", close_queue_unsaved_documents, 6)) { for (int n = 0; n < close_queue.Size; n++) diff --git a/imgui_internal.h b/imgui_internal.h index b399becd..9107cfea 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1146,6 +1146,7 @@ struct IMGUI_API ImGuiWindowTempData // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default] float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window + float NextItemWidth; float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] ImVectorItemFlagsStack; ImVector ItemWidthStack; @@ -1181,6 +1182,7 @@ struct IMGUI_API ImGuiWindowTempData ItemFlags = ImGuiItemFlags_Default_; ItemWidth = 0.0f; + NextItemWidth = +FLT_MAX; TextWrapPos = -1.0f; memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); @@ -1438,9 +1440,10 @@ namespace ImGui IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); + IMGUI_API float GetNextItemWidth(); IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); - IMGUI_API void PushMultiItemsWidths(int components, float width_full = 0.0f); + IMGUI_API void PushMultiItemsWidths(int components, float width_full); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); IMGUI_API bool IsItemToggledSelection(); // was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6812808e..d1ecf3ba 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -325,7 +325,7 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float w = CalcItemWidth(); + const float w = GetNextItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); @@ -1089,7 +1089,7 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over const ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; - ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f); + ImVec2 size = CalcItemSize(size_arg, GetNextItemWidth(), g.FontSize + style.FramePadding.y*2.0f); ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, 0)) @@ -1353,7 +1353,8 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth(); + const float expected_w = GetNextItemWidth(); + const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : expected_w; const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); @@ -1978,7 +1979,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = CalcItemWidth(); + const float w = GetNextItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); @@ -2052,7 +2053,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int bool value_changed = false; BeginGroup(); PushID(label); - PushMultiItemsWidths(components); + PushMultiItemsWidths(components, GetNextItemWidth()); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { @@ -2099,7 +2100,7 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); - PushMultiItemsWidths(2); + PushMultiItemsWidths(2, GetNextItemWidth()); bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power); PopItemWidth(); @@ -2144,7 +2145,7 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); - PushMultiItemsWidths(2); + PushMultiItemsWidths(2, GetNextItemWidth()); bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format); PopItemWidth(); @@ -2422,7 +2423,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = CalcItemWidth(); + const float w = GetNextItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); @@ -2501,7 +2502,7 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i bool value_changed = false; BeginGroup(); PushID(label); - PushMultiItemsWidths(components); + PushMultiItemsWidths(components, GetNextItemWidth()); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { @@ -2790,10 +2791,9 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() PushID(label); - PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); + SetNextItemWidth(ImMax(1.0f, GetNextItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format); - PopItemWidth(); // Step buttons const ImVec2 backup_frame_padding = style.FramePadding; @@ -2839,7 +2839,7 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, in bool value_changed = false; BeginGroup(); PushID(label); - PushMultiItemsWidths(components); + PushMultiItemsWidths(components, GetNextItemWidth()); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { @@ -3289,7 +3289,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ BeginGroup(); const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + ImVec2 size = CalcItemSize(size_arg, GetNextItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); @@ -4047,7 +4047,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag const ImGuiStyle& style = g.Style; const float square_sz = GetFrameHeight(); const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); - const float w_items_all = CalcItemWidth() - w_extra; + const float w_items_all = GetNextItemWidth() - w_extra; const char* label_display_end = FindRenderedTextEnd(label); BeginGroup(); @@ -4112,13 +4112,11 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag }; const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1; - PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) SameLine(0, style.ItemInnerSpacing.x); - if (n + 1 == components) - PushItemWidth(w_item_last); + SetNextItemWidth((n + 1 < components) ? w_item_one : w_item_last); if (flags & ImGuiColorEditFlags_Float) { value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); @@ -4131,8 +4129,6 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); } - PopItemWidth(); - PopItemWidth(); } else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { @@ -4142,7 +4138,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255)); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255)); - PushItemWidth(w_items_all); + SetNextItemWidth(w_items_all); if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { value_changed = true; @@ -4157,7 +4153,6 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); - PopItemWidth(); } ImGuiWindow* picker_active_window = NULL; @@ -4190,9 +4185,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; - PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? + SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); - PopItemWidth(); EndPopup(); } } @@ -4360,7 +4354,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl ImVec2 picker_pos = window->DC.CursorPos; float square_sz = GetFrameHeight(); float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars - float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box + float sv_picker_size = ImMax(bars_width * 1, GetNextItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x; float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x; float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f); @@ -5458,7 +5452,7 @@ bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. - ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + ImVec2 size = CalcItemSize(size_arg, GetNextItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); @@ -5575,7 +5569,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge const ImVec2 label_size = CalcTextSize(label, NULL, true); if (frame_size.x == 0.0f) - frame_size.x = CalcItemWidth(); + frame_size.x = GetNextItemWidth(); if (frame_size.y == 0.0f) frame_size.y = label_size.y + (style.FramePadding.y * 2); From 59f012d65603c5961b6eb3f6d2a003f0ba9d100e Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Apr 2019 19:48:51 +0200 Subject: [PATCH 279/566] Internals: ImHashStr() default parameter. --- imgui.cpp | 16 ++++++++-------- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8f56ab6c..5d705e4e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2535,7 +2535,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(&context->DrawListSharedData) { Name = ImStrdup(name); - ID = ImHashStr(name, 0); + ID = ImHashStr(name); IDStack.push_back(ID); Flags = ImGuiWindowFlags_None; Pos = ImVec2(0.0f, 0.0f); @@ -3629,7 +3629,7 @@ void ImGui::Initialize(ImGuiContext* context) // Add .ini handle for ImGuiWindow type ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Window"; - ini_handler.TypeHash = ImHashStr("Window", 0); + ini_handler.TypeHash = ImHashStr("Window"); ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen; ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine; ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll; @@ -4562,7 +4562,7 @@ ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) ImGuiWindow* ImGui::FindWindowByName(const char* name) { - ImGuiID id = ImHashStr(name, 0); + ImGuiID id = ImHashStr(name); return FindWindowByID(id); } @@ -8769,7 +8769,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) else { window = NULL; - source_id = ImHashStr("#SourceExtern", 0); + source_id = ImHashStr("#SourceExtern"); source_drag_active = true; } @@ -9210,7 +9210,7 @@ ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) g.SettingsWindows.push_back(ImGuiWindowSettings()); ImGuiWindowSettings* settings = &g.SettingsWindows.back(); settings->Name = ImStrdup(name); - settings->ID = ImHashStr(name, 0); + settings->ID = ImHashStr(name); return settings; } @@ -9225,7 +9225,7 @@ ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) { - if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name, 0))) + if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name))) return settings; return CreateNewWindowSettings(name); } @@ -9243,7 +9243,7 @@ void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) { ImGuiContext& g = *GImGui; - const ImGuiID type_hash = ImHashStr(type_name, 0); + const ImGuiID type_hash = ImHashStr(type_name); for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].TypeHash == type_hash) return &g.SettingsHandlers[handler_n]; @@ -9347,7 +9347,7 @@ const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { - ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name, 0)); + ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); if (!settings) settings = ImGui::CreateNewWindowSettings(name); return (void*)settings; diff --git a/imgui_internal.h b/imgui_internal.h index 9107cfea..b0a26a95 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -153,7 +153,7 @@ IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, cons // Helpers: Misc IMGUI_API ImU32 ImHashData(const void* data, size_t data_size, ImU32 seed = 0); -IMGUI_API ImU32 ImHashStr(const char* data, size_t data_size, ImU32 seed = 0); +IMGUI_API ImU32 ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0); IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size = NULL, int padding_bytes = 0); IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode); static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } @@ -630,7 +630,7 @@ struct ImGuiWindowSettings struct ImGuiSettingsHandler { const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' - ImGuiID TypeHash; // == ImHashStr(TypeName, 0, 0) + ImGuiID TypeHash; // == ImHashStr(TypeName) void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d1ecf3ba..82d792d6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6468,7 +6468,7 @@ static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label) { if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) { - ImGuiID id = ImHashStr(label, 0); + ImGuiID id = ImHashStr(label); KeepAliveID(id); return id; } From 20f0cb02816832644a5e05b0909e3fad71355e3d Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Apr 2019 20:28:43 +0200 Subject: [PATCH 280/566] Docking: Fixed an issue where DockBuilderSplitNode() wouldn't update the CentralNode shortcut immediately, which was problematic for immediately following DockBuilderDockWindow(). (#2109) --- imgui.cpp | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f8ffeef7..48cbad13 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11421,9 +11421,11 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) // Central node property needs to be moved to a leaf node, pick the last focused one. // FIXME-DOCKING: If we had to transfer other flags here, what would the policy be? ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeID); - IM_ASSERT(last_focused_node != NULL && DockNodeGetRootNode(last_focused_node) == DockNodeGetRootNode(payload_node)); + ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node); + IM_ASSERT(last_focused_node != NULL && last_focused_root_node == DockNodeGetRootNode(payload_node)); last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode; + last_focused_root_node->CentralNode = last_focused_node; } IM_ASSERT(node->Windows.Size == 0); @@ -11752,17 +11754,18 @@ static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node) DockNodeRemoveTabBar(node); } -struct ImGuiDockNodeUpdateScanResults +// Search function called once by root node in DockNodeUpdate() +struct ImGuiDockNodeFindInfoResults { ImGuiDockNode* CentralNode; ImGuiDockNode* FirstNodeWithWindows; int CountNodesWithWindows; //ImGuiWindowClass WindowClassForMerges; - ImGuiDockNodeUpdateScanResults() { CentralNode = FirstNodeWithWindows = NULL; CountNodesWithWindows = 0; } + ImGuiDockNodeFindInfoResults() { CentralNode = FirstNodeWithWindows = NULL; CountNodesWithWindows = 0; } }; -static void DockNodeUpdateScanRec(ImGuiDockNode* node, ImGuiDockNodeUpdateScanResults* results) +static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeFindInfoResults* results) { if (node->Windows.Size > 0) { @@ -11779,9 +11782,9 @@ static void DockNodeUpdateScanRec(ImGuiDockNode* node, ImGuiDockNodeUpdateScanRe if (results->CountNodesWithWindows > 1 && results->CentralNode != NULL) return; if (node->ChildNodes[0]) - DockNodeUpdateScanRec(node->ChildNodes[0], results); + DockNodeFindInfo(node->ChildNodes[0], results); if (node->ChildNodes[1]) - DockNodeUpdateScanRec(node->ChildNodes[1], results); + DockNodeFindInfo(node->ChildNodes[1], results); } // - Remove inactive windows/nodes. @@ -11880,8 +11883,8 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) // FIXME-DOCK: Merge this scan into the one above. // - Setup central node pointers // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) - ImGuiDockNodeUpdateScanResults results; - DockNodeUpdateScanRec(node, &results); + ImGuiDockNodeFindInfoResults results; + DockNodeFindInfo(node, &results); node->CentralNode = results.CentralNode; node->OnlyNodeWithWindows = (results.CountNodesWithWindows == 1) ? results.FirstNodeWithWindows : NULL; if (node->LastFocusedNodeID == 0 && results.FirstNodeWithWindows != NULL) @@ -12754,11 +12757,13 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node); DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size); - // Flags transfer + // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property) child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_; parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; + if (child_inheritor->IsCentralNode()) + DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor; } void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child) @@ -13062,10 +13067,15 @@ void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond) // Policy: Find central node or latest focused node. We first move back to our root node. new_node = DockNodeGetRootNode(new_node); if (new_node->CentralNode) + { + IM_ASSERT(new_node->CentralNode->IsCentralNode()); dock_id = new_node->CentralNode->ID; + } else + { dock_id = new_node->LastFocusedNodeID; } + } if (window->DockId == dock_id) return; @@ -13340,6 +13350,7 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) else if (has_central_node) { root_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; + root_node->CentralNode = root_node; } } From f159eb35fb562f1c29732322f9ea0a9a2ab0cae4 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Apr 2019 10:42:39 +0200 Subject: [PATCH 281/566] Examples: SDL: Removed unused code. (#2484) --- examples/example_sdl_opengl2/main.cpp | 2 -- examples/example_sdl_opengl3/main.cpp | 2 -- examples/example_sdl_vulkan/main.cpp | 2 -- 3 files changed, 6 deletions(-) diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index 029acefa..aaaf3ee7 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -28,8 +28,6 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); - SDL_DisplayMode current; - SDL_GetCurrentDisplayMode(0, ¤t); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_GLContext gl_context = SDL_GL_CreateContext(window); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 246449af..5b319a14 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -52,8 +52,6 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); - SDL_DisplayMode current; - SDL_GetCurrentDisplayMode(0, ¤t); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_GLContext gl_context = SDL_GL_CreateContext(window); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 812d0988..58a49949 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -326,8 +326,6 @@ int main(int, char**) } // Setup window - SDL_DisplayMode current; - SDL_GetCurrentDisplayMode(0, ¤t); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); From 16e9b8191b14d708b19263be26a1d975376b1ee4 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Apr 2019 11:16:17 +0200 Subject: [PATCH 282/566] Increased IMGUI_VERSION_NUM arbitrarily, help narrowing down reports that don't include a commit hash. Add comments. --- imgui.h | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/imgui.h b/imgui.h index 53e17253..37640640 100644 --- a/imgui.h +++ b/imgui.h @@ -47,7 +47,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.70 WIP" -#define IMGUI_VERSION_NUM 16990 +#define IMGUI_VERSION_NUM 16991 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -212,10 +212,10 @@ namespace ImGui // Main IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame. - IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until Render()/EndFrame(). - IMGUI_API void EndFrame(); // ends the ImGui frame. automatically called by Render(), you likely don't need to call that yourself directly. If you don't need to render data (skipping rendering) you may call EndFrame() but you'll have wasted CPU already! If you don't need to render, better to not create any imgui windows and not call NewFrame() at all! - IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data. (Obsolete: optionally call io.RenderDrawListsFn if set. Nowadays, prefer calling your render function yourself.) - IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. (Obsolete: this used to be passed to your io.RenderDrawListsFn() function.) + IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). + IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(), you likely don't need to call that yourself directly. If you don't need to render data (skipping rendering) you may call EndFrame() but you'll have wasted CPU already! If you don't need to render, better to not create any imgui windows and not call NewFrame() at all! + IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can get call GetDrawData() to obtain it and run your rendering function. (Obsolete: this used to call io.RenderDrawListsFn(). Nowadays, we allow and prefer calling your render function yourself.) + IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. // Demo, Debug, Information IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! @@ -1921,7 +1921,8 @@ struct ImDrawList }; // All draw data to render an ImGui frame -// (NB: the style and the naming convention here is a little inconsistent but we preserve them for backward compatibility purpose) +// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) struct ImDrawData { bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. From d0fb547dc1daecf7338e064abc6a2269540ae00d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Apr 2019 11:46:04 +0200 Subject: [PATCH 283/566] Viewports: Avoid rendering/swapping secondary viewports that are minimized. (#1542, #2496) --- imgui.cpp | 35 ++++++++++++++++++++++++----------- imgui.h | 5 +++-- imgui_internal.h | 3 +-- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 48cbad13..d2d7a472 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5622,7 +5622,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Pos = FindBestWindowPosForPopup(window); // Late create viewport if we don't fit within our current host viewport. - if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !window->Viewport->PlatformWindowMinimized) + if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized)) if (!window->Viewport->GetRect().Contains(window->Rect())) { // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport) @@ -10171,7 +10171,7 @@ static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport) { ImGuiContext& g = *GImGui; - if (!(viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) || window->Viewport == viewport || viewport->PlatformWindowMinimized) + if (!(viewport->Flags & (ImGuiViewportFlags_CanHostOtherWindows | ImGuiViewportFlags_Minimized)) || window->Viewport == viewport) return false; if (!viewport->GetRect().Contains(window->Rect())) return false; @@ -10226,7 +10226,7 @@ static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 m for (int n = 0; n < g.Viewports.Size; n++) { ImGuiViewportP* viewport = g.Viewports[n]; - if (!(viewport->Flags & ImGuiViewportFlags_NoInputs) && !viewport->PlatformWindowMinimized && viewport->GetRect().Contains(mouse_platform_pos)) + if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetRect().Contains(mouse_platform_pos)) if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount) best_candidate = viewport; } @@ -10245,7 +10245,13 @@ static void ImGui::UpdateViewportsNewFrame() const bool platform_funcs_available = viewport->PlatformWindowCreated; if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) - viewport->PlatformWindowMinimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); + { + bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); + if (minimized) + viewport->Flags |= ImGuiViewportFlags_Minimized; + else + viewport->Flags &= ~ImGuiViewportFlags_Minimized; + } } // Create/update main viewport with current platform position and size @@ -10255,7 +10261,7 @@ static void ImGui::UpdateViewportsNewFrame() ImVec2 main_viewport_platform_pos = ImVec2(0.0f, 0.0f); ImVec2 main_viewport_platform_size = g.IO.DisplaySize; if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) - main_viewport_platform_pos = main_viewport->PlatformWindowMinimized ? main_viewport->Pos : g.PlatformIO.Platform_GetWindowPos(main_viewport); + main_viewport_platform_pos = (main_viewport->Flags & ImGuiViewportFlags_Minimized) ? main_viewport->Pos : g.PlatformIO.Platform_GetWindowPos(main_viewport); AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_platform_pos, main_viewport_platform_size, ImGuiViewportFlags_CanHostOtherWindows); g.CurrentViewport = NULL; @@ -10293,7 +10299,7 @@ static void ImGui::UpdateViewportsNewFrame() { // Update Position and Size (from Platform Window to ImGui) if requested. // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. - if (!viewport->PlatformWindowMinimized && platform_funcs_available) + if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available) { if (viewport->PlatformRequestMove) viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); @@ -10437,6 +10443,7 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const viewport->Pos = pos; if (!viewport->PlatformRequestResize) viewport->Size = size; + viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags } else { @@ -10446,6 +10453,7 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const viewport->Idx = g.Viewports.Size; viewport->Pos = viewport->LastPos = pos; viewport->Size = size; + viewport->Flags = flags; UpdateViewportPlatformMonitor(viewport); g.Viewports.push_back(viewport); //IMGUI_DEBUG_LOG("Add Viewport %08X (%s)\n", id, window->Name); @@ -10464,7 +10472,6 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const } viewport->Window = window; - viewport->Flags = flags; viewport->LastFrameActive = g.FrameCount; IM_ASSERT(window == NULL || viewport->ID == window->ID); @@ -10721,9 +10728,11 @@ void ImGui::UpdatePlatformWindows() // // ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); // for (int i = 1; i < platform_io.Viewports.Size; i++) -// MyRenderFunction(platform_io.Viewports[i], my_args); +// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) +// MyRenderFunction(platform_io.Viewports[i], my_args); // for (int i = 1; i < platform_io.Viewports.Size; i++) -// MySwapBufferFunction(platform_io.Viewports[i], my_args); +// if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) +// MySwapBufferFunction(platform_io.Viewports[i], my_args); // void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg) { @@ -10732,12 +10741,16 @@ void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* render for (int i = 1; i < platform_io.Viewports.Size; i++) { ImGuiViewport* viewport = platform_io.Viewports[i]; + if (viewport->Flags & ImGuiViewportFlags_Minimized) + continue; if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg); if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg); } for (int i = 1; i < platform_io.Viewports.Size; i++) { ImGuiViewport* viewport = platform_io.Viewports[i]; + if (viewport->Flags & ImGuiViewportFlags_Minimized) + continue; if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg); if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg); } @@ -14072,7 +14085,7 @@ static void RenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewp ImVec2 scale = bb.GetSize() / viewport->Size; ImVec2 off = bb.Min - viewport->Pos * scale; - float alpha_mul = viewport->PlatformWindowMinimized ? 0.30f : 1.00f; + float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f; window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f)); for (int i = 0; i != g.Windows.Size; i++) { @@ -14287,7 +14300,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::BulletText("Flags: 0x%04X =%s%s%s%s%s%s", viewport->Flags, (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "", - (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", viewport->PlatformWindowMinimized ? ", PlatformWindowMinimized" : ""); + (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : ""); for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++) for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++) Funcs::NodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList"); diff --git a/imgui.h b/imgui.h index 0a08d6c8..263ab9e6 100644 --- a/imgui.h +++ b/imgui.h @@ -726,7 +726,7 @@ namespace ImGui IMGUI_API ImGuiPlatformIO& GetPlatformIO(); // platform/renderer functions, for back-end to setup + viewports list. IMGUI_API ImGuiViewport* GetMainViewport(); // main viewport. same as GetPlatformIO().MainViewport == GetPlatformIO().Viewports[0]. IMGUI_API void UpdatePlatformWindows(); // call in main loop. will call CreateWindow/ResizeWindow/etc. platform functions for each secondary viewport, and DestroyWindow for each inactive viewport. - IMGUI_API void RenderPlatformWindowsDefault(void* platform_arg = NULL, void* renderer_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport. may be reimplemented by user for custom rendering needs. + IMGUI_API void RenderPlatformWindowsDefault(void* platform_arg = NULL, void* renderer_arg = NULL); // call in main loop. will call RenderWindow/SwapBuffers platform functions for each secondary viewport which doesn't have the ImGuiViewportFlags_Minimized flag set. May be reimplemented by user for custom rendering needs. IMGUI_API void DestroyPlatformWindows(); // call DestroyWindow platform functions for all viewports. call from back-end Shutdown() if you need to close platform windows before imgui shutdown. otherwise will be called by DestroyContext(). IMGUI_API ImGuiViewport* FindViewportByID(ImGuiID id); // this is a helper for back-ends. IMGUI_API ImGuiViewport* FindViewportByPlatformHandle(void* platform_handle); // this is a helper for back-ends. the type platform_handle is decided by the back-end (e.g. HWND, MyWindow*, GLFWwindow* etc.) @@ -2347,7 +2347,8 @@ enum ImGuiViewportFlags_ ImGuiViewportFlags_NoFocusOnClick = 1 << 3, // Platform Window: Don't take focus when clicked on. ImGuiViewportFlags_NoInputs = 1 << 4, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it. ImGuiViewportFlags_NoRendererClear = 1 << 5, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). - ImGuiViewportFlags_TopMost = 1 << 6 // Platform Window: Display on top (for tooltips only) + ImGuiViewportFlags_TopMost = 1 << 6, // Platform Window: Display on top (for tooltips only) + ImGuiViewportFlags_Minimized = 1 << 7 // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. }; // The viewports created and managed by imgui. The role of the platform back-end is to create the platform/OS windows corresponding to each viewport. diff --git a/imgui_internal.h b/imgui_internal.h index 4c3ea3f7..39bcc057 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -756,7 +756,6 @@ struct ImGuiViewportP : public ImGuiViewport float LastAlpha; short PlatformMonitor; bool PlatformWindowCreated; - bool PlatformWindowMinimized; // When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport ImGuiWindow* Window; // Set when the viewport is owned by a window (and ImGuiViewportFlags_CanHostOtherWindows is NOT set) ImDrawList* DrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. ImDrawData DrawDataP; @@ -765,7 +764,7 @@ struct ImGuiViewportP : public ImGuiViewport ImVec2 LastPlatformSize; ImVec2 LastRendererSize; - ImGuiViewportP() { Idx = -1; LastFrameActive = LastFrameDrawLists[0] = LastFrameDrawLists[1] = LastFrontMostStampCount = -1; LastNameHash = 0; Alpha = LastAlpha = 1.0f; PlatformMonitor = -1; PlatformWindowCreated = PlatformWindowMinimized = false; Window = NULL; DrawLists[0] = DrawLists[1] = NULL; LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); } + ImGuiViewportP() { Idx = -1; LastFrameActive = LastFrameDrawLists[0] = LastFrameDrawLists[1] = LastFrontMostStampCount = -1; LastNameHash = 0; Alpha = LastAlpha = 1.0f; PlatformMonitor = -1; PlatformWindowCreated = false; Window = NULL; DrawLists[0] = DrawLists[1] = NULL; LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); } ~ImGuiViewportP() { if (DrawLists[0]) IM_DELETE(DrawLists[0]); if (DrawLists[1]) IM_DELETE(DrawLists[1]); } ImRect GetRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } ImVec2 GetCenter() const { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } From 994a92d79d65e71d12204b4a056c85dc84d58a61 Mon Sep 17 00:00:00 2001 From: David Amador Date: Mon, 22 Apr 2019 13:34:34 +0100 Subject: [PATCH 284/566] Added support to use controllers via SDL_GameController. (#2509) Updated sdl examples to use SDL_INIT_GAMECONTROLLER flag --- examples/example_sdl_opengl2/main.cpp | 2 +- examples/example_sdl_opengl3/main.cpp | 2 +- examples/example_sdl_vulkan/main.cpp | 2 +- examples/imgui_impl_sdl.cpp | 46 +++++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index aaaf3ee7..05adfbb7 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -16,7 +16,7 @@ int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) + if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 5b319a14..493b47ee 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -25,7 +25,7 @@ int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) + if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 58a49949..c9fa2671 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -319,7 +319,7 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) + if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return 1; diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 10f49493..f1d6a3ba 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -266,6 +266,49 @@ static void ImGui_ImplSDL2_UpdateMouseCursor() } } +static void ImGui_ImplSDL2_UpdateGamepads() +{ + ImGuiIO& io = ImGui::GetIO(); + memset(io.NavInputs, 0, sizeof(io.NavInputs)); + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + return; + + // Update gamepad inputs +#define MAP_BUTTON(NAV_NO, BUTTON_NO) { io.NavInputs[NAV_NO] = (SDL_GameControllerGetButton(game_controller, BUTTON_NO) == 1) ? 1.0f : 0.0f; } +#define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; } + + int axes_count = 0, buttons_count = 0; + SDL_GameController* game_controller = SDL_GameControllerOpen(0); + if(game_controller !=NULL) + { + const int thumb_dead_zone = 8000; + + MAP_BUTTON(ImGuiNavInput_Activate, SDL_CONTROLLER_BUTTON_A); // Cross / A + MAP_BUTTON(ImGuiNavInput_Cancel, SDL_CONTROLLER_BUTTON_B); // Circle / B + MAP_BUTTON(ImGuiNavInput_Menu, SDL_CONTROLLER_BUTTON_X); // Square / X + MAP_BUTTON(ImGuiNavInput_Input, SDL_CONTROLLER_BUTTON_Y); // Triangle / Y + MAP_BUTTON(ImGuiNavInput_DpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); // D-Pad Left + MAP_BUTTON(ImGuiNavInput_DpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); // D-Pad Right + MAP_BUTTON(ImGuiNavInput_DpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); // D-Pad Up + MAP_BUTTON(ImGuiNavInput_DpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); // D-Pad Down + MAP_BUTTON(ImGuiNavInput_FocusPrev, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB + MAP_BUTTON(ImGuiNavInput_FocusNext, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB + MAP_BUTTON(ImGuiNavInput_TweakSlow, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB + MAP_BUTTON(ImGuiNavInput_TweakFast, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB + MAP_ANALOG(ImGuiNavInput_LStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768); + MAP_ANALOG(ImGuiNavInput_LStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767); + MAP_ANALOG(ImGuiNavInput_LStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32767); + MAP_ANALOG(ImGuiNavInput_LStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767); +#undef MAP_BUTTON +#undef MAP_ANALOG + } + + if (axes_count > 0 && buttons_count > 0) + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + else + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; +} + void ImGui_ImplSDL2_NewFrame(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); @@ -288,4 +331,7 @@ void ImGui_ImplSDL2_NewFrame(SDL_Window* window) ImGui_ImplSDL2_UpdateMousePosAndButtons(); ImGui_ImplSDL2_UpdateMouseCursor(); + + // Gamepad navigation mapping + ImGui_ImplSDL2_UpdateGamepads(); } From 6789ea3482d6d5f1a1dc353758f7c512f6337b78 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Apr 2019 12:26:14 +0200 Subject: [PATCH 285/566] Examples: SDL: Gamepad support minor amend. Fixes ImGuiBackendFlags_HasGamepad not being set. Enable in Emscripten demo. Tweaks. (#2509, #2484). --- docs/CHANGELOG.txt | 3 +- examples/example_emscripten/main.cpp | 3 +- examples/example_sdl_opengl2/main.cpp | 3 +- examples/example_sdl_opengl3/main.cpp | 3 +- examples/example_sdl_vulkan/main.cpp | 3 +- examples/imgui_impl_glfw.cpp | 2 +- examples/imgui_impl_sdl.cpp | 67 +++++++++++++-------------- examples/imgui_impl_sdl.h | 2 +- examples/imgui_impl_win32.cpp | 2 +- 9 files changed, 46 insertions(+), 42 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 39f0da96..f982ff08 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,7 @@ Other Changes: - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. - Examples: Vulkan: Added ImGui_ImplVulkan_SetMinImageCount() to change min image count at runtime. (#2071) [@nathanvoglsam] +- Examples: SDL: Added support for SDL_GameController gamepads (enable with ImGuiConfigFlags_NavEnableGamepad). (#2509) [@DJLink] - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: DirectX10/11/12, Allegro, Marmalade: Render functions early out when display size is zero (minimized). (#2496) - Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] @@ -217,7 +218,7 @@ Other Changes: - Examples: Win32: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. (#1951, #2087, #2156, #2232) [many people] - Examples: SDL: Using the SDL_WINDOW_ALLOW_HIGHDPI flag. (#2306, #1676) [@rasky] -- Examples: Win32: Added support for XInput games (if ImGuiConfigFlags_NavEnableGamepad is enabled). +- Examples: Win32: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is enabled). - Examples: Win32: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. (#2264) - Examples: DirectX9: Explicitly disable fog (D3DRS_FOGENABLE) before drawing in case user state has it set. (#2288, #2230) - Examples: OpenGL2: Added #define GL_SILENCE_DEPRECATION to cope with newer XCode warnings. diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index fc7017d5..574e6e24 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -25,7 +25,7 @@ void main_loop(void*); int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; @@ -62,6 +62,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index 05adfbb7..ddefd096 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -16,7 +16,7 @@ int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_GAMECONTROLLER) != 0) + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; @@ -38,6 +38,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 493b47ee..08f1bb00 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -25,7 +25,7 @@ int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_GAMECONTROLLER) != 0) + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; @@ -78,6 +78,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index c9fa2671..2d49dda4 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -319,7 +319,7 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) int main(int, char**) { // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_GAMECONTROLLER) != 0) + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return 1; @@ -356,6 +356,7 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 0ed40cde..0ed9f7d2 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -325,6 +325,6 @@ void ImGui_ImplGlfw_NewFrame() ImGui_ImplGlfw_UpdateMousePosAndButtons(); ImGui_ImplGlfw_UpdateMouseCursor(); - // Gamepad navigation mapping + // Update game controllers (if enabled and available) ImGui_ImplGlfw_UpdateGamepads(); } diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index f1d6a3ba..a9ff5cd8 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -7,9 +7,9 @@ // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Clipboard support. // [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE). +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // Missing features: // [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME. -// [ ] Platform: Gamepad support (need to use SDL_GameController API to fill the io.NavInputs[] value when ImGuiConfigFlags_NavEnableGamepad is set). // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application). // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. @@ -272,41 +273,39 @@ static void ImGui_ImplSDL2_UpdateGamepads() memset(io.NavInputs, 0, sizeof(io.NavInputs)); if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) return; - - // Update gamepad inputs -#define MAP_BUTTON(NAV_NO, BUTTON_NO) { io.NavInputs[NAV_NO] = (SDL_GameControllerGetButton(game_controller, BUTTON_NO) == 1) ? 1.0f : 0.0f; } -#define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; } - - int axes_count = 0, buttons_count = 0; + + // Get gamepad SDL_GameController* game_controller = SDL_GameControllerOpen(0); - if(game_controller !=NULL) + if (!game_controller) { - const int thumb_dead_zone = 8000; - - MAP_BUTTON(ImGuiNavInput_Activate, SDL_CONTROLLER_BUTTON_A); // Cross / A - MAP_BUTTON(ImGuiNavInput_Cancel, SDL_CONTROLLER_BUTTON_B); // Circle / B - MAP_BUTTON(ImGuiNavInput_Menu, SDL_CONTROLLER_BUTTON_X); // Square / X - MAP_BUTTON(ImGuiNavInput_Input, SDL_CONTROLLER_BUTTON_Y); // Triangle / Y - MAP_BUTTON(ImGuiNavInput_DpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); // D-Pad Left - MAP_BUTTON(ImGuiNavInput_DpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); // D-Pad Right - MAP_BUTTON(ImGuiNavInput_DpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); // D-Pad Up - MAP_BUTTON(ImGuiNavInput_DpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); // D-Pad Down - MAP_BUTTON(ImGuiNavInput_FocusPrev, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB - MAP_BUTTON(ImGuiNavInput_FocusNext, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB - MAP_BUTTON(ImGuiNavInput_TweakSlow, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB - MAP_BUTTON(ImGuiNavInput_TweakFast, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB - MAP_ANALOG(ImGuiNavInput_LStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768); - MAP_ANALOG(ImGuiNavInput_LStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767); - MAP_ANALOG(ImGuiNavInput_LStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32767); - MAP_ANALOG(ImGuiNavInput_LStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767); -#undef MAP_BUTTON -#undef MAP_ANALOG - } - - if (axes_count > 0 && buttons_count > 0) - io.BackendFlags |= ImGuiBackendFlags_HasGamepad; - else io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; + return; + } + + // Update gamepad inputs + #define MAP_BUTTON(NAV_NO, BUTTON_NO) { io.NavInputs[NAV_NO] = (SDL_GameControllerGetButton(game_controller, BUTTON_NO) != 0) ? 1.0f : 0.0f; } + #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; } + const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value. + MAP_BUTTON(ImGuiNavInput_Activate, SDL_CONTROLLER_BUTTON_A); // Cross / A + MAP_BUTTON(ImGuiNavInput_Cancel, SDL_CONTROLLER_BUTTON_B); // Circle / B + MAP_BUTTON(ImGuiNavInput_Menu, SDL_CONTROLLER_BUTTON_X); // Square / X + MAP_BUTTON(ImGuiNavInput_Input, SDL_CONTROLLER_BUTTON_Y); // Triangle / Y + MAP_BUTTON(ImGuiNavInput_DpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); // D-Pad Left + MAP_BUTTON(ImGuiNavInput_DpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); // D-Pad Right + MAP_BUTTON(ImGuiNavInput_DpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); // D-Pad Up + MAP_BUTTON(ImGuiNavInput_DpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); // D-Pad Down + MAP_BUTTON(ImGuiNavInput_FocusPrev, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB + MAP_BUTTON(ImGuiNavInput_FocusNext, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB + MAP_BUTTON(ImGuiNavInput_TweakSlow, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB + MAP_BUTTON(ImGuiNavInput_TweakFast, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB + MAP_ANALOG(ImGuiNavInput_LStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768); + MAP_ANALOG(ImGuiNavInput_LStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767); + MAP_ANALOG(ImGuiNavInput_LStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32767); + MAP_ANALOG(ImGuiNavInput_LStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767); + + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + #undef MAP_BUTTON + #undef MAP_ANALOG } void ImGui_ImplSDL2_NewFrame(SDL_Window* window) @@ -332,6 +331,6 @@ void ImGui_ImplSDL2_NewFrame(SDL_Window* window) ImGui_ImplSDL2_UpdateMousePosAndButtons(); ImGui_ImplSDL2_UpdateMouseCursor(); - // Gamepad navigation mapping + // Update game controllers (if enabled and available) ImGui_ImplSDL2_UpdateGamepads(); } diff --git a/examples/imgui_impl_sdl.h b/examples/imgui_impl_sdl.h index ec8190cc..39cc98e5 100644 --- a/examples/imgui_impl_sdl.h +++ b/examples/imgui_impl_sdl.h @@ -6,9 +6,9 @@ // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Clipboard support. // [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE). +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // Missing features: // [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME. -// [ ] Platform: Gamepad support (need to use SDL_GameController API to fill the io.NavInputs[] value when ImGuiConfigFlags_NavEnableGamepad is set). // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 524923c3..59cf88ce 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -230,7 +230,7 @@ void ImGui_ImplWin32_NewFrame() ImGui_ImplWin32_UpdateMouseCursor(); } - // Update game controllers (if available) + // Update game controllers (if enabled and available) ImGui_ImplWin32_UpdateGamepads(); } From 6db0766564600bfb94c2cf0bb0b676c2929a92fc Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 24 Apr 2019 17:04:20 +0200 Subject: [PATCH 286/566] Misc comments, internal renaming, added disable indentation option to Columns demo section. --- docs/TODO.txt | 1 + imgui.cpp | 7 ++++--- imgui.h | 2 +- imgui_demo.cpp | 15 ++++++++++++++- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 6 +++--- 6 files changed, 25 insertions(+), 10 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 279342ca..57845d36 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -207,6 +207,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) - tree node: tweak color scheme to distinguish headers from selected tree node (#581) - tree node: leaf/non-leaf highlight mismatch. + - tree node: _NoIndentOnOpen flag? would require to store a per-depth bit mask to store info for pop (or whatever is cheaper) - settings: write more decent code to allow saving/loading new fields: columns, selected tree nodes? - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file (#437) diff --git a/imgui.cpp b/imgui.cpp index 5d705e4e..7a169bf8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -393,8 +393,9 @@ CODE - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). - 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). - old binding will still work as is, however prefer using the separated bindings as they will be updated to be multi-viewport conformant. + old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports. when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call. + in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details. - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. @@ -5444,7 +5445,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.TextWrapPosStack.resize(0); window->DC.CurrentColumns = NULL; window->DC.TreeDepth = 0; - window->DC.TreeDepthMayJumpToParentOnPop = 0x00; + window->DC.TreeStoreMayJumpToParentOnPop = 0x00; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); @@ -6396,7 +6397,7 @@ void ImGui::SetNextWindowBgAlpha(float alpha) g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) } -// FIXME: This is in window space (not screen space!) +// FIXME: This is in window space (not screen space!). We should try to obsolete all those functions. ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui.h b/imgui.h index 37640640..d10df2f0 100644 --- a/imgui.h +++ b/imgui.h @@ -782,7 +782,7 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding(). - //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed + //ImGuiTreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 12, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2233eab7..695fd869 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2367,6 +2367,13 @@ static void ShowDemoWindowColumns() ImGui::PushID("Columns"); + static bool disable_indent = false; + ImGui::Checkbox("Disable tree indentation", &disable_indent); + ImGui::SameLine(); + HelpMarker("Disable the indenting of tree nodes so demo columns can use the full window width."); + if (disable_indent) + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f); + // Basic columns if (ImGui::TreeNode("Basic")) { @@ -2472,7 +2479,10 @@ static void ShowDemoWindowColumns() if (h_borders && ImGui::GetColumnIndex() == 0) ImGui::Separator(); ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); - ImGui::Text("Width %.2f\nOffset %.2f", ImGui::GetColumnWidth(), ImGui::GetColumnOffset()); + ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); + ImGui::Text("Long text that is likely to clip"); + ImGui::Button("Button", ImVec2(-1.0f, 0.0f)); ImGui::NextColumn(); } ImGui::Columns(1); @@ -2540,6 +2550,9 @@ static void ShowDemoWindowColumns() ImGui::Separator(); ImGui::TreePop(); } + + if (disable_indent) + ImGui::PopStyleVar(); ImGui::PopID(); } diff --git a/imgui_internal.h b/imgui_internal.h index b0a26a95..4d8faa05 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1123,7 +1123,7 @@ struct IMGUI_API ImGuiWindowTempData ImVec2 PrevLineSize; float PrevLineTextBaseOffset; int TreeDepth; - ImU32 TreeDepthMayJumpToParentOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31 + ImU32 TreeStoreMayJumpToParentOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary. ImGuiID LastItemId; ImGuiItemStatusFlags LastItemStatusFlags; ImRect LastItemRect; // Interaction rect @@ -1165,7 +1165,7 @@ struct IMGUI_API ImGuiWindowTempData CurrentLineSize = PrevLineSize = ImVec2(0.0f, 0.0f); CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; TreeDepth = 0; - TreeDepthMayJumpToParentOnPop = 0x00; + TreeStoreMayJumpToParentOnPop = 0x00; LastItemId = 0; LastItemStatusFlags = 0; LastItemRect = LastItemDisplayRect = ImRect(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 82d792d6..42afb20e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5073,7 +5073,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero. if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) - window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth); + window->DC.TreeStoreMayJumpToParentOnPop |= (1 << window->DC.TreeDepth); bool item_add = ItemAdd(interact_bb, id); window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; @@ -5223,12 +5223,12 @@ void ImGui::TreePop() window->DC.TreeDepth--; if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) - if (g.NavIdIsAlive && (window->DC.TreeDepthMayJumpToParentOnPop & (1 << window->DC.TreeDepth))) + if (g.NavIdIsAlive && (window->DC.TreeStoreMayJumpToParentOnPop & (1 << window->DC.TreeDepth))) { SetNavID(window->IDStack.back(), g.NavLayer); NavMoveRequestCancel(); } - window->DC.TreeDepthMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1; + window->DC.TreeStoreMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1; IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. PopID(); From 16b18b265ee5c9bdcc8ce7ce56a296fe76d6d602 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Apr 2019 11:34:07 +0200 Subject: [PATCH 287/566] MenuItem, BeginMenu: Fix undesirable tall frames in horizontal layout context, which would be visible when trying to use rounded selectable/menus. PushStyleVar: Added comments in the assert message. Minor tweaks. --- imgui.cpp | 4 ++-- imgui_widgets.cpp | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7a169bf8..888d3f49 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6006,7 +6006,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) *pvar = val; return; } - IM_ASSERT(0); // Called function with wrong-type? Variable is not a float. + IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!"); } void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) @@ -6020,7 +6020,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) *pvar = val; return; } - IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2. + IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!"); } void ImGui::PopStyleVar(int count) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 42afb20e..708bf0c3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5405,7 +5405,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl bb.Max.x -= (GetContentRegionMax().x - max_x); } - if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); RenderTextClipped(bb_inner.Min, bb_inner.Max, label, NULL, &label_size, style.SelectableTextAlign, &bb); if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); @@ -5877,10 +5877,11 @@ void ImGui::EndMenuBar() { // To do so we claim focus back, restore NavId and then process the movement request for yet another frame. // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost) - IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check + const ImGuiNavLayer layer = ImGuiNavLayer_Menu; + IM_ASSERT(window->DC.NavLayerActiveMaskNext & (1 << layer)); // Sanity check FocusWindow(window); - SetNavIDWithRectRel(window->NavLastIds[1], 1, window->NavRectRel[1]); - g.NavLayer = ImGuiNavLayer_Menu; + SetNavIDWithRectRel(window->NavLastIds[layer], layer, window->NavRectRel[layer]); + g.NavLayer = layer; g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; NavMoveRequestCancel(); @@ -5930,7 +5931,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() popup_pos = ImVec2(pos.x - 1.0f - (float)(int)(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight()); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); - PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); float w = label_size.x; pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); PopStyleVar(); @@ -6074,7 +6075,7 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, boo // Note that in this situation we render neither the shortcut neither the selected tick mark float w = label_size.x; window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); - PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); pressed = Selectable(label, false, flags, ImVec2(w, 0.0f)); PopStyleVar(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). From 4dc4ace8644923151364fc659f0aba751667ed5e Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Apr 2019 11:46:55 +0200 Subject: [PATCH 288/566] Window: Fixed window with the AlwaysAutoResize flag unnecessarily extending their hovering boundaries by a few pixels (this is used to facilitate resizing from borders when available for a given window). One of the noticeable minor side effect was that navigating menus would have had a tendency to disable highlight from parent menu items earlier than necessary while approaching the child menu. + Changelog fixed unfinished sentence and tweaks, --- docs/CHANGELOG.txt | 21 +++++++++++++-------- imgui.cpp | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f982ff08..97871ceb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,31 +46,36 @@ Other Changes: - InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) - InputText: Fixed ImGuiInputTextFlags_AllowTabInput leading to two tabs characters being inserted if the back-end provided both Key and Character input. (#2467, #1336) -- Added SetNextItemWidth() helper to avoid using PushItemWidth/PopItemWidth() for single items. +- Layout: Added SetNextItemWidth() helper to avoid using PushItemWidth/PopItemWidth() for single items. Note that SetNextItemWidth() currently only affect the same subset of items as PushItemWidth(), - generally referred to as the large framed+labeled items. - Because the new SetNextItemWidth() function is explicit + generally referred to as the large framed+labeled items. Because the new SetNextItemWidth() + function is explicit we may later extend its effect to more items. +- Layout: Fixed PushItemWidth(-width) for right-side alignment laying out some items (button, listbox, etc.) + with negative sizes if the 'width' argument was smaller than the available width at the time of item + submission. +- Window: Fixed window with the AlwaysAutoResize flag unnecessarily extending their hovering boundaries + by a few pixels (this is used to facilitate resizing from borders when available for a given window). + One of the noticeable minor side effect was that navigating menus would have had a tendency to disable + highlight from parent menu items earlier than necessary while approaching the child menu. +- Window: Close button is horizontally aligned with style.FramePadding.x. - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] - PlotLines, PlotHistogram: Ignore NaN values when calculating min/max bounds. (#2485) -- Window: Window close button is horizontally aligned with style.FramePadding.x. - Columns: Fixed boundary of clipping being off by 1 pixel within the left column. - Combo, Slider, Scrollbar: Improve rendering in situation when there's only a few pixels available (<3 pixels). -- Misc: Fixed PushItemWidth(-width) (for right-side alignment) laying out certain items (button, listbox, etc.) - with negative sizes if the 'width' argument was smaller than the available width at the time of item submission, - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) -- Examples: Emscripten: Added Emscripten+SDL+GLES2 example. (#2494, #2492, #2351, #336) [@nicolasnoble] +- Examples: Emscripten: Added Emscripten+SDL+GLES2 example. (#2494, #2492, #2351, #336) [@nicolasnoble, @redblobgames] +- Examples: SDL: Added support for SDL_GameController gamepads (enable with ImGuiConfigFlags_NavEnableGamepad). (#2509) [@DJLink] - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Fixed in-flight buffers issues when using multi-viewports. (#2461, #2348, #2378, #2097) - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). - Examples: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. - Examples: Vulkan: Added ImGui_ImplVulkan_SetMinImageCount() to change min image count at runtime. (#2071) [@nathanvoglsam] -- Examples: SDL: Added support for SDL_GameController gamepads (enable with ImGuiConfigFlags_NavEnableGamepad). (#2509) [@DJLink] - Examples: DirectX9: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). (#2454) - Examples: DirectX10/11/12, Allegro, Marmalade: Render functions early out when display size is zero (minimized). (#2496) - Examples: GLUT: Fixed existing FreeGLUT example to work with regular GLUT. (#2465) [@andrewwillmott] diff --git a/imgui.cpp b/imgui.cpp index 888d3f49..c253a1c6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4067,7 +4067,7 @@ static void FindHoveredWindow() // Using the clipped AABB, a child window will typically be clipped by its parent (not always) ImRect bb(window->OuterRectClipped); - if ((window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_NoResize)) + if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) bb.Expand(padding_regular); else bb.Expand(padding_for_resize_from_edges); From 1ca6e5b59faa72ed487e5fe17d2923c15955b8b8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Apr 2019 12:01:01 +0200 Subject: [PATCH 289/566] Examples: Glut: Added note about missing cursor support. (#2375, #2465) --- examples/imgui_impl_glut.cpp | 1 + examples/imgui_impl_glut.h | 1 + 2 files changed, 2 insertions(+) diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index d8bd7498..546a7b85 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -6,6 +6,7 @@ // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I +// [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. diff --git a/examples/imgui_impl_glut.h b/examples/imgui_impl_glut.h index 8fde9bab..89be9993 100644 --- a/examples/imgui_impl_glut.h +++ b/examples/imgui_impl_glut.h @@ -6,6 +6,7 @@ // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I +// [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. From 59a3f0476d0a4e6d5c294c5f2389d187c76b2c7c Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Apr 2019 15:21:22 +0200 Subject: [PATCH 290/566] Internals: Using more explicit PushOverrideID() helper + renamed equivalent internal tree helper. --- imgui.cpp | 7 +++++++ imgui_internal.h | 3 ++- imgui_widgets.cpp | 18 ++++++++++-------- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c253a1c6..6eeed76b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6682,6 +6682,13 @@ void ImGui::PushID(int int_id) window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id)); } +// Push a given id value ignoring the ID stack as a seed. +void ImGui::PushOverrideID(ImGuiID id) +{ + ImGuiWindow* window = GImGui->CurrentWindow; + window->IDStack.push_back(id); +} + void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui_internal.h b/imgui_internal.h index 4d8faa05..7aeaf679 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1431,6 +1431,7 @@ namespace ImGui IMGUI_API void SetHoveredID(ImGuiID id); IMGUI_API void KeepAliveID(ImGuiID id); IMGUI_API void MarkItemEdited(ImGuiID id); + IMGUI_API void PushOverrideID(ImGuiID id); // Basic Helpers for widget code IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f); @@ -1546,7 +1547,7 @@ namespace ImGui IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f); IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging - IMGUI_API void TreePushRawID(ImGuiID id); + IMGUI_API void TreePushOverrideID(ImGuiID id); // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 708bf0c3..950c8cf9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5082,7 +5082,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (!item_add) { if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) - TreePushRawID(id); + TreePushOverrideID(id); IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open; } @@ -5186,7 +5186,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l } if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) - TreePushRawID(id); + TreePushOverrideID(id); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open; } @@ -5207,7 +5207,7 @@ void ImGui::TreePush(const void* ptr_id) PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); } -void ImGui::TreePushRawID(ImGuiID id) +void ImGui::TreePushOverrideID(ImGuiID id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); @@ -6211,7 +6211,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG return false; if ((flags & ImGuiTabBarFlags_DockNode) == 0) - window->IDStack.push_back(tab_bar->ID); + PushOverrideID(tab_bar->ID); // Add to stack g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar)); @@ -6663,7 +6663,8 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags) { ImGuiContext& g = *GImGui; - if (g.CurrentWindow->SkipItems) + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) return false; ImGuiTabBar* tab_bar = g.CurrentTabBar; @@ -6676,7 +6677,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; - g.CurrentWindow->IDStack.push_back(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) + PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) } return ret; } @@ -6684,7 +6685,8 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f void ImGui::EndTabItem() { ImGuiContext& g = *GImGui; - if (g.CurrentWindow->SkipItems) + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) return; ImGuiTabBar* tab_bar = g.CurrentTabBar; @@ -6696,7 +6698,7 @@ void ImGui::EndTabItem() IM_ASSERT(tab_bar->LastTabItemIdx >= 0); ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) - g.CurrentWindow->IDStack.pop_back(); + window->IDStack.pop_back(); } bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags) From 0ca1675ff9d079fb67a377399ceea6643b4667c8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Apr 2019 15:46:10 +0200 Subject: [PATCH 291/566] Internals: TempInputText: Rename InputScalarAsWidgetReplacement() -> TempInputTextScalar(), ScalarAsInputTextId -> TempInputTextId, small tidying up in affected functions. --- docs/TODO.txt | 2 +- imgui.cpp | 4 ++-- imgui_internal.h | 7 ++++--- imgui_widgets.cpp | 40 +++++++++++++++++++++------------------- 4 files changed, 28 insertions(+), 25 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 57845d36..9e64b163 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -143,7 +143,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - image button: not taking an explicit id can be problematic. (#2464, #1390) - - slider/drag: ctrl+click when format doesn't include a % character.. disable? display underlying value in default format? (see InputScalarAsWidgetReplacement) + - slider/drag: ctrl+click when format doesn't include a % character.. disable? display underlying value in default format? (see TempInputTextScalar) - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). (#1946) - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. diff --git a/imgui.cpp b/imgui.cpp index 6eeed76b..2dbc4207 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3515,8 +3515,8 @@ void ImGui::NewFrame() g.ActiveIdIsAlive = 0; g.ActiveIdPreviousFrameIsAlive = false; g.ActiveIdIsJustActivated = false; - if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId) - g.ScalarAsInputTextId = 0; + if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId) + g.TempInputTextId = 0; // Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; diff --git a/imgui_internal.h b/imgui_internal.h index 7aeaf679..0cf8f03b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -938,7 +938,7 @@ struct ImGuiContext // Widget state ImGuiInputTextState InputTextState; ImFont InputTextPasswordFont; - ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. + ImGuiID TempInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets ImVec4 ColorPickerRef; bool DragCurrentAccumDirty; @@ -1075,7 +1075,7 @@ struct ImGuiContext CurrentTabBar = NULL; - ScalarAsInputTextId = 0; + TempInputTextId = 0; ColorEditOptions = ImGuiColorEditFlags__OptionsDefault; DragCurrentAccumDirty = false; DragCurrentAccum = 0.0f; @@ -1559,7 +1559,8 @@ namespace ImGui // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format); + IMGUI_API bool TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format); + inline bool TempInputTextIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputTextId == id); } // Color IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 950c8cf9..46eaf7f3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2000,9 +2000,10 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Drag turns it into an input box - bool start_text_input = false; + bool temp_input_is_active = TempInputTextIsActive(id); + bool temp_input_start = false; const bool focus_requested = FocusableItemRegister(window, id); - if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) + if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && !temp_input_is_active)) { SetActiveID(id, window); SetFocusID(id, window); @@ -2010,15 +2011,15 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); if (focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) { - start_text_input = true; - g.ScalarAsInputTextId = 0; + temp_input_start = true; + g.TempInputTextId = 0; } } - if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + if (temp_input_is_active || temp_input_start) { window->DC.CursorPos = frame_bb.Min; FocusableItemUnregister(window); - return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); + return TempInputTextScalar(frame_bb, id, label, data_type, v, format); } // Actual drag behavior @@ -2442,10 +2443,11 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Slider turns it into an input box - bool start_text_input = false; + bool temp_input_is_active = TempInputTextIsActive(id); + bool temp_input_start = false; const bool focus_requested = FocusableItemRegister(window, id); const bool hovered = ItemHoverable(frame_bb, id); - if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) + if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && !temp_input_is_active)) { SetActiveID(id, window); SetFocusID(id, window); @@ -2453,15 +2455,15 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); if (focus_requested || g.IO.KeyCtrl || g.NavInputId == id) { - start_text_input = true; - g.ScalarAsInputTextId = 0; + temp_input_start = true; + g.TempInputTextId = 0; } } - if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + if (temp_input_is_active || temp_input_start) { window->DC.CursorPos = frame_bb.Min; FocusableItemUnregister(window); - return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); + return TempInputTextScalar(frame_bb, id, label, data_type, v, format); } // Draw frame @@ -2648,7 +2650,7 @@ bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, // - ImParseFormatFindEnd() [Internal] // - ImParseFormatTrimDecorations() [Internal] // - ImParseFormatPrecision() [Internal] -// - InputScalarAsWidgetReplacement() [Internal] +// - TempInputTextScalar() [Internal] // - InputScalar() // - InputScalarN() // - InputFloat() @@ -2734,16 +2736,16 @@ int ImParseFormatPrecision(const char* fmt, int default_precision) return (precision == INT_MAX) ? default_precision : precision; } -// Create text input in place of an active drag/slider (used when doing a CTRL+Click on drag/slider widgets) +// Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets) // FIXME: Facilitate using this in variety of other situations. -bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format) +bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format) { IM_UNUSED(id); ImGuiContext& g = *GImGui; - // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id. + // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. // We clear ActiveID on the first frame to allow the InputText() taking it back. - if (g.ScalarAsInputTextId == 0) + if (g.TempInputTextId == 0) ClearActiveID(); char fmt_buf[32]; @@ -2753,11 +2755,11 @@ bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const c ImStrTrimBlanks(data_buf); ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); bool value_changed = InputTextEx(label, NULL, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags); - if (g.ScalarAsInputTextId == 0) + if (g.TempInputTextId == 0) { // First frame we started displaying the InputText widget, we expect it to take the active id. IM_ASSERT(g.ActiveId == id); - g.ScalarAsInputTextId = g.ActiveId; + g.TempInputTextId = g.ActiveId; } if (value_changed) return DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, NULL); From dd15b44230c7b9cad7609cedf3884aec579860dc Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Apr 2019 16:04:45 +0200 Subject: [PATCH 292/566] Internals: TempInputText: Tidying up DragScalar / SliderScalar / TempInputTextScalar. --- imgui_widgets.cpp | 73 +++++++++++++++++++++++------------------------ 1 file changed, 36 insertions(+), 37 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 46eaf7f3..9b212545 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1989,8 +1989,6 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa if (!ItemAdd(total_bb, id, &frame_bb)) return false; - const bool hovered = ItemHoverable(frame_bb, id); - // Default format string when passing NULL // Patch old "%.0f" format string to use "%d", read function comments for more details. IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); @@ -2000,38 +1998,38 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Drag turns it into an input box + const bool hovered = ItemHoverable(frame_bb, id); bool temp_input_is_active = TempInputTextIsActive(id); bool temp_input_start = false; - const bool focus_requested = FocusableItemRegister(window, id); - if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && !temp_input_is_active)) + if (!temp_input_is_active) { - SetActiveID(id, window); - SetFocusID(id, window); - FocusWindow(window); - g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); - if (focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) + const bool focus_requested = FocusableItemRegister(window, id); + if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || g.NavInputId == id) { - temp_input_start = true; - g.TempInputTextId = 0; + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + if (focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) + { + temp_input_start = true; + FocusableItemUnregister(window); + } } } if (temp_input_is_active || temp_input_start) - { - window->DC.CursorPos = frame_bb.Min; - FocusableItemUnregister(window); return TempInputTextScalar(frame_bb, id, label, data_type, v, format); - } - - // Actual drag behavior - const bool value_changed = DragBehavior(id, data_type, v, v_speed, v_min, v_max, format, power, ImGuiDragFlags_None); - if (value_changed) - MarkItemEdited(id); // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); + // Drag behavior + const bool value_changed = DragBehavior(id, data_type, v, v_speed, v_min, v_max, format, power, ImGuiDragFlags_None); + if (value_changed) + MarkItemEdited(id); + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format); @@ -2443,28 +2441,27 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Slider turns it into an input box + const bool hovered = ItemHoverable(frame_bb, id); bool temp_input_is_active = TempInputTextIsActive(id); bool temp_input_start = false; - const bool focus_requested = FocusableItemRegister(window, id); - const bool hovered = ItemHoverable(frame_bb, id); - if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && !temp_input_is_active)) + if (!temp_input_is_active) { - SetActiveID(id, window); - SetFocusID(id, window); - FocusWindow(window); - g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); - if (focus_requested || g.IO.KeyCtrl || g.NavInputId == id) + const bool focus_requested = FocusableItemRegister(window, id); + if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id) { - temp_input_start = true; - g.TempInputTextId = 0; + SetActiveID(id, window); + SetFocusID(id, window); + FocusWindow(window); + g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); + if (focus_requested || g.IO.KeyCtrl || g.NavInputId == id) + { + temp_input_start = true; + FocusableItemUnregister(window); + } } } if (temp_input_is_active || temp_input_start) - { - window->DC.CursorPos = frame_bb.Min; - FocusableItemUnregister(window); return TempInputTextScalar(frame_bb, id, label, data_type, v, format); - } // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -2740,12 +2737,12 @@ int ImParseFormatPrecision(const char* fmt, int default_precision) // FIXME: Facilitate using this in variety of other situations. bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format) { - IM_UNUSED(id); ImGuiContext& g = *GImGui; // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. // We clear ActiveID on the first frame to allow the InputText() taking it back. - if (g.TempInputTextId == 0) + const bool init = (g.TempInputTextId != id); + if (init) ClearActiveID(); char fmt_buf[32]; @@ -2753,9 +2750,11 @@ bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf)); DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, data_ptr, format); ImStrTrimBlanks(data_buf); + + g.CurrentWindow->DC.CursorPos = bb.Min; ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); bool value_changed = InputTextEx(label, NULL, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags); - if (g.TempInputTextId == 0) + if (init) { // First frame we started displaying the InputText widget, we expect it to take the active id. IM_ASSERT(g.ActiveId == id); From 56c3aaf6bd06bbde95138b9dad61e1fa33ccfde8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Apr 2019 16:17:48 +0200 Subject: [PATCH 293/566] Nav: Fixed Drag/Slider functions going into text input mode when keyboard CTRL is held while pressing NavActivate. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 11 +++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 97871ceb..dbe87c97 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,7 @@ Other Changes: - PlotLines, PlotHistogram: Ignore NaN values when calculating min/max bounds. (#2485) - Columns: Fixed boundary of clipping being off by 1 pixel within the left column. - Combo, Slider, Scrollbar: Improve rendering in situation when there's only a few pixels available (<3 pixels). +- Nav: Fixed Drag/Slider functions going into text input mode when keyboard CTRL is held while pressing NavActivate. - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9b212545..bebbf3d8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2004,13 +2004,15 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa if (!temp_input_is_active) { const bool focus_requested = FocusableItemRegister(window, id); - if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || g.NavInputId == id) + const bool clicked = (hovered && g.IO.MouseClicked[0]); + const bool double_clicked = (hovered && g.IO.MouseDoubleClicked[0]); + if (focus_requested || clicked || double_clicked || g.NavActivateId == id || g.NavInputId == id) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); - if (focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) + if (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id) { temp_input_start = true; FocusableItemUnregister(window); @@ -2447,13 +2449,14 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co if (!temp_input_is_active) { const bool focus_requested = FocusableItemRegister(window, id); - if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id) + const bool clicked = (hovered && g.IO.MouseClicked[0]); + if (focus_requested || clicked || g.NavActivateId == id || g.NavInputId == id) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); - if (focus_requested || g.IO.KeyCtrl || g.NavInputId == id) + if (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id) { temp_input_start = true; FocusableItemUnregister(window); From a649d904d7c6274584a38a18702c340c1ecdf567 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 26 Apr 2019 00:28:28 +0200 Subject: [PATCH 294/566] Examples: Emscripten: Fixed not enabling Docking and Nav by default. (#2494) --- examples/example_emscripten/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index 574e6e24..90055718 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -61,8 +61,9 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. From c5d83d8af205618d950527625838377a9853b3b8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 26 Apr 2019 22:25:30 +0200 Subject: [PATCH 295/566] Separator: Declare its thickness (1.0f) to the layout, making items around separator more symmetrical. --- docs/CHANGELOG.txt | 3 ++- imgui_widgets.cpp | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dbe87c97..c51fcc0e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,7 +62,8 @@ Other Changes: - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] - PlotLines, PlotHistogram: Ignore NaN values when calculating min/max bounds. (#2485) -- Columns: Fixed boundary of clipping being off by 1 pixel within the left column. +- Columns: Fixed boundary of clipping being off by 1 pixel within the left column. (#125) +- Separator: Declare its thickness (1.0f) to the layout, making items around separator more symmetrical. - Combo, Slider, Scrollbar: Improve rendering in situation when there's only a few pixels available (<3 pixels). - Nav: Fixed Drag/Slider functions going into text input mode when keyboard CTRL is held while pressing NavActivate. - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bebbf3d8..82bef8fb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1203,7 +1203,7 @@ void ImGui::Separator() return; ImGuiContext& g = *GImGui; - // Those flags should eventually be overridable by the user + // Those flags should eventually be overrideable by the user ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected if (flags & ImGuiSeparatorFlags_Vertical) @@ -1222,7 +1222,7 @@ void ImGui::Separator() x1 += window->DC.Indent.x; const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); - ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. + ItemSize(ImVec2(0.0f, 1.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit if (!ItemAdd(bb, 0)) { if (window->DC.CurrentColumns) @@ -1252,7 +1252,7 @@ void ImGui::VerticalSeparator() float y1 = window->DC.CursorPos.y; float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y; const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2)); - ItemSize(ImVec2(bb.GetWidth(), 0.0f)); + ItemSize(ImVec2(1.0f, 0.0f)); if (!ItemAdd(bb, 0)) return; From 5d799d76ea78a2f3fcd87cd66bf76fd8ade61a7a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 26 Apr 2019 21:55:09 +0200 Subject: [PATCH 296/566] Internals: Nav scrolling uses InnerMainRect instead of InnerClipRect. --- imgui.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2dbc4207..7c85e4e1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8101,14 +8101,14 @@ static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) - SetWindowScrollY(window, window->Scroll.y - window->InnerClipRect.GetHeight()); + SetWindowScrollY(window, window->Scroll.y - window->InnerMainRect.GetHeight()); else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) - SetWindowScrollY(window, window->Scroll.y + window->InnerClipRect.GetHeight()); + SetWindowScrollY(window, window->Scroll.y + window->InnerMainRect.GetHeight()); } else { const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; - const float page_offset_y = ImMax(0.0f, window->InnerClipRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); + const float page_offset_y = ImMax(0.0f, window->InnerMainRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); float nav_scoring_rect_offset_y = 0.0f; if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) { From 61d92580aa772cbe5b64211c738ce1fdf34672e6 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 26 Apr 2019 23:17:24 +0200 Subject: [PATCH 297/566] Window: Fixed contents region being off by WindowBorderSize amount on the right when scrollbar is active. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 16 ++++++++-------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c51fcc0e..c33d9204 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,7 @@ Other Changes: One of the noticeable minor side effect was that navigating menus would have had a tendency to disable highlight from parent menu items earlier than necessary while approaching the child menu. - Window: Close button is horizontally aligned with style.FramePadding.x. +- Window: Fixed contents region being off by WindowBorderSize amount on the right when scrollbar is active. - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] diff --git a/imgui.cpp b/imgui.cpp index 7c85e4e1..7516081d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5414,8 +5414,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); - window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); - window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); + window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + window->WindowBorderSize)); + window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + window->WindowBorderSize)); // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) @@ -5517,10 +5517,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } } - // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() - window->OuterRectClipped = window->Rect(); - window->OuterRectClipped.ClipWith(window->ClipRect); - // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. // Maybe we can support CTRL+C on every element? @@ -5530,13 +5526,17 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) LogToClipboard(); */ + // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() + window->OuterRectClipped = window->Rect(); + window->OuterRectClipped.ClipWith(window->ClipRect); + // Inner rectangle // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); - window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize; - window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize; + window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); + window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE); // Inner clipping rectangle From 00b3c830db849551a26dbaccf0cfc8bb2e7fa2b9 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 26 Apr 2019 23:21:30 +0200 Subject: [PATCH 298/566] Internals: Begin: Moved OuterRectClipped/InnerMainRect/InnerClipRect computation higher up in the function, next to ContentsRect/WorkRect code. Removed commented out debug drawing code which is now available in Metrics window. --- imgui.cpp | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7516081d..4f79cec8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5417,6 +5417,24 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + window->WindowBorderSize)); window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + window->WindowBorderSize)); + // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() + window->OuterRectClipped = window->Rect(); + window->OuterRectClipped.ClipWith(window->ClipRect); + + // Inner rectangle + // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame + // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; + window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); + window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); + + // Inner clipping rectangle + // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); + window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; @@ -5526,26 +5544,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) LogToClipboard(); */ - // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() - window->OuterRectClipped = window->Rect(); - window->OuterRectClipped.ClipWith(window->ClipRect); - - // Inner rectangle - // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame - // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. - window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; - window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); - window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); - window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); - //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE); - - // Inner clipping rectangle - // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. - window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize))); - window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); - window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize))); - window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); - // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). // This is useful to allow creating context menus on title bar only, etc. window->DC.LastItemId = window->MoveId; From 3d363c91fd32667f9645d0fa84399da7db6b95e4 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 28 Apr 2019 14:49:15 +0200 Subject: [PATCH 299/566] Internals: Exposed ImGuiDataTypeInfo, DataTypeGetInfo(), DataTypeFormatString(). Comments. --- imgui_internal.h | 14 +++++++++++++- imgui_widgets.cpp | 47 ++++++++++++++++++++--------------------------- 2 files changed, 33 insertions(+), 28 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 0cf8f03b..28a98dc2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -65,6 +65,7 @@ struct ImGuiColorMod; // Stacked color modifier, backup of modifie struct ImGuiColumnData; // Storage data for a single column struct ImGuiColumns; // Storage data for a columns set struct ImGuiContext; // Main imgui context +struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data @@ -501,7 +502,6 @@ struct ImVec1 ImVec1(float _x) { x = _x; } }; - // 2D axis aligned bounding-box // NB: we can't rely on ImVec2 math operators being available here struct IMGUI_API ImRect @@ -538,6 +538,14 @@ struct IMGUI_API ImRect bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } }; +// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). +struct ImGuiDataTypeInfo +{ + size_t Size; // Size in byte + const char* PrintFmt; // Default printf format for the type + const char* ScanFmt; // Default scanf format for the type +}; + // Stacked color modifier, backup of modified data so we can restore it struct ImGuiColorMod { @@ -1557,6 +1565,10 @@ namespace ImGui template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); + // Data type helpers + IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); + IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format); + // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 82bef8fb..0b3d2400 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -105,7 +105,6 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); //------------------------------------------------------------------------- // Data Type helpers -static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format); static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format); @@ -1539,6 +1538,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa // [SECTION] Data Type and Data Formatting Helpers [Internal] //------------------------------------------------------------------------- // - PatchFormatStringFloatToInt() +// - DataTypeGetInfo() // - DataTypeFormatString() // - DataTypeApplyOp() // - DataTypeApplyOpFromText() @@ -1546,13 +1546,6 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa // - RoundScalarWithFormat<>() //------------------------------------------------------------------------- -struct ImGuiDataTypeInfo -{ - size_t Size; - const char* PrintFmt; // Unused - const char* ScanFmt; -}; - static const ImGuiDataTypeInfo GDataTypeInfo[] = { { sizeof(char), "%d", "%d" }, // ImGuiDataType_S8 @@ -1597,7 +1590,13 @@ static const char* PatchFormatStringFloatToInt(const char* fmt) return fmt; } -static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format) +const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type) +{ + IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); + return &GDataTypeInfo[data_type]; +} + +int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format) { // Signedness doesn't matter when pushing integer arguments if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32) @@ -1696,11 +1695,12 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all. IM_ASSERT(data_type < ImGuiDataType_COUNT); int data_backup[2]; - IM_ASSERT(GDataTypeInfo[data_type].Size <= sizeof(data_backup)); - memcpy(data_backup, data_ptr, GDataTypeInfo[data_type].Size); + const ImGuiDataTypeInfo* type_info = ImGui::DataTypeGetInfo(data_type); + IM_ASSERT(type_info->Size <= sizeof(data_backup)); + memcpy(data_backup, data_ptr, type_info->Size); if (format == NULL) - format = GDataTypeInfo[data_type].ScanFmt; + format = type_info->ScanFmt; // FIXME-LEGACY: The aim is to remove those operators and write a proper expression evaluator at some point.. int arg1i = 0; @@ -1769,7 +1769,7 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b IM_ASSERT(0); } - return memcmp(data_backup, data_ptr, GDataTypeInfo[data_type].Size) != 0; + return memcmp(data_backup, data_ptr, type_info->Size) != 0; } static float GetMinimumStepAtDecimalPrecision(int decimal_precision) @@ -1990,11 +1990,9 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa return false; // Default format string when passing NULL - // Patch old "%.0f" format string to use "%d", read function comments for more details. - IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) - format = GDataTypeInfo[data_type].PrintFmt; - else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) + format = DataTypeGetInfo(data_type)->PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.) format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Drag turns it into an input box @@ -2435,11 +2433,9 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co return false; // Default format string when passing NULL - // Patch old "%.0f" format string to use "%d", read function comments for more details. - IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) - format = GDataTypeInfo[data_type].PrintFmt; - else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) + format = DataTypeGetInfo(data_type)->PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.) format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Slider turns it into an input box @@ -2591,11 +2587,9 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d return false; // Default format string when passing NULL - // Patch old "%.0f" format string to use "%d", read function comments for more details. - IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) - format = GDataTypeInfo[data_type].PrintFmt; - else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) + format = DataTypeGetInfo(data_type)->PrintFmt; + else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.) format = PatchFormatStringFloatToInt(format); const bool hovered = ItemHoverable(frame_bb, id); @@ -2777,9 +2771,8 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; - IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) - format = GDataTypeInfo[data_type].PrintFmt; + format = DataTypeGetInfo(data_type)->PrintFmt; char buf[64]; DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, data_ptr, format); From 4e81b2d09388ed9769eb3c5125095d0fd5a5d52c Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 28 Apr 2019 17:05:23 +0200 Subject: [PATCH 300/566] Internals: Renaming. Renamed ImGuiPopupRef to ImGuiPopupData for consistency and added constructor. --- imgui.cpp | 17 +++++++++-------- imgui_internal.h | 12 +++++++----- imgui_widgets.cpp | 2 +- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4f79cec8..bc1a5025 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1068,6 +1068,7 @@ static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb static ImVec2 NavCalcPreferredRefPos(); static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); +static int FindWindowFocusIndex(ImGuiWindow* window); // Misc static void UpdateMouseInputs(); @@ -3602,7 +3603,7 @@ void ImGui::NewFrame() // Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow && !g.NavWindow->WasActive) - FocusPreviousWindowIgnoringOne(NULL); + FocusTopMostWindowIgnoringOne(NULL); // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. @@ -5002,7 +5003,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0); if (flags & ImGuiWindowFlags_Popup) { - ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; + ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed window_just_activated_by_user |= (window != popup_ref.Window); } @@ -5035,7 +5036,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) CheckStacksSize(window, true); if (flags & ImGuiWindowFlags_Popup) { - ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; + ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; popup_ref.Window = window; g.BeginPopupStack.push_back(popup_ref); window->PopupId = popup_ref.PopupId; @@ -5724,7 +5725,7 @@ void ImGui::FocusWindow(ImGuiWindow* window) BringWindowToDisplayFront(window); } -void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window) +void ImGui::FocusTopMostWindowIgnoringOne(ImGuiWindow* ignore_window) { ImGuiContext& g = *GImGui; for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--) @@ -6944,7 +6945,7 @@ void ImGui::OpenPopupEx(ImGuiID id) ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; int current_stack_size = g.BeginPopupStack.Size; - ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. + ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; popup_ref.ParentWindow = parent_window; @@ -7008,7 +7009,7 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window) // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++) { - ImGuiPopupRef& popup = g.OpenPopupStack[popup_count_to_keep]; + ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep]; if (!popup.Window) continue; IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); @@ -8129,7 +8130,7 @@ static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) return 0.0f; } -static int FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) +static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--) @@ -8154,7 +8155,7 @@ static void NavUpdateWindowingHighlightWindow(int focus_change_dir) if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal) return; - const int i_current = FindWindowFocusIndex(g.NavWindowingTarget); + const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget); ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir); if (!window_target) window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir); diff --git a/imgui_internal.h b/imgui_internal.h index 28a98dc2..f76beb1e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -72,7 +72,7 @@ struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() intern struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiNavMoveResult; // Result of a directional navigation move query result struct ImGuiNextWindowData; // Storage for SetNexWindow** functions -struct ImGuiPopupRef; // Storage for current popup stack +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 ImGuiTabBar; // Storage for a tab bar @@ -648,7 +648,7 @@ struct ImGuiSettingsHandler }; // Storage for current popup stack -struct ImGuiPopupRef +struct ImGuiPopupData { ImGuiID PopupId; // Set on OpenPopup() ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() @@ -657,6 +657,8 @@ struct ImGuiPopupRef ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup + + ImGuiPopupData() { PopupId = 0; Window = ParentWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; } }; struct ImGuiColumnData @@ -856,8 +858,8 @@ struct ImGuiContext ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() ImVector FontStack; // Stack for PushFont()/PopFont() - ImVector OpenPopupStack; // Which popups are open (persistent) - ImVector BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) + ImVectorOpenPopupStack; // Which popups are open (persistent) + ImVectorBeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions ImGuiCond NextTreeNodeOpenCond; @@ -1390,7 +1392,7 @@ namespace ImGui IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); IMGUI_API ImGuiWindow* FindWindowByName(const char* name); IMGUI_API void FocusWindow(ImGuiWindow* window); - IMGUI_API void FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window); + IMGUI_API void FocusTopMostWindowIgnoringOne(ImGuiWindow* ignore_window); IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window); IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window); IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0b3d2400..5cb1975c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5824,7 +5824,7 @@ void ImGui::EndMainMenuBar() // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window ImGuiContext& g = *GImGui; if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0) - FocusPreviousWindowIgnoringOne(g.NavWindow); + FocusTopMostWindowIgnoringOne(g.NavWindow); End(); } From 09db2f6dec01c57e88d45a329550c1dc024ecbb4 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 28 Apr 2019 18:50:51 +0200 Subject: [PATCH 301/566] Fix 61d9258 when there is not scrollbar "Window: Fixed contents region being off by WindowBorderSize amount on the right when scrollbar is active." --- imgui.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bc1a5025..61d5a2cf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5413,10 +5413,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update various regions. Variables they depends on are set above in this function. // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out. window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); - window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + window->WindowBorderSize)); - window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + window->WindowBorderSize)); + window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); + window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() window->OuterRectClipped = window->Rect(); From 3276b127657ae6f4d813ba38a4366a006d1a73f2 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 28 Apr 2019 20:55:51 +0200 Subject: [PATCH 302/566] Internals: Added DataTypeApplyOp, DataTypeApplyOpFromText to imgui_internal.h --- imgui_internal.h | 2 ++ imgui_widgets.cpp | 8 ++------ 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index f76beb1e..075d18aa 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1570,6 +1570,8 @@ namespace ImGui // Data type helpers IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format); + IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); + IMGUI_API bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format); // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5cb1975c..c707e0ee 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -104,10 +104,6 @@ static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); // [SECTION] Forward Declarations //------------------------------------------------------------------------- -// Data Type helpers -static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); -static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format); - // For InputTextEx() static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data); static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); @@ -1619,7 +1615,7 @@ int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type return 0; } -static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2) +void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2) { IM_ASSERT(op == '+' || op == '-'); switch (data_type) @@ -1671,7 +1667,7 @@ static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* // User can input math operators (e.g. +100) to edit a numerical values. // NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. -static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format) +bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format) { while (ImCharIsBlankA(*buf)) buf++; From bda2cde68eed30c5c1992709c909ad220d226ba4 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 28 Apr 2019 21:52:12 +0200 Subject: [PATCH 303/566] Popups: Closing a popup restores the focused/nav window in place at the time of the popup opening, instead of restoring the window that was in the window stack at the time of the OpenPopup call. (#2517) Among other things, this allows opening a popup while no window are focused, and pressing Escape to clear the focus again. --- docs/CHANGELOG.txt | 4 ++++ docs/TODO.txt | 1 + imgui.cpp | 44 +++++++++++++++++++++++++++----------------- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 5 +++-- 5 files changed, 38 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c33d9204..e6d387b7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,10 @@ Other Changes: highlight from parent menu items earlier than necessary while approaching the child menu. - Window: Close button is horizontally aligned with style.FramePadding.x. - Window: Fixed contents region being off by WindowBorderSize amount on the right when scrollbar is active. +- Popups: Closing a popup restores the focused/nav window in place at the time of the popup opening, + instead of restoring the window that was in the window stack at the time of the OpenPopup call. (#2517) + Among other things, this allows opening a popup while no window are focused, and pressing Escape to + clear the focus again. - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] diff --git a/docs/TODO.txt b/docs/TODO.txt index 9e64b163..f900e7e1 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -291,6 +291,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - nav/menus: allow pressing Menu to leave a sub-menu. - nav/menus: a way to access the main menu bar with Alt? (currently needs CTRL+TAB) - nav/menus: when using the main menu bar, even though we restore focus after, the underlying window loses its title bar highlight during menu manipulation. could we prevent it? + - nav/menus: main menu bar currently cannot restore a NULL focus. Could save NavWindow at the time of being focused, similarly to what popup do? - nav: simulate right-click or context activation? (SHIFT+F10) - nav: tabs should go through most/all widgets (in submission order?). - nav: when CTRL-Tab/windowing is active, the HoveredWindow detection doesn't take account of the window display re-ordering. diff --git a/imgui.cpp b/imgui.cpp index 61d5a2cf..e465fdf1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3603,7 +3603,7 @@ void ImGui::NewFrame() // Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow && !g.NavWindow->WasActive) - FocusTopMostWindowIgnoringOne(NULL); + FocusTopMostWindowUnderOne(NULL, NULL); // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. @@ -5726,10 +5726,18 @@ void ImGui::FocusWindow(ImGuiWindow* window) BringWindowToDisplayFront(window); } -void ImGui::FocusTopMostWindowIgnoringOne(ImGuiWindow* ignore_window) +void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window) { ImGuiContext& g = *GImGui; - for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--) + + int start_idx = g.WindowsFocusOrder.Size - 1; + if (under_this_window != NULL) + { + int under_this_window_idx = FindWindowFocusIndex(under_this_window); + if (under_this_window_idx != -1) + start_idx = under_this_window_idx - 1; + } + for (int i = start_idx; i >= 0; i--) { // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. ImGuiWindow* window = g.WindowsFocusOrder[i]; @@ -5741,6 +5749,7 @@ void ImGui::FocusTopMostWindowIgnoringOne(ImGuiWindow* ignore_window) return; } } + FocusWindow(NULL); } void ImGui::SetNextItemWidth(float item_width) @@ -6949,7 +6958,7 @@ void ImGui::OpenPopupEx(ImGuiID id) ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; - popup_ref.ParentWindow = parent_window; + popup_ref.SourceWindow = g.NavWindow; popup_ref.OpenFrameCount = g.FrameCount; popup_ref.OpenParentId = parent_window->IDStack.back(); popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); @@ -7035,24 +7044,25 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window) void ImGui::ClosePopupToLevel(int remaining, bool apply_focus_to_window_under) { - IM_ASSERT(remaining >= 0); ImGuiContext& g = *GImGui; - ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow; + IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); + ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow; + ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window; g.OpenPopupStack.resize(remaining); - // FIXME: This code is faulty and we may want to eventually to replace or remove the 'apply_focus_to_window_under=true' path completely. - // Instead of using g.OpenPopupStack[remaining-1].Window etc. we should find the highest root window that is behind the popups we are closing. - // The current code will set focus to the parent of the popup window which is incorrect. - // It rarely manifested until now because UpdateMouseMovingWindowNewFrame() would call FocusWindow() again on the clicked window, - // leading to a chain of focusing A (clicked window) then B (parent window of the popup) then A again. - // However if the clicked window has the _NoMove flag set we would be left with B focused. - // For now, we have disabled this path when called from ClosePopupsOverWindow() because the users of ClosePopupsOverWindow() don't need to alter focus anyway, - // but we should inspect and fix this properly. if (apply_focus_to_window_under) { - if (g.NavLayer == 0) - focus_window = NavRestoreLastChildNavWindow(focus_window); - FocusWindow(focus_window); + if (focus_window && !focus_window->WasActive && popup_window) + { + // Fallback + FocusTopMostWindowUnderOne(popup_window, NULL); + } + else + { + if (g.NavLayer == 0 && focus_window) + focus_window = NavRestoreLastChildNavWindow(focus_window); + FocusWindow(focus_window); + } } } diff --git a/imgui_internal.h b/imgui_internal.h index 075d18aa..415dfaea 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -652,13 +652,13 @@ struct ImGuiPopupData { ImGuiID PopupId; // Set on OpenPopup() ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() - ImGuiWindow* ParentWindow; // Set on OpenPopup() + ImGuiWindow* SourceWindow; // Set on OpenPopup() copy of NavWindow at the time of opening the popup int OpenFrameCount; // Set on OpenPopup() ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup - ImGuiPopupData() { PopupId = 0; Window = ParentWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; } + ImGuiPopupData() { PopupId = 0; Window = SourceWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; } }; struct ImGuiColumnData @@ -1392,7 +1392,7 @@ namespace ImGui IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); IMGUI_API ImGuiWindow* FindWindowByName(const char* name); IMGUI_API void FocusWindow(ImGuiWindow* window); - IMGUI_API void FocusTopMostWindowIgnoringOne(ImGuiWindow* ignore_window); + IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window); IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window); IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window); IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c707e0ee..f3e9ecd0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5818,9 +5818,10 @@ void ImGui::EndMainMenuBar() EndMenuBar(); // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window + // FIXME: With this strategy we won't be able to restore a NULL focus. ImGuiContext& g = *GImGui; if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0) - FocusTopMostWindowIgnoringOne(g.NavWindow); + FocusTopMostWindowUnderOne(g.NavWindow, NULL); End(); } @@ -5951,7 +5952,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) { // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. bool moving_within_opened_triangle = false; - if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].ParentWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar)) + if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar)) { if (ImGuiWindow* next_window = g.OpenPopupStack[g.BeginPopupStack.Size].Window) { From 842a720e72ff959ec393ae420819b8c05af679a1 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 28 Apr 2019 22:21:23 +0200 Subject: [PATCH 304/566] Popups: Closes popup at the time of FocusWindow(). Fixes right-click from closing all popups instead of aiming at the hovered popup level (regression in 1.67's ae76a1fd). --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 37 +++++++++++++++++++++---------------- imgui_demo.cpp | 7 +++++++ imgui_internal.h | 4 ++-- 4 files changed, 32 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e6d387b7..a753438e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,8 @@ Other Changes: instead of restoring the window that was in the window stack at the time of the OpenPopup call. (#2517) Among other things, this allows opening a popup while no window are focused, and pressing Escape to clear the focus again. +- Popups: Fixed right-click from closing all popups instead of aiming at the hovered popup level + (regression in 1.67). - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] diff --git a/imgui.cpp b/imgui.cpp index e465fdf1..d58ba779 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2880,7 +2880,8 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId) return false; - // Test if interactions on this window are blocked by an active popup or modal + // Test if interactions on this window are blocked by an active popup or modal. + // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. if (!IsWindowContentHoverable(window, flags)) return false; @@ -3213,8 +3214,9 @@ void ImGui::UpdateMouseMovingWindowEndFrame() } } - // With right mouse button we close popups without changing focus - // (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger) + // With right mouse button we close popups without changing focus based on where the mouse is aimed + // Instead, focus will be restored to the window under the bottom-most closed popup. + // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger) if (g.IO.MouseClicked[1]) { // Find the top-most window between HoveredWindow and the front most Modal Window. @@ -3231,7 +3233,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (window == g.HoveredWindow) hovered_window_above_modal = true; } - ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal); + ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true); } } @@ -3609,7 +3611,7 @@ void ImGui::NewFrame() // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); g.BeginPopupStack.resize(0); - ClosePopupsOverWindow(g.NavWindow); + ClosePopupsOverWindow(g.NavWindow, false); // Create implicit/fallback window - which we will only render it if the user has added something to it. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. @@ -5707,6 +5709,9 @@ void ImGui::FocusWindow(ImGuiWindow* window) //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL); } + // Close popups if any + ClosePopupsOverWindow(window, false); + // Passing NULL allow to disable keyboard focus if (!window) return; @@ -7005,7 +7010,7 @@ bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button) return false; } -void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window) +void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.empty()) @@ -7026,23 +7031,23 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window) if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) continue; - // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow) - bool popup_or_descendent_has_focus = false; - for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_has_focus; m++) + // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow) + bool popup_or_descendent_is_ref_window = false; + for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++) if (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow) - popup_or_descendent_has_focus = true; - if (!popup_or_descendent_has_focus) + popup_or_descendent_is_ref_window = true; + if (!popup_or_descendent_is_ref_window) break; } } if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below { //IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep); - ClosePopupToLevel(popup_count_to_keep, false); + ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup); } } -void ImGui::ClosePopupToLevel(int remaining, bool apply_focus_to_window_under) +void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); @@ -7050,7 +7055,7 @@ void ImGui::ClosePopupToLevel(int remaining, bool apply_focus_to_window_under) ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window; g.OpenPopupStack.resize(remaining); - if (apply_focus_to_window_under) + if (restore_focus_to_window_under_popup) { if (focus_window && !focus_window->WasActive && popup_window) { @@ -8278,11 +8283,11 @@ static void ImGui::NavUpdateWindowing() // Apply final focus if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)) { + ClearActiveID(); g.NavDisableHighlight = false; g.NavDisableMouseHover = true; apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window); - ClosePopupsOverWindow(apply_focus_window); - ClearActiveID(); + ClosePopupsOverWindow(apply_focus_window, false); FocusWindow(apply_focus_window); if (apply_focus_window->NavLastIds[0] == 0) NavInitWindow(apply_focus_window, false); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 695fd869..a57cfac4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2209,6 +2209,13 @@ static void ShowDemoWindowPopups() if (ImGui::BeginMenu("Sub-menu")) { ImGui::MenuItem("Click me"); + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + ImGui::Text("I am the last one here."); + ImGui::EndPopup(); + } ImGui::EndMenu(); } ImGui::EndPopup(); diff --git a/imgui_internal.h b/imgui_internal.h index 415dfaea..23b95257 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1466,8 +1466,8 @@ namespace ImGui // Popups, Modals, Tooltips IMGUI_API void OpenPopupEx(ImGuiID id); - IMGUI_API void ClosePopupToLevel(int remaining, bool apply_focus_to_window_under); - IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window); + IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); + IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id within current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true); From 4dec7447958402b3353a02bbbb7cc4d186b61bae Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 28 Apr 2019 23:49:57 +0200 Subject: [PATCH 305/566] Tidying up BeginMenu() code + comments. --- imgui.cpp | 5 +++-- imgui_widgets.cpp | 43 ++++++++++++++++++++++++------------------- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d58ba779..5a584c90 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7034,8 +7034,9 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow) bool popup_or_descendent_is_ref_window = false; for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++) - if (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow) - popup_or_descendent_is_ref_window = true; + if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window) + if (popup_window->RootWindow == ref_window->RootWindow) + popup_or_descendent_is_ref_window = true; if (!popup_or_descendent_is_ref_window) break; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f3e9ecd0..874b038a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5947,31 +5947,36 @@ bool ImGui::BeginMenu(const char* label, bool enabled) if (menuset_is_open) g.NavWindow = backed_nav_window; - bool want_open = false, want_close = false; + bool want_open = false; + bool want_close = false; if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) { + // Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. - bool moving_within_opened_triangle = false; - if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar)) + bool moving_toward_other_child_menu = false; + + ImGuiWindow* child_menu_window = (g.BeginPopupStack.Size < g.OpenPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window) ? g.OpenPopupStack[g.BeginPopupStack.Size].Window : NULL; + if (g.HoveredWindow == window && child_menu_window != NULL && !(window->Flags & ImGuiWindowFlags_MenuBar)) { - if (ImGuiWindow* next_window = g.OpenPopupStack[g.BeginPopupStack.Size].Window) - { - // FIXME-DPI: Values should be derived from a master "scale" factor. - ImRect next_window_rect = next_window->Rect(); - ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; - ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); - ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); - float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. - ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues - tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? - tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); - moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); - //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug - } + // FIXME-DPI: Values should be derived from a master "scale" factor. + ImRect next_window_rect = child_menu_window->Rect(); + ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; + ImVec2 tb = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. + ta.x += (window->Pos.x < child_menu_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? + tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); + moving_toward_other_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); + //GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG] } + if (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_toward_other_child_menu) + want_close = true; - want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); - want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); + if (!menu_is_open && hovered && pressed) // Click to open + want_open = true; + else if (!menu_is_open && hovered && !moving_toward_other_child_menu) // Hover to open + want_open = true; if (g.NavActivateId == id) { From 4c0f34fd5da00056d003fc0cbd97e7219605caac Mon Sep 17 00:00:00 2001 From: Richard Mitton Date: Sat, 27 Apr 2019 15:38:25 -0700 Subject: [PATCH 306/566] Improved algorithm for mitre joints on thick lines --- imgui_demo.cpp | 2 ++ imgui_draw.cpp | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a57cfac4..05311c52 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4095,6 +4095,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_All, th); x += sz + spacing; draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight, th); x += sz + spacing; draw_list->AddTriangle(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32, th); x += sz + spacing; + draw_list->AddTriangle(ImVec2(x + sz*0.5f, y), ImVec2(x + sz*0.6f, y + sz - 0.5f), ImVec2(x + sz*0.4f, y + sz - 0.5f), col32, th); x += sz + spacing; draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col32, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col32, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, th); x += sz + spacing; // Diagonal line @@ -4108,6 +4109,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f); x += sz + spacing; draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight); x += sz + spacing; draw_list->AddTriangleFilled(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32); x += sz + spacing; + draw_list->AddTriangleFilled(ImVec2(x + sz*0.5f, y), ImVec2(x + sz*0.6f, y + sz - 0.5f), ImVec2(x + sz*0.4f, y + sz - 0.5f), col32); x += sz + spacing; draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col32); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col32); x += spacing + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col32); x += sz; // Pixel (faster than AddLine) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 290fadb8..95903660 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -664,6 +664,7 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c // Those macros expects l-values. #define IM_NORMALIZE2F_OVER_ZERO(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } } #define IM_NORMALIZE2F_OVER_EPSILON_CLAMP(VX,VY,EPS,INVLENMAX) { float d2 = VX*VX + VY*VY; if (d2 > EPS) { float inv_len = 1.0f / ImSqrt(d2); if (inv_len > INVLENMAX) inv_len = INVLENMAX; VX *= inv_len; VY *= inv_len; } } +#define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 < 0.5f) d2 = 0.5f; float inv_lensq = 1.0f / d2; VX *= inv_lensq; VY *= inv_lensq; } // 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. @@ -725,7 +726,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // 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_NORMALIZE2F_OVER_EPSILON_CLAMP(dm_x, dm_y, 0.000001f, 100.0f) + IM_FIXNORMAL2F(dm_x, dm_y) dm_x *= AA_SIZE; dm_y *= AA_SIZE; @@ -780,7 +781,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // 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_NORMALIZE2F_OVER_EPSILON_CLAMP(dm_x, dm_y, 0.000001f, 100.0f); + 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; @@ -900,7 +901,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun 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_NORMALIZE2F_OVER_EPSILON_CLAMP(dm_x, dm_y, 0.000001f, 100.0f); + IM_FIXNORMAL2F(dm_x, dm_y); dm_x *= AA_SIZE * 0.5f; dm_y *= AA_SIZE * 0.5f; From 0f2852806c7176a7017d3bbcdc711363651c696b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Apr 2019 12:44:17 +0200 Subject: [PATCH 307/566] Amend 48a09a7 with changelog, breaking changes, tweak demo code for spacing. (#2518) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 1 + imgui_demo.cpp | 60 ++++++++++++++++++++++++---------------------- imgui_draw.cpp | 5 ++-- 4 files changed, 39 insertions(+), 31 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a753438e..bc326aff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -34,6 +34,8 @@ HOW TO UPDATE? ----------------------------------------------------------------------- Breaking Changes: +- ImDrawList: Fixed rectangles with thick lines (>1.0f) not being as thick as requested. (#2518) + If you have custom rendering using thick lines, they will appear thicker now. - Examples: Vulkan: Added MinImageCount/ImageCount fields in ImGui_ImplVulkan_InitInfo, required during initialization to specify the number of in-flight image requested by swap chains. (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071, #1677) [@nathanvoglsam] @@ -73,6 +75,8 @@ Other Changes: - Separator: Declare its thickness (1.0f) to the layout, making items around separator more symmetrical. - Combo, Slider, Scrollbar: Improve rendering in situation when there's only a few pixels available (<3 pixels). - Nav: Fixed Drag/Slider functions going into text input mode when keyboard CTRL is held while pressing NavActivate. +- ImDrawList: Improved algorithm for mitre joints on thick lines, preserving correct thickness up to 90 degrees + angles, also faster to output. (#2518) [@rmitton] - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. diff --git a/imgui.cpp b/imgui.cpp index 5a584c90..61f410a7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,7 @@ CODE When you are not sure about a 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. + - 2019/04/29 (1.70) - fixed ImDrawList rectangles with thick lines (>1.0f) not being as thick as requested. If you have custom rendering using rectangles with thick lines, they will appear thicker now. - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 05311c52..33f33af8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4077,44 +4077,48 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::BeginTabItem("Primitives")) { static float sz = 36.0f; - static float thickness = 4.0f; - static ImVec4 col = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); + static float thickness = 3.0f; + static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f"); ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f"); - ImGui::ColorEdit4("Color", &col.x); + ImGui::ColorEdit4("Color", &colf.x); const ImVec2 p = ImGui::GetCursorScreenPos(); - const ImU32 col32 = ImColor(col); - float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f; + const ImU32 col = ImColor(colf); + float x = p.x + 4.0f, y = p.y + 4.0f; + float spacing = 10.0f; + ImDrawCornerFlags corners_none = 0; + ImDrawCornerFlags corners_all = ImDrawCornerFlags_All; + ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight; for (int n = 0; n < 2; n++) { - // First line uses a thickness of 1.0, second line uses the configurable thickness + // First line uses a thickness of 1.0f, second line uses the configurable thickness float th = (n == 0) ? 1.0f : thickness; - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6, th); x += sz + spacing; // Hexagon - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 20, th); x += sz + spacing; // Circle - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 0.0f, ImDrawCornerFlags_All, th); x += sz + spacing; - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_All, th); x += sz + spacing; - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight, th); x += sz + spacing; - draw_list->AddTriangle(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32, th); x += sz + spacing; - draw_list->AddTriangle(ImVec2(x + sz*0.5f, y), ImVec2(x + sz*0.6f, y + sz - 0.5f), ImVec2(x + sz*0.4f, y + sz - 0.5f), col32, th); x += sz + spacing; - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col32, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col32, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, th); x += sz + spacing; // Diagonal line - draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz*1.3f, y + sz*0.3f), ImVec2(x + sz - sz*1.3f, y + sz - sz*0.3f), ImVec2(x + sz, y + sz), col32, th); + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 6, th); x += sz + spacing; // Hexagon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 20, th); x += sz + spacing; // Circle + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, corners_none, th); x += sz + spacing; // Square + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_all, th); x += sz + spacing; // Square with all rounded corners + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br, th); 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->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->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x, 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->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz*1.3f, y + sz*0.3f), ImVec2(x + sz - sz*1.3f, y + sz - sz*0.3f), ImVec2(x + sz, y + sz), col, th); x = p.x + 4; y += sz + spacing; } - draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 6); x += sz + spacing; // Hexagon - draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col32, 32); x += sz + spacing; // Circle - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32); x += sz + spacing; - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f); x += sz + spacing; - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col32, 10.0f, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight); x += sz + spacing; - draw_list->AddTriangleFilled(ImVec2(x + sz*0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col32); x += sz + spacing; - draw_list->AddTriangleFilled(ImVec2(x + sz*0.5f, y), ImVec2(x + sz*0.6f, y + sz - 0.5f), ImVec2(x + sz*0.4f, y + sz - 0.5f), col32); x += sz + spacing; - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col32); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col32); x += spacing + spacing; // Vertical line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col32); x += sz; // Pixel (faster than AddLine) + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 6); x += sz + spacing; // Hexagon + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 32); x += sz + spacing; // Circle + 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 + 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->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)); - ImGui::Dummy(ImVec2((sz + spacing) * 9.5f, (sz + spacing) * 3)); + ImGui::Dummy(ImVec2((sz + spacing) * 9.8f, (sz + spacing) * 3)); ImGui::EndTabItem(); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 95903660..5d493600 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -662,9 +662,8 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c // On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superflous function calls to optimize debug/non-inlined builds. // Those macros expects l-values. -#define IM_NORMALIZE2F_OVER_ZERO(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } } -#define IM_NORMALIZE2F_OVER_EPSILON_CLAMP(VX,VY,EPS,INVLENMAX) { float d2 = VX*VX + VY*VY; if (d2 > EPS) { float inv_len = 1.0f / ImSqrt(d2); if (inv_len > INVLENMAX) inv_len = INVLENMAX; VX *= inv_len; VY *= inv_len; } } -#define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 < 0.5f) d2 = 0.5f; float inv_lensq = 1.0f / d2; VX *= inv_lensq; VY *= inv_lensq; } +#define IM_NORMALIZE2F_OVER_ZERO(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } } +#define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 < 0.5f) d2 = 0.5f; float inv_lensq = 1.0f / d2; VX *= inv_lensq; VY *= inv_lensq; } // 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. From db2d58a68b923319695acfd10dadb6706a200d32 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Apr 2019 16:34:02 +0200 Subject: [PATCH 308/566] Drag and Drop: Fixed drag source with ImGuiDragDropFlags_SourceAllowNullID and null ID from receiving click regardless of being covered by another window (it didn't honor correct hovering rules). (#2521) --- docs/CHANGELOG.txt | 2 ++ docs/TODO.txt | 1 + imgui.cpp | 10 +++++----- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bc326aff..dbbca6db 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -75,6 +75,8 @@ Other Changes: - Separator: Declare its thickness (1.0f) to the layout, making items around separator more symmetrical. - Combo, Slider, Scrollbar: Improve rendering in situation when there's only a few pixels available (<3 pixels). - Nav: Fixed Drag/Slider functions going into text input mode when keyboard CTRL is held while pressing NavActivate. +- Drag and Drop: Fixed drag source with ImGuiDragDropFlags_SourceAllowNullID and null ID from receiving click + regardless of being covered by another window (it didn't honor correct hovering rules). (#2521) - ImDrawList: Improved algorithm for mitre joints on thick lines, preserving correct thickness up to 90 degrees angles, also faster to output. (#2518) [@rmitton] - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert diff --git a/docs/TODO.txt b/docs/TODO.txt index f900e7e1..2dbf1f0f 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -235,6 +235,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - filters: handle wild-cards (with implicit leading/trailing *), reg-exprs - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb) + - drag and drop: drag tooltip hovering over source widget with IsItemHovered/SetTooltip flickers. - drag and drop: releasing a drop shows the "..." tooltip for one frame - since e13e598 (#1725) - drag and drop: have some way to know when a drag begin from BeginDragDropSource() pov. - drag and drop: allow preview tooltip to be submitted from a different place than the drag source. (#1725) diff --git a/imgui.cpp b/imgui.cpp index 61f410a7..a57b13aa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8764,16 +8764,16 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) return false; } + // Early out + if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window)) + return false; + // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image() // We build a throwaway ID based on current ID stack + relative AABB of items in window. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. - bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0; - if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window)) - return false; source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect); - if (is_hovered) - SetHoveredID(source_id); + bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id); if (is_hovered && g.IO.MouseClicked[mouse_button]) { SetActiveID(source_id, window); From 3fbc0b7a9e8022ab43e5f886f0af8463e269130a Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Apr 2019 18:31:51 +0200 Subject: [PATCH 309/566] Obsoleted GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 +----- imgui.h | 3 ++- imgui_demo.cpp | 4 ++-- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dbbca6db..fb41b3b6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,8 @@ HOW TO UPDATE? Breaking Changes: - ImDrawList: Fixed rectangles with thick lines (>1.0f) not being as thick as requested. (#2518) If you have custom rendering using thick lines, they will appear thicker now. +- Obsoleted GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. + Kept inline redirection function. - Examples: Vulkan: Added MinImageCount/ImageCount fields in ImGui_ImplVulkan_InitInfo, required during initialization to specify the number of in-flight image requested by swap chains. (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). (#2071, #1677) [@nathanvoglsam] diff --git a/imgui.cpp b/imgui.cpp index a57b13aa..5d7a29d6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -370,6 +370,7 @@ CODE You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2019/04/29 (1.70) - fixed ImDrawList rectangles with thick lines (>1.0f) not being as thick as requested. If you have custom rendering using rectangles with thick lines, they will appear thicker now. + - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! @@ -6438,11 +6439,6 @@ ImVec2 ImGui::GetContentRegionAvail() return GetContentRegionMaxScreen() - window->DC.CursorPos; } -float ImGui::GetContentRegionAvailWidth() -{ - return GetContentRegionAvail().x; -} - // In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { diff --git a/imgui.h b/imgui.h index d10df2f0..62af07d7 100644 --- a/imgui.h +++ b/imgui.h @@ -288,7 +288,6 @@ namespace ImGui // - Those functions are bound to be redesigned soon (they are confusing, incomplete and return values in local window coordinates which increases confusion) IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() - IMGUI_API float GetContentRegionAvailWidth(); // == GetContentRegionAvail().x IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates IMGUI_API float GetWindowContentRegionWidth(); // @@ -1529,6 +1528,8 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.70 (from May 2019) + static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.69 (from Mar 2019) static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.66 (from Sep 2018) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 33f33af8..75f690ce 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1752,9 +1752,9 @@ static void ShowDemoWindowLayout() ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::DragFloat("float##2", &f); - ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); + ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)"); ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); - ImGui::SetNextItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.5f); ImGui::DragFloat("float##3", &f); ImGui::Text("SetNextItemWidth/PushItemWidth(-100)"); From 5c1cd5c8c7f0bbf016c741867c3a9fd99926f438 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Apr 2019 22:15:59 +0200 Subject: [PATCH 310/566] ImDrawCallback_ResetRenderState, Examples: Added support for reset render state callback. (#2037, #1639, #2452) --- docs/CHANGELOG.txt | 5 ++ examples/imgui_impl_allegro5.cpp | 47 +++++++----- examples/imgui_impl_dx10.cpp | 68 ++++++++++-------- examples/imgui_impl_dx11.cpp | 70 ++++++++++-------- examples/imgui_impl_dx12.cpp | 118 ++++++++++++++++-------------- examples/imgui_impl_dx9.cpp | 119 +++++++++++++++++-------------- examples/imgui_impl_opengl2.cpp | 49 ++++++++----- examples/imgui_impl_opengl3.cpp | 107 +++++++++++++++------------ examples/imgui_impl_vulkan.cpp | 94 +++++++++++++----------- imgui.h | 11 ++- 10 files changed, 394 insertions(+), 294 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fb41b3b6..2e37f985 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,11 @@ Breaking Changes: on them but it is possible you have!). Other Changes: +- ImDrawList: Added ImDrawCallback_ResetRenderState, a special ImDrawList::AddCallback() value + to request the renderer back-end to reset its render state. (#2037, #1639, #2452) +- Examples: Added support for ImDrawCallback_ResetRenderState in all renderer back-ends. + Each renderer code setting up initial render state has been moved to a function so it could + be called at the start of rendering and when a ResetRenderState is requested. (#2037, #1639, #2452) - InputText: Fixed selection background starts rendering one frame after the cursor movement when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] - InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index ca0444ff..b517fcfe 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -60,23 +60,9 @@ struct ImDrawVertAllegro ALLEGRO_COLOR col; }; -// Render function. -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) -void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) +static void ImGui_ImplAllegro5_SetupRenderState(ImDrawData* draw_data) { - // Avoid rendering when minimized - if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) - return; - - // Backup Allegro state that will be modified - ALLEGRO_TRANSFORM last_transform = *al_get_current_transform(); - ALLEGRO_TRANSFORM last_projection_transform = *al_get_current_projection_transform(); - int last_clip_x, last_clip_y, last_clip_w, last_clip_h; - al_get_clipping_rectangle(&last_clip_x, &last_clip_y, &last_clip_w, &last_clip_h); - int last_blender_op, last_blender_src, last_blender_dst; - al_get_blender(&last_blender_op, &last_blender_src, &last_blender_dst); - - // Setup render state + // Setup blending al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA); // Setup orthographic projection matrix @@ -92,7 +78,28 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) al_orthographic_transform(&transform, L, T, 1.0f, R, B, -1.0f); al_use_projection_transform(&transform); } +} + +// Render function. +// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) +void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) +{ + // Avoid rendering when minimized + if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) + return; + + // Backup Allegro state that will be modified + ALLEGRO_TRANSFORM last_transform = *al_get_current_transform(); + ALLEGRO_TRANSFORM last_projection_transform = *al_get_current_projection_transform(); + int last_clip_x, last_clip_y, last_clip_w, last_clip_h; + al_get_clipping_rectangle(&last_clip_x, &last_clip_y, &last_clip_w, &last_clip_h); + int last_blender_op, last_blender_src, last_blender_dst; + al_get_blender(&last_blender_op, &last_blender_src, &last_blender_dst); + + // Setup desired render state + ImGui_ImplAllegro5_SetupRenderState(draw_data); + // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -135,10 +142,16 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplAllegro5_SetupRenderState(draw_data); + else + pcmd->UserCallback(cmd_list, pcmd); } else { + // Draw ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->TextureId; al_set_clipping_rectangle(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y, pcmd->ClipRect.z - pcmd->ClipRect.x, pcmd->ClipRect.w - pcmd->ClipRect.y); al_draw_prim(&vertices[0], g_VertexDecl, texture, idx_offset, idx_offset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST); diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 7bb58859..532d5542 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -55,6 +55,37 @@ struct VERTEX_CONSTANT_BUFFER float mvp[4][4]; }; +static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* ctx) +{ + // Setup viewport + D3D10_VIEWPORT vp; + memset(&vp, 0, sizeof(D3D10_VIEWPORT)); + vp.Width = (UINT)draw_data->DisplaySize.x; + vp.Height = (UINT)draw_data->DisplaySize.y; + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + vp.TopLeftX = vp.TopLeftY = 0; + ctx->RSSetViewports(1, &vp); + + // Bind shader and vertex buffers + unsigned int stride = sizeof(ImDrawVert); + unsigned int offset = 0; + ctx->IASetInputLayout(g_pInputLayout); + ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset); + ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); + ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx->VSSetShader(g_pVertexShader); + ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); + ctx->PSSetShader(g_pPixelShader); + ctx->PSSetSamplers(0, 1, &g_pFontSampler); + + // Setup render state + const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; + ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff); + ctx->OMSetDepthStencilState(g_pDepthStencilState, 0); + ctx->RSSetState(g_pRasterizerState); +} + // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) @@ -172,33 +203,8 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); ctx->IAGetInputLayout(&old.InputLayout); - // Setup viewport - D3D10_VIEWPORT vp; - memset(&vp, 0, sizeof(D3D10_VIEWPORT)); - vp.Width = (UINT)draw_data->DisplaySize.x; - vp.Height = (UINT)draw_data->DisplaySize.y; - vp.MinDepth = 0.0f; - vp.MaxDepth = 1.0f; - vp.TopLeftX = vp.TopLeftY = 0; - ctx->RSSetViewports(1, &vp); - - // Bind shader and vertex buffers - unsigned int stride = sizeof(ImDrawVert); - unsigned int offset = 0; - ctx->IASetInputLayout(g_pInputLayout); - ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset); - ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); - ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - ctx->VSSetShader(g_pVertexShader); - ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); - ctx->PSSetShader(g_pPixelShader); - ctx->PSSetSamplers(0, 1, &g_pFontSampler); - - // Setup render state - const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; - ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff); - ctx->OMSetDepthStencilState(g_pDepthStencilState, 0); - ctx->RSSetState(g_pRasterizerState); + // Setup desired DX state + ImGui_ImplDX10_SetupRenderState(draw_data, ctx); // Render command lists int vtx_offset = 0; @@ -212,8 +218,12 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { - // User callback (registered via ImDrawList::AddCallback) - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplDX10_SetupRenderState(draw_data, ctx); + else + pcmd->UserCallback(cmd_list, pcmd); } else { diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index e8d022f6..01362bd2 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -55,6 +55,37 @@ struct VERTEX_CONSTANT_BUFFER float mvp[4][4]; }; +static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* ctx) +{ + // Setup viewport + D3D11_VIEWPORT vp; + memset(&vp, 0, sizeof(D3D11_VIEWPORT)); + vp.Width = draw_data->DisplaySize.x; + vp.Height = draw_data->DisplaySize.y; + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + vp.TopLeftX = vp.TopLeftY = 0; + ctx->RSSetViewports(1, &vp); + + // Setup shader and vertex buffers + unsigned int stride = sizeof(ImDrawVert); + unsigned int offset = 0; + ctx->IASetInputLayout(g_pInputLayout); + ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset); + ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); + ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx->VSSetShader(g_pVertexShader, NULL, 0); + ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); + ctx->PSSetShader(g_pPixelShader, NULL, 0); + ctx->PSSetSamplers(0, 1, &g_pFontSampler); + + // Setup blend state + const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; + ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff); + ctx->OMSetDepthStencilState(g_pDepthStencilState, 0); + ctx->RSSetState(g_pRasterizerState); +} + // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) @@ -177,33 +208,8 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); ctx->IAGetInputLayout(&old.InputLayout); - // Setup viewport - D3D11_VIEWPORT vp; - memset(&vp, 0, sizeof(D3D11_VIEWPORT)); - vp.Width = draw_data->DisplaySize.x; - vp.Height = draw_data->DisplaySize.y; - vp.MinDepth = 0.0f; - vp.MaxDepth = 1.0f; - vp.TopLeftX = vp.TopLeftY = 0; - ctx->RSSetViewports(1, &vp); - - // Bind shader and vertex buffers - unsigned int stride = sizeof(ImDrawVert); - unsigned int offset = 0; - ctx->IASetInputLayout(g_pInputLayout); - ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset); - ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); - ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - ctx->VSSetShader(g_pVertexShader, NULL, 0); - ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); - ctx->PSSetShader(g_pPixelShader, NULL, 0); - ctx->PSSetSamplers(0, 1, &g_pFontSampler); - - // Setup render state - const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; - ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff); - ctx->OMSetDepthStencilState(g_pDepthStencilState, 0); - ctx->RSSetState(g_pRasterizerState); + // Setup desired DX state + ImGui_ImplDX11_SetupRenderState(draw_data, ctx); // Render command lists int vtx_offset = 0; @@ -215,10 +221,14 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) + if (pcmd->UserCallback != NULL) { - // User callback (registered via ImDrawList::AddCallback) - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplDX11_SetupRenderState(draw_data, ctx); + else + pcmd->UserCallback(cmd_list, pcmd); } else { diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 45fb4c79..258a179b 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -58,6 +58,61 @@ struct VERTEX_CONSTANT_BUFFER float mvp[4][4]; }; +static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, FrameResources* fr) +{ + // Setup orthographic projection matrix into our constant buffer + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). + VERTEX_CONSTANT_BUFFER vertex_constant_buffer; + { + float L = draw_data->DisplayPos.x; + 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; + float mvp[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.5f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, + }; + memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp)); + } + + // Setup viewport + D3D12_VIEWPORT vp; + memset(&vp, 0, sizeof(D3D12_VIEWPORT)); + vp.Width = draw_data->DisplaySize.x; + vp.Height = draw_data->DisplaySize.y; + vp.MinDepth = 0.0f; + vp.MaxDepth = 1.0f; + vp.TopLeftX = vp.TopLeftY = 0.0f; + ctx->RSSetViewports(1, &vp); + + // Bind shader and vertex buffers + unsigned int stride = sizeof(ImDrawVert); + unsigned int offset = 0; + D3D12_VERTEX_BUFFER_VIEW vbv; + memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW)); + vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset; + vbv.SizeInBytes = fr->VertexBufferSize * stride; + vbv.StrideInBytes = stride; + ctx->IASetVertexBuffers(0, 1, &vbv); + D3D12_INDEX_BUFFER_VIEW ibv; + memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW)); + ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress(); + ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx); + ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; + ctx->IASetIndexBuffer(&ibv); + ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx->SetPipelineState(g_pPipelineState); + ctx->SetGraphicsRootSignature(g_pRootSignature); + ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); + + // Setup blend factor + const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; + ctx->OMSetBlendFactor(blend_factor); +} + // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx) @@ -140,57 +195,8 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL fr->VertexBuffer->Unmap(0, &range); fr->IndexBuffer->Unmap(0, &range); - // Setup orthographic projection matrix into our constant buffer - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). - VERTEX_CONSTANT_BUFFER vertex_constant_buffer; - { - float L = draw_data->DisplayPos.x; - 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; - float mvp[4][4] = - { - { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, - { 0.0f, 0.0f, 0.5f, 0.0f }, - { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, - }; - memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp)); - } - - // Setup viewport - D3D12_VIEWPORT vp; - memset(&vp, 0, sizeof(D3D12_VIEWPORT)); - vp.Width = draw_data->DisplaySize.x; - vp.Height = draw_data->DisplaySize.y; - vp.MinDepth = 0.0f; - vp.MaxDepth = 1.0f; - vp.TopLeftX = vp.TopLeftY = 0.0f; - ctx->RSSetViewports(1, &vp); - - // Bind shader and vertex buffers - unsigned int stride = sizeof(ImDrawVert); - unsigned int offset = 0; - D3D12_VERTEX_BUFFER_VIEW vbv; - memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW)); - vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset; - vbv.SizeInBytes = fr->VertexBufferSize * stride; - vbv.StrideInBytes = stride; - ctx->IASetVertexBuffers(0, 1, &vbv); - D3D12_INDEX_BUFFER_VIEW ibv; - memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW)); - ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress(); - ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx); - ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; - ctx->IASetIndexBuffer(&ibv); - ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - ctx->SetPipelineState(g_pPipelineState); - ctx->SetGraphicsRootSignature(g_pRootSignature); - ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); - - // Setup blend factor - const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; - ctx->OMSetBlendFactor(blend_factor); + // Setup desired DX state + ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); // Render command lists int vtx_offset = 0; @@ -202,10 +208,14 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) + if (pcmd->UserCallback != NULL) { - // User callback (registered via ImDrawList::AddCallback) - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); + else + pcmd->UserCallback(cmd_list, pcmd); } else { diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 566ea4ce..ab08551b 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -42,6 +42,62 @@ struct CUSTOMVERTEX }; #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) +static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) +{ + // Setup viewport + D3DVIEWPORT9 vp; + vp.X = vp.Y = 0; + vp.Width = (DWORD)draw_data->DisplaySize.x; + vp.Height = (DWORD)draw_data->DisplaySize.y; + vp.MinZ = 0.0f; + vp.MaxZ = 1.0f; + g_pd3dDevice->SetViewport(&vp); + + // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient) + g_pd3dDevice->SetPixelShader(NULL); + g_pd3dDevice->SetVertexShader(NULL); + g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); + g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, false); + g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); + g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true); + g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false); + g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); + g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); + g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); + g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, true); + g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); + g_pd3dDevice->SetRenderState(D3DRS_FOGENABLE, false); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); + g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); + g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + + // Setup orthographic projection matrix + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). + // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() + { + float L = draw_data->DisplayPos.x + 0.5f; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f; + float T = draw_data->DisplayPos.y + 0.5f; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f; + D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } }; + D3DMATRIX mat_projection = + { { { + 2.0f/(R-L), 0.0f, 0.0f, 0.0f, + 0.0f, 2.0f/(T-B), 0.0f, 0.0f, + 0.0f, 0.0f, 0.5f, 0.0f, + (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f + } } }; + g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity); + g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity); + g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection); + } +} + // Render function. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) @@ -111,58 +167,8 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) g_pd3dDevice->SetIndices(g_pIB); g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); - // Setup viewport - D3DVIEWPORT9 vp; - vp.X = vp.Y = 0; - vp.Width = (DWORD)draw_data->DisplaySize.x; - vp.Height = (DWORD)draw_data->DisplaySize.y; - vp.MinZ = 0.0f; - vp.MaxZ = 1.0f; - g_pd3dDevice->SetViewport(&vp); - - // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient) - g_pd3dDevice->SetPixelShader(NULL); - g_pd3dDevice->SetVertexShader(NULL); - g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); - g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, false); - g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); - g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true); - g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false); - g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); - g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); - g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); - g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, true); - g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); - g_pd3dDevice->SetRenderState(D3DRS_FOGENABLE, false); - g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); - g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); - g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); - g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); - g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); - g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); - - // Setup orthographic projection matrix - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). - // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() - { - float L = draw_data->DisplayPos.x + 0.5f; - float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f; - float T = draw_data->DisplayPos.y + 0.5f; - float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f; - D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } }; - D3DMATRIX mat_projection = - { { { - 2.0f/(R-L), 0.0f, 0.0f, 0.0f, - 0.0f, 2.0f/(T-B), 0.0f, 0.0f, - 0.0f, 0.0f, 0.5f, 0.0f, - (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f - } } }; - g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity); - g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity); - g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection); - } + // Setup desired DX state + ImGui_ImplDX9_SetupRenderState(draw_data); // Render command lists int vtx_offset = 0; @@ -174,9 +180,14 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) + if (pcmd->UserCallback != NULL) { - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplDX9_SetupRenderState(draw_data); + else + pcmd->UserCallback(cmd_list, pcmd); } else { diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index 17e8b728..9d7e335b 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -72,24 +72,9 @@ void ImGui_ImplOpenGL2_NewFrame() ImGui_ImplOpenGL2_CreateDeviceObjects(); } -// OpenGL2 Render function. -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) -// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. -void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) +static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height) { - // 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); - int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); - if (fb_width == 0 || fb_height == 0) - return; - - // We are using the OpenGL fixed pipeline to make the example code simpler to read! // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill. - GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); - GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); - GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); - GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); - glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); @@ -121,6 +106,28 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); +} + +// OpenGL2 Render function. +// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) +// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. +void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) +{ + // 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); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if (fb_width == 0 || fb_height == 0) + return; + + // Backup GL state + GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); + GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); + GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); + glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT); + + // Setup desired GL state + ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports @@ -141,8 +148,12 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { - // User callback (registered via ImDrawList::AddCallback) - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height); + else + pcmd->UserCallback(cmd_list, pcmd); } else { @@ -167,7 +178,7 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) } } - // Restore modified state + // Restore modified GL state glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 347da470..55849c5a 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -150,6 +150,56 @@ void ImGui_ImplOpenGL3_NewFrame() ImGui_ImplOpenGL3_CreateDeviceObjects(); } +static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object) +{ + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glEnable(GL_SCISSOR_TEST); +#ifdef GL_POLYGON_MODE + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); +#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). DisplayMin is typically (0,0) for single viewport apps. + glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); + float L = draw_data->DisplayPos.x; + 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; + const float ortho_projection[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f }, + }; + glUseProgram(g_ShaderHandle); + glUniform1i(g_AttribLocationTex, 0); + glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); +#ifdef GL_SAMPLER_BINDING + glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. +#endif + + (void)vertex_array_object; +#ifndef IMGUI_IMPL_OPENGL_ES2 + glBindVertexArray(vertex_array_object); +#endif + + // Bind vertex/index buffers and setup attributes for ImDrawVert + glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); + glEnableVertexAttribArray(g_AttribLocationVtxPos); + glEnableVertexAttribArray(g_AttribLocationVtxUV); + glEnableVertexAttribArray(g_AttribLocationVtxColor); + glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)); + glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); + glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); +} + // OpenGL3 Render function. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. @@ -195,55 +245,14 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) clip_origin_lower_left = false; #endif - // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill - glEnable(GL_BLEND); - glBlendEquation(GL_FUNC_ADD); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable(GL_CULL_FACE); - glDisable(GL_DEPTH_TEST); - glEnable(GL_SCISSOR_TEST); -#ifdef GL_POLYGON_MODE - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); -#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). DisplayMin is typically (0,0) for single viewport apps. - glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); - float L = draw_data->DisplayPos.x; - 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; - const float ortho_projection[4][4] = - { - { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, - { 0.0f, 0.0f, -1.0f, 0.0f }, - { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f }, - }; - glUseProgram(g_ShaderHandle); - glUniform1i(g_AttribLocationTex, 0); - glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); -#ifdef GL_SAMPLER_BINDING - glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. -#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. -#ifndef IMGUI_IMPL_OPENGL_ES2 GLuint vertex_array_object = 0; +#ifndef IMGUI_IMPL_OPENGL_ES2 glGenVertexArrays(1, &vertex_array_object); - glBindVertexArray(vertex_array_object); #endif - - // Bind vertex/index buffers and setup attributes for ImDrawVert - glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); - glEnableVertexAttribArray(g_AttribLocationVtxPos); - glEnableVertexAttribArray(g_AttribLocationVtxUV); - glEnableVertexAttribArray(g_AttribLocationVtxColor); - glVertexAttribPointer(g_AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)); - glVertexAttribPointer(g_AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); - glVertexAttribPointer(g_AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); + ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports @@ -262,10 +271,14 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) + if (pcmd->UserCallback != NULL) { - // User callback (registered via ImDrawList::AddCallback) - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); + else + pcmd->UserCallback(cmd_list, pcmd); } else { diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index e2da42ba..5e8d7d48 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -259,6 +259,49 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory p_buffer_size = new_size; } +static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkCommandBuffer command_buffer, ImGui_ImplVulkanH_FrameRenderBuffers* rb, int fb_width, int fb_height) +{ + // Bind pipeline and descriptor sets: + { + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_Pipeline); + VkDescriptorSet desc_set[1] = { g_DescriptorSet }; + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_PipelineLayout, 0, 1, desc_set, 0, NULL); + } + + // Bind Vertex And Index Buffer: + { + VkBuffer vertex_buffers[1] = { rb->VertexBuffer }; + VkDeviceSize vertex_offset[1] = { 0 }; + vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset); + vkCmdBindIndexBuffer(command_buffer, rb->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); + } + + // Setup viewport: + { + VkViewport viewport; + viewport.x = 0; + viewport.y = 0; + viewport.width = (float)fb_width; + viewport.height = (float)fb_height; + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.0f; + vkCmdSetViewport(command_buffer, 0, 1, &viewport); + } + + // Setup scale and translation: + // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps. + { + float scale[2]; + scale[0] = 2.0f / draw_data->DisplaySize.x; + scale[1] = 2.0f / draw_data->DisplaySize.y; + float translate[2]; + translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0]; + translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1]; + vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale); + vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate); + } +} + // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer) @@ -323,45 +366,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm vkUnmapMemory(v->Device, rb->IndexBufferMemory); } - // Bind pipeline and descriptor sets: - { - vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_Pipeline); - VkDescriptorSet desc_set[1] = { g_DescriptorSet }; - vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_PipelineLayout, 0, 1, desc_set, 0, NULL); - } - - // Bind Vertex And Index Buffer: - { - VkBuffer vertex_buffers[1] = { rb->VertexBuffer }; - VkDeviceSize vertex_offset[1] = { 0 }; - vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset); - vkCmdBindIndexBuffer(command_buffer, rb->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); - } - - // Setup viewport: - { - VkViewport viewport; - viewport.x = 0; - viewport.y = 0; - viewport.width = (float)fb_width; - viewport.height = (float)fb_height; - viewport.minDepth = 0.0f; - viewport.maxDepth = 1.0f; - vkCmdSetViewport(command_buffer, 0, 1, &viewport); - } - - // Setup scale and translation: - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps. - { - float scale[2]; - scale[0] = 2.0f / draw_data->DisplaySize.x; - scale[1] = 2.0f / draw_data->DisplaySize.y; - float translate[2]; - translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0]; - translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1]; - vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale); - vkCmdPushConstants(command_buffer, g_PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate); - } + // Setup desired Vulkan state + ImGui_ImplVulkan_SetupRenderState(draw_data, command_buffer, rb, fb_width, fb_height); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports @@ -376,10 +382,14 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) + if (pcmd->UserCallback != NULL) { - // User callback (registered via ImDrawList::AddCallback) - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplVulkan_SetupRenderState(draw_data, command_buffer, rb, fb_width, fb_height); + else + pcmd->UserCallback(cmd_list, pcmd); } else { diff --git a/imgui.h b/imgui.h index 62af07d7..f2c44e69 100644 --- a/imgui.h +++ b/imgui.h @@ -1759,11 +1759,18 @@ struct ImColor // Draw callbacks for advanced uses. // NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, -// you can poke into the draw list for that! Draw callback may be useful for example to: A) Change your GPU render state, -// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +// you can poke into the draw list for that! Draw callback may be useful for example to: +// A) Change your GPU render state, +// B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); +// Special Draw Callback value to request renderer back-end to reset the graphics/render state. +// The renderer back-end needs to handle this special value, otherwise it will crash trying to call a function at this address. +// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored. +// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call). +#define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) + // Typically, 1 command = 1 GPU draw call (unless command is a callback) struct ImDrawCmd { From 7c6ba3a1da6b692d4a53fac65825c16e9355ef16 Mon Sep 17 00:00:00 2001 From: Max Thrun Date: Fri, 29 Mar 2019 11:11:55 -0700 Subject: [PATCH 311/566] ImDrawCallback_ResetRenderState: Added Metal. --- docs/CHANGELOG.txt | 6 ++-- examples/imgui_impl_metal.mm | 58 +++++++++++++++++++++++++----------- 2 files changed, 43 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2e37f985..86fd1a90 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,9 +47,9 @@ Breaking Changes: Other Changes: - ImDrawList: Added ImDrawCallback_ResetRenderState, a special ImDrawList::AddCallback() value to request the renderer back-end to reset its render state. (#2037, #1639, #2452) -- Examples: Added support for ImDrawCallback_ResetRenderState in all renderer back-ends. - Each renderer code setting up initial render state has been moved to a function so it could - be called at the start of rendering and when a ResetRenderState is requested. (#2037, #1639, #2452) + Examples: Added support for ImDrawCallback_ResetRenderState in all renderer back-ends. Each + renderer code setting up initial render state has been moved to a function so it could be + called at the start of rendering and when a ResetRenderState is requested. [@ocornut, @bear24rw] - InputText: Fixed selection background starts rendering one frame after the cursor movement when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] - InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index c559590b..c49c286c 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -56,6 +56,12 @@ - (void)enqueueReusableBuffer:(MetalBuffer *)buffer; - (id)renderPipelineStateForFrameAndDevice:(id)device; - (void)emptyRenderPipelineStateCache; +- (void)setupRenderState:(ImDrawData *)drawData + commandBuffer:(id)commandBuffer + commandEncoder:(id)commandEncoder + renderPipelineState:(id)renderPipelineState + vertexBuffer:(MetalBuffer *)vertexBuffer + vertexBufferOffset:(size_t)vertexBufferOffset; - (void)renderDrawData:(ImDrawData *)drawData commandBuffer:(id)commandBuffer commandEncoder:(id)commandEncoder; @@ -397,16 +403,13 @@ void ImGui_ImplMetal_DestroyDeviceObjects() [self.renderPipelineStateCache removeAllObjects]; } -- (void)renderDrawData:(ImDrawData *)drawData - commandBuffer:(id)commandBuffer - commandEncoder:(id)commandEncoder +- (void)setupRenderState:(ImDrawData *)drawData + commandBuffer:(id)commandBuffer + commandEncoder:(id)commandEncoder + renderPipelineState:(id)renderPipelineState + vertexBuffer:(MetalBuffer *)vertexBuffer + vertexBufferOffset:(size_t)vertexBufferOffset { - // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x); - int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y); - if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0) - return; - [commandEncoder setCullMode:MTLCullModeNone]; [commandEncoder setDepthStencilState:g_sharedMetalContext.depthStencilState]; @@ -417,12 +420,13 @@ void ImGui_ImplMetal_DestroyDeviceObjects() { .originX = 0.0, .originY = 0.0, - .width = double(fb_width), - .height = double(fb_height), + .width = (double)(drawData->DisplaySize.x * drawData->FramebufferScale.x), + .height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y), .znear = 0.0, .zfar = 1.0 }; [commandEncoder setViewport:viewport]; + float L = drawData->DisplayPos.x; float R = drawData->DisplayPos.x + drawData->DisplaySize.x; float T = drawData->DisplayPos.y; @@ -436,18 +440,32 @@ void ImGui_ImplMetal_DestroyDeviceObjects() { 0.0f, 0.0f, 1/(F-N), 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f }, }; - [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1]; + [commandEncoder setRenderPipelineState:renderPipelineState]; + + [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0]; + [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0]; +} + +- (void)renderDrawData:(ImDrawData *)drawData + commandBuffer:(id)commandBuffer + commandEncoder:(id)commandEncoder +{ + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x); + int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0) + return; + + id renderPipelineState = [self renderPipelineStateForFrameAndDevice:commandBuffer.device]; + size_t vertexBufferLength = drawData->TotalVtxCount * sizeof(ImDrawVert); size_t indexBufferLength = drawData->TotalIdxCount * sizeof(ImDrawIdx); MetalBuffer* vertexBuffer = [self dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; MetalBuffer* indexBuffer = [self dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; - id renderPipelineState = [self renderPipelineStateForFrameAndDevice:commandBuffer.device]; - [commandEncoder setRenderPipelineState:renderPipelineState]; - - [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0]; + [self setupRenderState:drawData commandBuffer:commandBuffer commandEncoder:commandEncoder renderPipelineState:renderPipelineState vertexBuffer:vertexBuffer vertexBufferOffset:0]; // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports @@ -471,8 +489,12 @@ void ImGui_ImplMetal_DestroyDeviceObjects() const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { - // User callback (registered via ImDrawList::AddCallback) - pcmd->UserCallback(cmd_list, pcmd); + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + [self setupRenderState:drawData commandBuffer:commandBuffer commandEncoder:commandEncoder renderPipelineState:renderPipelineState vertexBuffer:vertexBuffer vertexBufferOffset:vertexBufferOffset]; + else + pcmd->UserCallback(cmd_list, pcmd); } else { From ae405b83a4cbd989f449fbd4f7ab715129231b2d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Apr 2019 22:28:29 +0200 Subject: [PATCH 312/566] Examples: Added missing per-renderer local changelogs. (#2037, #1639, #2452) --- examples/imgui_impl_allegro5.cpp | 1 + examples/imgui_impl_dx10.cpp | 1 + examples/imgui_impl_dx11.cpp | 1 + examples/imgui_impl_dx12.cpp | 1 + examples/imgui_impl_dx9.cpp | 1 + examples/imgui_impl_metal.mm | 1 + examples/imgui_impl_opengl2.cpp | 1 + examples/imgui_impl_opengl3.cpp | 1 + examples/imgui_impl_vulkan.cpp | 5 +++-- 9 files changed, 11 insertions(+), 2 deletions(-) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index b517fcfe..b05fa2a3 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: Renderer: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-11-30: Platform: Added touchscreen support. // 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window. // 2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12). diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 532d5542..8d2c647d 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -10,6 +10,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions. diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 01362bd2..9a44d6ae 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -10,6 +10,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility. diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 258a179b..358b2e55 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Various minor tidying up. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index ab08551b..f375c390 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -10,6 +10,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index c49c286c..c4947893 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -10,6 +10,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-07-05: Metal: Added new Metal backend implementation. diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index 9d7e335b..e1584a16 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -18,6 +18,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications. diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 55849c5a..364b9ccf 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. // 2019-03-15: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 5e8d7d48..e5c95079 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -20,8 +20,9 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-XX-XX: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). -// 2019-XX-XX: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. +// 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). +// 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. From a1c432d1adcc37cf72975f35b22d6bd5a1c516e9 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 27 Apr 2019 17:11:06 +0200 Subject: [PATCH 313/566] Internals: SettingsHandlerWindow_ReadLine uses context parameter. --- imgui.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5d7a29d6..e5448882 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9374,21 +9374,22 @@ static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler* return (void*)settings; } -static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +static void SettingsHandlerWindow_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void* entry, const char* line) { + ImGuiContext& g = *ctx; ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; float x, y; int i; if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); - else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize); + else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } -static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { // Gather data from windows that were active during this session // (if a window wasn't opened in this session we preserve its settings) - ImGuiContext& g = *imgui_ctx; + ImGuiContext& g = *ctx; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; From ce19cb465f7b509b9bde9347cc1094bfabfae1e7 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 2 May 2019 16:29:40 +0200 Subject: [PATCH 314/566] Internals: Rename GetContentRegionMaxScreen() -> GetWorkRectMax(). At this point this is mostly useful to facilitate merge of other branches. --- imgui.cpp | 10 +++++----- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e5448882..96f2caec 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2983,7 +2983,7 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) ImGuiWindow* window = GImGui->CurrentWindow; if (wrap_pos_x == 0.0f) - wrap_pos_x = GetContentRegionMaxScreen().x; + wrap_pos_x = GetWorkRectMax().x; else if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space @@ -5808,7 +5808,7 @@ float ImGui::GetNextItemWidth() } if (w < 0.0f) { - float region_max_x = GetContentRegionMaxScreen().x; + float region_max_x = GetWorkRectMax().x; w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); } w = (float)(int)w; @@ -5836,7 +5836,7 @@ ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) ImVec2 region_max; if (size.x < 0.0f || size.y < 0.0f) - region_max = GetContentRegionMaxScreen(); + region_max = GetWorkRectMax(); if (size.x == 0.0f) size.x = default_w; @@ -6424,7 +6424,7 @@ ImVec2 ImGui::GetContentRegionMax() } // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. -ImVec2 ImGui::GetContentRegionMaxScreen() +ImVec2 ImGui::GetWorkRectMax() { ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max; @@ -6436,7 +6436,7 @@ ImVec2 ImGui::GetContentRegionMaxScreen() ImVec2 ImGui::GetContentRegionAvail() { ImGuiWindow* window = GImGui->CurrentWindow; - return GetContentRegionMaxScreen() - window->DC.CursorPos; + return GetWorkRectMax() - window->DC.CursorPos; } // In window space (not screen space!) diff --git a/imgui_internal.h b/imgui_internal.h index 23b95257..0aacd0fd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1458,7 +1458,7 @@ namespace ImGui IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); IMGUI_API bool IsItemToggledSelection(); // was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) - IMGUI_API ImVec2 GetContentRegionMaxScreen(); + IMGUI_API ImVec2 GetWorkRectMax(); // Logging/Capture IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 874b038a..894da543 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5044,7 +5044,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // We vertically grow up to current line height up the typical widget height. const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it const float frame_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); - ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(GetContentRegionMaxScreen().x, window->DC.CursorPos.y + frame_height)); + ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(GetWorkRectMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding From 86f92fe75605021a7440d72131a6aa7e27ca13a9 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 2 May 2019 20:19:53 +0200 Subject: [PATCH 315/566] Demo: Improved trees in columns demo. (#2136) --- docs/CHANGELOG.txt | 1 + imgui_demo.cpp | 39 +++++++++++++++++++++++++++++++-------- imgui_internal.h | 2 +- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 86fd1a90..d808f4c2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -89,6 +89,7 @@ Other Changes: - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. +- Demo: Improved trees in columns demo. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - Examples: Emscripten: Added Emscripten+SDL+GLES2 example. (#2494, #2492, #2351, #336) [@nicolasnoble, @redblobgames] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 75f690ce..0d9c50a1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2545,16 +2545,39 @@ static void ShowDemoWindowColumns() ImGui::TreePop(); } - bool node_open = ImGui::TreeNode("Tree within single cell"); - ImGui::SameLine(); HelpMarker("NB: Tree node must be poped before ending the cell. There's no storage of state per-cell."); - if (node_open) + if (ImGui::TreeNode("Tree")) { - ImGui::Columns(2, "tree items"); - ImGui::Separator(); - if (ImGui::TreeNode("Hello")) { ImGui::BulletText("Sailor"); ImGui::TreePop(); } ImGui::NextColumn(); - if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Marin"); ImGui::TreePop(); } ImGui::NextColumn(); + ImGui::Columns(2, "tree", true); + for (int x = 0; x < 3; x++) + { + bool open1 = ImGui::TreeNode((void*)(intptr_t)x, "Node%d", x); + ImGui::NextColumn(); + ImGui::Text("Node contents"); + ImGui::NextColumn(); + if (open1) + { + for (int y = 0; y < 5; y++) + { + bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y); + ImGui::NextColumn(); + ImGui::Text("Node contents"); + if (open2) + { + ImGui::Text("Even more contents"); + if (ImGui::TreeNode("Tree in column")) + { + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::TreePop(); + } + } + ImGui::NextColumn(); + if (open2) + ImGui::TreePop(); + } + ImGui::TreePop(); + } + } ImGui::Columns(1); - ImGui::Separator(); ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index 0aacd0fd..4130ab8a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -346,7 +346,7 @@ enum ImGuiSelectableFlagsPrivate_ ImGuiSelectableFlags_NoHoldingActiveID = 1 << 10, ImGuiSelectableFlags_PressedOnClick = 1 << 11, ImGuiSelectableFlags_PressedOnRelease = 1 << 12, - ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 13, + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 13, // FIXME: We may be able to remove this (added in 6251d379 for menus) ImGuiSelectableFlags_AllowItemOverlap = 1 << 14 }; From 2dc81057ec4e5fbd97d06044967550b5c41b5387 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 May 2019 14:28:57 +0200 Subject: [PATCH 316/566] Selectable: With ImGuiSelectableFlags_AllowDoubleClick doesn't return true on the mouse button releas efollowing the double-click. Only first mouse release + second mouse down (double-click) returns true. Likewise for internal ButtonBehavior() with both _PressedOnClickRelease | _PressedOnDoubleClick. (#2503) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 3 +++ imgui.h | 3 ++- imgui_widgets.cpp | 15 +++++++++++---- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d808f4c2..045df875 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -74,6 +74,9 @@ Other Changes: clear the focus again. - Popups: Fixed right-click from closing all popups instead of aiming at the hovered popup level (regression in 1.67). +- Selectable: With ImGuiSelectableFlags_AllowDoubleClick doesn't return true on the mouse button release + following the double-click. Only first mouse release + second mouse down (double-click) returns true. + Likewise for internal ButtonBehavior() with both _PressedOnClickRelease | _PressedOnDoubleClick. (#2503) - GetMouseDragDelta(): also returns the delta on the mouse button released frame. (#2419) - GetMouseDragDelta(): verify that mouse positions are valid otherwise returns zero. - Inputs: Also add support for horizontal scroll with Shift+Mouse Wheel. (#2424, #1463) [@LucaRood] diff --git a/imgui.cpp b/imgui.cpp index 96f2caec..43afd235 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3282,6 +3282,7 @@ static void ImGui::UpdateMouseInputs() g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; + g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i]; g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; } @@ -3293,6 +3294,8 @@ static void ImGui::UpdateMouseInputs() g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x); g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y); } + if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i]) + g.IO.MouseDownWasDoubleClick[i] = false; if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation g.NavDisableMouseHover = false; } diff --git a/imgui.h b/imgui.h index f2c44e69..78e4c3d6 100644 --- a/imgui.h +++ b/imgui.h @@ -1435,7 +1435,8 @@ struct ImGuiIO bool MouseClicked[5]; // Mouse button went from !Down to Down bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? bool MouseReleased[5]; // Mouse button went from Down to !Down - bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. + bool MouseDownOwned[5]; // Track if button was clicked inside an imgui window. We don't request mouse capture from the application if click started outside ImGui bounds. + bool MouseDownWasDoubleClick[5]; // Track if button down was a double-click float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) float MouseDownDurationPrev[5]; // Previous time the mouse button has been down ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 894da543..f146920d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -429,6 +429,10 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // Frame N+6 (mouse button is released) - true - - true - // Frame N+7 (mouse button is released) - true - - - - //------------------------------------------------------------------------------------------------------------------------------------------------ +// Note that some combinations are supported, +// - PressedOnDragDropHold can generally be associated with any flag. +// - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported. +//------------------------------------------------------------------------------------------------------------------------------------------------ // The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set: // Repeat+ Repeat+ Repeat+ Repeat+ // PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick @@ -569,10 +573,13 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } else { - if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) - if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps - if (!g.DragDropActive) - pressed = true; + if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) && !g.DragDropActive) + { + bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[0]; + bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay; // Repeat mode trumps + if (!is_double_click_release && !is_repeating_already) + pressed = true; + } ClearActiveID(); } if (!(flags & ImGuiButtonFlags_NoNavFocus)) From e2166db282140867d96f24326897a2b04d99ed14 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 May 2019 15:06:06 +0200 Subject: [PATCH 317/566] Internals: Fixed incorrect repeat delay/rate calculation in IsMouseClicked() with repeat flag leading to involontary but thankfully doubling the rate. Using our standard function, making the multiplicator explicit. --- imgui.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 43afd235..361fa076 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4195,8 +4195,9 @@ bool ImGui::IsMouseClicked(int button, bool repeat) if (repeat && t > g.IO.KeyRepeatDelay) { - float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; - if ((ImFmod(t - delay, rate) > rate*0.5f) != (ImFmod(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) + // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold. + int amount = CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.5f); + if (amount > 0) return true; } From 9c1f02a42c402cd18af10fbc73985f5237d3f9da Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 May 2019 18:40:36 +0200 Subject: [PATCH 318/566] Misc: Made IMGUI_CHECKVERSION() macro also check for matching size of ImDrawIdx. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 10 +++++++--- imgui.h | 4 ++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 045df875..8b26cab7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -91,6 +91,7 @@ Other Changes: angles, also faster to output. (#2518) [@rmitton] - Misc: Added IM_MALLOC/IM_FREE macros mimicking IM_NEW/IM_DELETE so user doesn't need to revert to using the ImGui::MemAlloc()/MemFree() calls directly. +- Misc: Made IMGUI_CHECKVERSION() macro also check for matching size of ImDrawIdx. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. - Demo: Improved trees in columns demo. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized diff --git a/imgui.cpp b/imgui.cpp index 361fa076..19c0906b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3039,9 +3039,12 @@ void ImGui::SetCurrentContext(ImGuiContext* ctx) #endif } -// Helper function to verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit -// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. you may see different structures from what imgui.cpp sees which is highly problematic. -bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert) +// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui. +// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit +// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code +// may see different structures thanwhat imgui.cpp sees, which is problematic. +// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui. +bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) { bool error = false; if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); } @@ -3050,6 +3053,7 @@ bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, si if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); } if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); } if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); } + if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); } return !error; } diff --git a/imgui.h b/imgui.h index 78e4c3d6..17d9d4c3 100644 --- a/imgui.h +++ b/imgui.h @@ -48,7 +48,7 @@ Index of this file: // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.70 WIP" #define IMGUI_VERSION_NUM 16991 -#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) +#define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) // IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h) @@ -207,7 +207,7 @@ namespace ImGui IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context IMGUI_API ImGuiContext* GetCurrentContext(); IMGUI_API void SetCurrentContext(ImGuiContext* ctx); - IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert); + IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // Main IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) From 526e2303bc1bfec7ca98e1328c15ce835cb47bc5 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 May 2019 19:09:44 +0200 Subject: [PATCH 319/566] Window: Fixed SetNextWindowSizeConstraints() with non-rounded positions making windows drift. (#2067, #2530) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 2 ++ imgui.h | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8b26cab7..514c5d3c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,7 @@ Other Changes: highlight from parent menu items earlier than necessary while approaching the child menu. - Window: Close button is horizontally aligned with style.FramePadding.x. - Window: Fixed contents region being off by WindowBorderSize amount on the right when scrollbar is active. +- Window: Fixed SetNextWindowSizeConstraints() with non-rounded positions making windows drift. (#2067, 2530) - Popups: Closing a popup restores the focused/nav window in place at the time of the popup opening, instead of restoring the window that was in the window stack at the time of the OpenPopup call. (#2517) Among other things, this allows opening a popup while no window are focused, and pressing Escape to diff --git a/imgui.cpp b/imgui.cpp index 19c0906b..68ac63ac 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4648,6 +4648,8 @@ static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) g.NextWindowData.SizeCallback(&data); new_size = data.DesiredSize; } + new_size.x = ImFloor(new_size.x); + new_size.y = ImFloor(new_size.y); } // Minimum size diff --git a/imgui.h b/imgui.h index 17d9d4c3..774c1b51 100644 --- a/imgui.h +++ b/imgui.h @@ -269,7 +269,7 @@ namespace ImGui // Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() - IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints. IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() From 4f22a45cb58a40b92724c6fb29e1c1b574ea5a37 Mon Sep 17 00:00:00 2001 From: ibachar Date: Sat, 4 May 2019 15:54:02 +0300 Subject: [PATCH 320/566] Removed git merge leftovers --- examples/imgui_impl_dx11.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 80ea9959..dfc32b49 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -92,7 +92,6 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC ctx->OMSetDepthStencilState(g_pDepthStencilState, 0); ctx->RSSetState(g_pRasterizerState); } ->>>>>>> master // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) From 5ecc9d58654c73bef446be2fead03cfbcb13d728 Mon Sep 17 00:00:00 2001 From: Max Thrun Date: Wed, 1 May 2019 18:31:42 -0700 Subject: [PATCH 321/566] Examples: Metal: Add GLFW+Metal example --- examples/example_glfw_metal/Makefile | 44 +++++++ examples/example_glfw_metal/main.mm | 166 +++++++++++++++++++++++++++ 2 files changed, 210 insertions(+) create mode 100644 examples/example_glfw_metal/Makefile create mode 100644 examples/example_glfw_metal/main.mm diff --git a/examples/example_glfw_metal/Makefile b/examples/example_glfw_metal/Makefile new file mode 100644 index 00000000..35f17737 --- /dev/null +++ b/examples/example_glfw_metal/Makefile @@ -0,0 +1,44 @@ +# +# You will need GLFW (http://www.glfw.org): +# brew install glfw +# + +#CXX = g++ +#CXX = clang++ + +EXE = example_glfw_metal +SOURCES = main.mm +SOURCES += ../imgui_impl_glfw.cpp ../imgui_impl_metal.mm +SOURCES += ../../imgui.cpp ../../imgui_widgets.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) + +LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore +LIBS += -L/usr/local/lib -lglfw + +CXXFLAGS = -I../ -I../../ -I/usr/local/include +CXXFLAGS += -Wall -Wformat +CFLAGS = $(CXXFLAGS) + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../../%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:../%.mm + $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< + +%.o:%.mm + $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< + +all: $(EXE) + @echo Build complete + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm new file mode 100644 index 00000000..3b162afb --- /dev/null +++ b/examples/example_glfw_metal/main.mm @@ -0,0 +1,166 @@ +// ImGui - standalone example application for GLFW + Metal, using programmable pipeline +// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. + +#include "imgui.h" +#include "imgui_impl_glfw.h" +#include "imgui_impl_metal.h" + +#define GLFW_INCLUDE_NONE +#define GLFW_EXPOSE_NATIVE_COCOA +#include +#include + +#import +#import + +#include + +static void glfw_error_callback(int error, const char* description) +{ + fprintf(stderr, "Glfw Error %d: %s\n", error, description); +} + +int main(int, char**) +{ + // Setup Dear ImGui binding + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Read 'misc/fonts/README.txt' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != NULL); + + // Setup window + glfwSetErrorCallback(glfw_error_callback); + if (!glfwInit()) + return 1; + + // Create window with graphics context + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Metal example", NULL, NULL); + if (window == NULL) + return 1; + + id device = MTLCreateSystemDefaultDevice();; + id commandQueue = [device newCommandQueue]; + + ImGui_ImplGlfw_InitForOpenGL(window, true); + ImGui_ImplMetal_Init(device); + + NSWindow *nswin = glfwGetCocoaWindow(window); + CAMetalLayer *layer = [CAMetalLayer layer]; + layer.device = device; + layer.pixelFormat = MTLPixelFormatBGRA8Unorm; + nswin.contentView.layer = layer; + nswin.contentView.wantsLayer = YES; + + MTLRenderPassDescriptor *renderPassDescriptor = [MTLRenderPassDescriptor new]; + + bool show_demo_window = true; + bool show_another_window = false; + float clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; + + // Main loop + while (!glfwWindowShouldClose(window)) + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + glfwPollEvents(); + + int width, height; + glfwGetFramebufferSize(window, &width, &height); + layer.drawableSize = CGSizeMake(width, height); + id drawable = [layer nextDrawable]; + + id commandBuffer = [commandQueue commandBuffer]; + renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0], clear_color[1], clear_color[2], clear_color[3]); + renderPassDescriptor.colorAttachments[0].texture = drawable.texture; + renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear; + renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore; + id renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; + [renderEncoder pushDebugGroup:@"ImGui demo"]; + + // Start the Dear ImGui frame + ImGui_ImplMetal_NewFrame(renderPassDescriptor); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + ImGui_ImplMetal_RenderDrawData(ImGui::GetDrawData(), commandBuffer, renderEncoder); + + [renderEncoder popDebugGroup]; + [renderEncoder endEncoding]; + + [commandBuffer presentDrawable:drawable]; + [commandBuffer commit]; + } + + // Cleanup + ImGui_ImplMetal_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + ImGui::DestroyContext(); + + glfwDestroyWindow(window); + glfwTerminate(); + + return 0; +} From 6c196cf4324cd1bba483031373af425fed4af25a Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 May 2019 10:02:59 +0200 Subject: [PATCH 322/566] Examples Readme and Changelog tweaks, added #2527, re-ordered examples/README alphabetically. --- docs/CHANGELOG.txt | 14 ++--- examples/README.txt | 75 +++++++++++++++----------- examples/example_glut_opengl2/main.cpp | 1 + examples/imgui_impl_glut.cpp | 1 + examples/imgui_impl_glut.h | 1 + imgui.cpp | 2 +- 6 files changed, 56 insertions(+), 38 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 514c5d3c..1e4d8a23 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -34,8 +34,9 @@ HOW TO UPDATE? ----------------------------------------------------------------------- Breaking Changes: -- ImDrawList: Fixed rectangles with thick lines (>1.0f) not being as thick as requested. (#2518) - If you have custom rendering using thick lines, they will appear thicker now. +- ImDrawList: Improved algorithm for mitre joints on thick lines, preserving correct thickness + up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, + they will appear a little thicker now. (#2518) [@rmitton] - Obsoleted GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function. - Examples: Vulkan: Added MinImageCount/ImageCount fields in ImGui_ImplVulkan_InitInfo, required @@ -50,8 +51,8 @@ Other Changes: Examples: Added support for ImDrawCallback_ResetRenderState in all renderer back-ends. Each renderer code setting up initial render state has been moved to a function so it could be called at the start of rendering and when a ResetRenderState is requested. [@ocornut, @bear24rw] -- InputText: Fixed selection background starts rendering one frame after the cursor movement - when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] +- InputText: Fixed selection background rendering one frame after the cursor movement when + first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] - InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) - InputText: Fixed ImGuiInputTextFlags_AllowTabInput leading to two tabs characters being inserted if the back-end provided both Key and Character input. (#2467, #1336) @@ -68,7 +69,7 @@ Other Changes: highlight from parent menu items earlier than necessary while approaching the child menu. - Window: Close button is horizontally aligned with style.FramePadding.x. - Window: Fixed contents region being off by WindowBorderSize amount on the right when scrollbar is active. -- Window: Fixed SetNextWindowSizeConstraints() with non-rounded positions making windows drift. (#2067, 2530) +- Window: Fixed SetNextWindowSizeConstraints() with non-rounded positions making windows drift. (#2067, #2530) - Popups: Closing a popup restores the focused/nav window in place at the time of the popup opening, instead of restoring the window that was in the window stack at the time of the OpenPopup call. (#2517) Among other things, this allows opening a popup while no window are focused, and pressing Escape to @@ -97,8 +98,9 @@ Other Changes: - Demo: Improved trees in columns demo. - Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) -- Examples: Emscripten: Added Emscripten+SDL+GLES2 example. (#2494, #2492, #2351, #336) [@nicolasnoble, @redblobgames] - Examples: SDL: Added support for SDL_GameController gamepads (enable with ImGuiConfigFlags_NavEnableGamepad). (#2509) [@DJLink] +- Examples: Emscripten: Added Emscripten+SDL+GLES2 example. (#2494, #2492, #2351, #336) [@nicolasnoble, @redblobgames] +- Examples: Metal: Added Glfw+Metal example. (#2527) [@bear24rw] - Examples: OpenGL3: Minor tweaks + not calling glBindBuffer more than necessary in the render loop. - Examples: Vulkan: Fixed in-flight buffers issues when using multi-viewports. (#2461, #2348, #2378, #2097) - Examples: Vulkan: Added missing support for 32-bit indices (#define ImDrawIdx unsigned int). diff --git a/examples/README.txt b/examples/README.txt index cd60733c..6a34c076 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -91,7 +91,7 @@ Most the example bindings are split in 2 parts: This is counter-intuitive, but this will get you running faster! Once you better understand how imgui works and is bound, you can rewrite the code using your own systems. - - Road-map: Dear ImGui 1.70 (WIP currently in the "viewport" branch) will allows imgui windows to be + - Road-map: Dear ImGui 1.80 (WIP currently in the "docking" branch) will allows imgui windows to be seamlessly detached from the main application window. This is achieved using an extra layer to the platform and renderer bindings, which allows imgui to communicate platform-specific requests. If you decide to use unmodified imgui_impl_xxxx.cpp files, you will automatically benefit from @@ -101,7 +101,7 @@ Most the example bindings are split in 2 parts: List of Platforms Bindings in this repository: imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ - imgui_impl_osx.mm ; macOS native API + imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl back-ends) imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org imgui_impl_win32.cpp ; Win32 native API (Windows) imgui_impl_glut.cpp ; GLUT/FreeGLUT (not recommended unless really miss the 90's) @@ -122,7 +122,7 @@ List of high-level Frameworks Bindings in this repository: (combine Platform + R imgui_impl_allegro5.cpp imgui_impl_marmalade.cpp -Note that Dear ImGui works with Emscripten. +Note that Dear ImGui works with Emscripten. The examples_emscripten/ app uses sdl.cpp + opengl3.cpp but other combinations are possible. Third-party framework, graphics API and languages bindings are listed at: @@ -151,40 +151,33 @@ Building: directly with a command-line compiler. -example_win32_directx9/ - DirectX9 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp - -example_win32_directx10/ - DirectX10 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx10.cpp - -example_win32_directx11/ - DirectX11 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx11.cpp - -example_win32_directx12/ - DirectX12 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp - This is quite long and tedious, because: DirectX12. +example_allegro5/ + Allegro 5 example. + = main.cpp + imgui_impl_allegro5.cpp example_apple_metal/ OSX & iOS + Metal. = main.m + imgui_impl_osx.mm + imgui_impl_metal.mm It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. - (NB: you may still want to use GLFW or SDL which will also support Windows, Linux along with OSX.) + (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms back-ends. + You may prefer to use the GLFW Or SDL back-ends, which will also support Windows and Linux.) example_apple_opengl2/ OSX + OpenGL2. = main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp - (NB: you may still want to use GLFW or SDL which will also support Windows, Linux along with OSX.) + (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms back-ends. + You may prefer to use the GLFW Or SDL back-ends, which will also support Windows and Linux.) example_empscripten: Emcripten + SDL2 + OpenGL3+/ES2/ES3 example. = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp - Note that other examples based on SDL or GLFW + GL could easily be modified to work with Emscripten. + Note that other examples based on SDL or GLFW + OpenGL could easily be modified to work with Emscripten. We provide this to make the Emscripten differences obvious, and have them not pollute all other examples. +example_glfw_metal/ + GLFW (Mac) + Vulkan example. + = main.mm + imgui_impl_glfw.cpp + imgui_impl_metal.mm. + example_glfw_opengl2/ GLFW + OpenGL2 example (legacy, fixed pipeline). = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp @@ -200,12 +193,24 @@ example_glfw_opengl3/ = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp This uses more modern OpenGL calls and custom shaders. Prefer using that if you are using modern OpenGL in your application (anything with shaders). + (Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent + source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different + from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.) example_glfw_vulkan/ GLFW (Win32, Mac, Linux) + Vulkan example. = main.cpp + imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp This is quite long and tedious, because: Vulkan. +example_glut_opengl2/ + GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2. + = main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp + Note that GLUT/FreeGLUT is largely obsolete software, prefer using GLFW or SDL. + +example_marmalade/ + Marmalade example using IwGx. + = main.cpp + imgui_impl_marmalade.cpp + example_sdl_opengl2/ SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline). = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp @@ -221,20 +226,28 @@ example_sdl_opengl3/ = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp This uses more modern OpenGL calls and custom shaders. Prefer using that if you are using modern OpenGL in your application (anything with shaders). + (Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent + source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different + from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.) example_sdl_vulkan/ SDL2 (Win32, Mac, Linux, etc.) + Vulkan example. = main.cpp + imgui_impl_sdl.cpp + imgui_impl_vulkan.cpp This is quite long and tedious, because: Vulkan. -example_allegro5/ - Allegro 5 example. - = main.cpp + imgui_impl_allegro5.cpp +example_win32_directx9/ + DirectX9 example, Windows only. + = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp -example_glut_opengl2/ - GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2. - = main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp +example_win32_directx10/ + DirectX10 example, Windows only. + = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx10.cpp -example_marmalade/ - Marmalade example using IwGx. - = main.cpp + imgui_impl_marmalade.cpp +example_win32_directx11/ + DirectX11 example, Windows only. + = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx11.cpp + +example_win32_directx12/ + DirectX12 example, Windows only. + = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp + This is quite long and tedious, because: DirectX12. diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 1089baee..e9fc1068 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -3,6 +3,7 @@ // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! +// !!! Prefer using GLFW Or SDL instead! #include "imgui.h" #include "../imgui_impl_glut.h" diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index 546a7b85..af42d4ae 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -3,6 +3,7 @@ // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! +// !!! Prefer using GLFW or SDL instead! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I diff --git a/examples/imgui_impl_glut.h b/examples/imgui_impl_glut.h index 89be9993..c6fcfd07 100644 --- a/examples/imgui_impl_glut.h +++ b/examples/imgui_impl_glut.h @@ -3,6 +3,7 @@ // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! +// !!! Prefer using GLFW or SDL instead! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I diff --git a/imgui.cpp b/imgui.cpp index 68ac63ac..1351d285 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,7 +369,7 @@ CODE When you are not sure about a 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. - - 2019/04/29 (1.70) - fixed ImDrawList rectangles with thick lines (>1.0f) not being as thick as requested. If you have custom rendering using rectangles with thick lines, they will appear thicker now. + - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). From d88121ff5b90013647d1b27ee7d5012f1d85a452 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 May 2019 10:11:02 +0200 Subject: [PATCH 323/566] Examples: DirectX9/10/11: Taking reference to device + subsequent merge of this in docking will fix DX9 issue #2524 --- examples/imgui_impl_dx10.cpp | 3 ++- examples/imgui_impl_dx11.cpp | 6 ++++-- examples/imgui_impl_dx9.cpp | 3 ++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 8d2c647d..235428fc 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -500,6 +500,7 @@ bool ImGui_ImplDX10_Init(ID3D10Device* device) } if (pDXGIDevice) pDXGIDevice->Release(); if (pDXGIAdapter) pDXGIAdapter->Release(); + g_pd3dDevice->AddRef(); return true; } @@ -508,7 +509,7 @@ void ImGui_ImplDX10_Shutdown() { ImGui_ImplDX10_InvalidateDeviceObjects(); if (g_pFactory) { g_pFactory->Release(); g_pFactory = NULL; } - g_pd3dDevice = NULL; + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } } void ImGui_ImplDX10_NewFrame() diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 9a44d6ae..18c32e6c 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -508,6 +508,8 @@ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_co } if (pDXGIDevice) pDXGIDevice->Release(); if (pDXGIAdapter) pDXGIAdapter->Release(); + g_pd3dDevice->AddRef(); + g_pd3dDeviceContext->AddRef(); return true; } @@ -516,8 +518,8 @@ void ImGui_ImplDX11_Shutdown() { ImGui_ImplDX11_InvalidateDeviceObjects(); if (g_pFactory) { g_pFactory->Release(); g_pFactory = NULL; } - g_pd3dDevice = NULL; - g_pd3dDeviceContext = NULL; + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } + if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } } void ImGui_ImplDX11_NewFrame() diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index f375c390..fd4522cd 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -219,13 +219,14 @@ bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) io.BackendRendererName = "imgui_impl_dx9"; g_pd3dDevice = device; + g_pd3dDevice->AddRef(); return true; } void ImGui_ImplDX9_Shutdown() { ImGui_ImplDX9_InvalidateDeviceObjects(); - g_pd3dDevice = NULL; + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } } static bool ImGui_ImplDX9_CreateFontsTexture() From 9ddb8493d5ee832fde957ec0a389ea9b083ebc6a Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 May 2019 12:07:29 +0200 Subject: [PATCH 324/566] Examples: DirectX9: Fixes for multi-viewports, destroying all swap chains. (#2520, #2502) --- examples/imgui_impl_dx9.cpp | 33 +++++++++++++++++++++++++++++---- examples/imgui_impl_dx9.h | 2 +- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index c5d0fc4f..b601c892 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -11,7 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2018-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. +// 2019-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. @@ -48,6 +48,8 @@ struct CUSTOMVERTEX // Forward Declarations static void ImGui_ImplDX9_InitPlatformInterface(); static void ImGui_ImplDX9_ShutdownPlatformInterface(); +static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows(); +static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows(); static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) { @@ -272,6 +274,7 @@ bool ImGui_ImplDX9_CreateDeviceObjects() return false; if (!ImGui_ImplDX9_CreateFontsTexture()) return false; + ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows(); return true; } @@ -282,6 +285,7 @@ void ImGui_ImplDX9_InvalidateDeviceObjects() if (g_pVB) { g_pVB->Release(); g_pVB = NULL; } if (g_pIB) { g_pIB->Release(); g_pIB = NULL; } if (g_FontTexture) { g_FontTexture->Release(); g_FontTexture = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. + ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows(); } void ImGui_ImplDX9_NewFrame() @@ -316,13 +320,16 @@ static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport) ZeroMemory(&data->d3dpp, sizeof(D3DPRESENT_PARAMETERS)); data->d3dpp.Windowed = TRUE; data->d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; + data->d3dpp.BackBufferWidth = (UINT)viewport->Size.x; + data->d3dpp.BackBufferHeight = (UINT)viewport->Size.y; data->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; data->d3dpp.hDeviceWindow = hWnd; data->d3dpp.EnableAutoDepthStencil = TRUE; data->d3dpp.AutoDepthStencilFormat = D3DFMT_D16; data->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync - g_pd3dDevice->CreateAdditionalSwapChain(&data->d3dpp, &data->SwapChain); + HRESULT hr = g_pd3dDevice->CreateAdditionalSwapChain(&data->d3dpp, &data->SwapChain); IM_UNUSED(hr); + IM_ASSERT(hr == D3D_OK); IM_ASSERT(data->SwapChain != NULL); } @@ -349,7 +356,8 @@ static void ImGui_ImplDX9_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) data->SwapChain = NULL; data->d3dpp.BackBufferWidth = (UINT)size.x; data->d3dpp.BackBufferHeight = (UINT)size.y; - g_pd3dDevice->CreateAdditionalSwapChain(&data->d3dpp, &data->SwapChain); + HRESULT hr = g_pd3dDevice->CreateAdditionalSwapChain(&data->d3dpp, &data->SwapChain); IM_UNUSED(hr); + IM_ASSERT(hr == D3D_OK); } } @@ -381,7 +389,8 @@ static void ImGui_ImplDX9_RenderWindow(ImGuiViewport* viewport, void*) static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*) { ImGuiViewportDataDx9* data = (ImGuiViewportDataDx9*)viewport->RendererUserData; - data->SwapChain->Present(NULL, NULL, data->d3dpp.hDeviceWindow, NULL, NULL); + HRESULT hr = data->SwapChain->Present(NULL, NULL, data->d3dpp.hDeviceWindow, NULL, NULL); + IM_ASSERT(hr == D3D_OK); } static void ImGui_ImplDX9_InitPlatformInterface() @@ -398,3 +407,19 @@ static void ImGui_ImplDX9_ShutdownPlatformInterface() { ImGui::DestroyPlatformWindows(); } + +static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows() +{ + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + for (int i = 1; i < platform_io.Viewports.Size; i++) + if (!platform_io.Viewports[i]->RendererUserData) + ImGui_ImplDX9_CreateWindow(platform_io.Viewports[i]); +} + +static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows() +{ + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + for (int i = 1; i < platform_io.Viewports.Size; i++) + if (platform_io.Viewports[i]->RendererUserData) + ImGui_ImplDX9_DestroyWindow(platform_io.Viewports[i]); +} diff --git a/examples/imgui_impl_dx9.h b/examples/imgui_impl_dx9.h index 86953684..bff71b08 100644 --- a/examples/imgui_impl_dx9.h +++ b/examples/imgui_impl_dx9.h @@ -19,5 +19,5 @@ IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing ImGui state. -IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); From e6c982509d899d2c276711e5d0999d59672d03c2 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 May 2019 12:12:32 +0200 Subject: [PATCH 325/566] Examples: DirectX9: Fixes for multi-viewports. Avoid using a depth/stencil target for secondary viewport. (#2520, #2502) --- examples/imgui_impl_dx9.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index b601c892..5abc68c6 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -324,7 +324,7 @@ static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport) data->d3dpp.BackBufferHeight = (UINT)viewport->Size.y; data->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; data->d3dpp.hDeviceWindow = hWnd; - data->d3dpp.EnableAutoDepthStencil = TRUE; + data->d3dpp.EnableAutoDepthStencil = FALSE; data->d3dpp.AutoDepthStencilFormat = D3DFMT_D16; data->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync @@ -368,22 +368,27 @@ static void ImGui_ImplDX9_RenderWindow(ImGuiViewport* viewport, void*) LPDIRECT3DSURFACE9 render_target = NULL; LPDIRECT3DSURFACE9 last_render_target = NULL; + LPDIRECT3DSURFACE9 last_depth_stencil = NULL; data->SwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &render_target); g_pd3dDevice->GetRenderTarget(0, &last_render_target); + g_pd3dDevice->GetDepthStencilSurface(&last_depth_stencil); g_pd3dDevice->SetRenderTarget(0, render_target); + g_pd3dDevice->SetDepthStencilSurface(NULL); if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear)) { D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f)); - g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); + g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, clear_col_dx, 1.0f, 0); } ImGui_ImplDX9_RenderDrawData(viewport->DrawData); // Restore render target g_pd3dDevice->SetRenderTarget(0, last_render_target); + g_pd3dDevice->SetDepthStencilSurface(last_depth_stencil); render_target->Release(); last_render_target->Release(); + if (last_depth_stencil) last_depth_stencil->Release(); } static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*) From d1d5075b66f93686954154ceaba7fe30abc41f4b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 May 2019 14:17:39 +0200 Subject: [PATCH 326/566] Version 1.70 --- docs/CHANGELOG.txt | 2 +- docs/TODO.txt | 14 ++++++++++++-- examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 10 files changed, 23 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1e4d8a23..cafaa6bb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -30,7 +30,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.70 WIP (In Progress) + VERSION 1.70 (Released 2019-05-06) ----------------------------------------------------------------------- Breaking Changes: diff --git a/docs/TODO.txt b/docs/TODO.txt index 2dbf1f0f..4c89c8e3 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -27,6 +27,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window: investigate better auto-positioning for new windows. - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - window/child: the first draw command of a child window could be moved into the current draw command of the parent window (unless child+tooltip?). + - window/child: border could be emitted in parent as well. - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - window/tab: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). - scrolling: while holding down a scrollbar, try to keep the same contents visible (at least while not moving mouse) @@ -65,6 +66,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: a way to represent "mixed" values, so e.g. all values replaced with **, including check-boxes, colors, etc. with support for multi-components widgets (e.g. SliderFloat3, make only "Y" mixed) - widgets: selectable: generic BeginSelectable()/EndSelectable() mechanism. - widgets: selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) + - widgets: checkbox with custom glyph inside frame. - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) @@ -170,6 +172,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - listbox: keyboard navigation. - listbox: disable capturing mouse wheel if the listbox has no scrolling. (#1681) - listbox: scrolling should track modified selection. + - listbox: future api should allow to enable horizontal scrolling (#2510) !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) - popups/modal: make modal title bar blink when trying to click outside the modal @@ -236,15 +239,19 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb) - drag and drop: drag tooltip hovering over source widget with IsItemHovered/SetTooltip flickers. + - drag and drop: fix/support/options for overlapping drag sources. - drag and drop: releasing a drop shows the "..." tooltip for one frame - since e13e598 (#1725) + - drag and drop: drag source on a group object (would need e.g. an invisible button covering group in EndGroup) https://twitter.com/paniq/status/1121446364909535233 - drag and drop: have some way to know when a drag begin from BeginDragDropSource() pov. - drag and drop: allow preview tooltip to be submitted from a different place than the drag source. (#1725) - drag and drop: allow using with other mouse buttons (where activeid won't be set). (#1637) - drag and drop: make it easier and provide a demo to have tooltip both are source and target site, with a more detailed one on target site (tooltip ordering problem) - - drag and drop: test with reordering nodes (in a list, or a tree node). (#143) + - drag and drop: demo with reordering nodes (in a list, or a tree node). (#143) - drag and drop: test integrating with os drag and drop (make it easy to do a naive WM_DROPFILE integration) + - drag and drop: allow for multiple payload types. (#143) - drag and drop: make payload optional? (#143) - - drag and drop: feedback when hovering a modal (cursor?) + - drag and drop: (#143) "both an in-process pointer and a promise to generate a serialized version, for whether the drag ends inside or outside the same process" + - drag and drop: feedback when hovering a region blocked by modal (mouse cursor "NO"?) - node/graph editor (#306) - pie menus patterns (#434) - markup: simple markup language for color change? (#902) @@ -267,6 +274,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font/draw: vertical and/or rotated text renderer (#705) - vertical is easier clipping wise - font/draw: need to be able to specify wrap start position. - font/draw: better reserve policy for large horizontal block of text (shouldn't reserve for all clipped lines) + - font/draw: underline, squiggle line rendering helpers. - font: optimization: for monospace font (like the default one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance (need to make sure TAB is still correct), would save on cache line. - font: add support for kerning, probably optional. A) perhaps default to (32..128)^2 matrix ~ 9K entries = 36KB, then hash for non-ascii?. B) or sparse lookup into per-char list? - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) @@ -309,6 +317,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - inputs: support track pad style scrolling & slider edit. - inputs/io: backspace and arrows in the context of a text input could use system repeat rate. - inputs/io: clarify/standardize/expose repeat rate and repeat delays (#1808) + - inputs: add mouse cursor for unavailable/no? IDC_NO/SDL_SYSTEM_CURSOR_NO. - misc: idle: expose "woken up" boolean (set by inputs) and/or animation time (for cursor blink) for back-end to be able stop refreshing easily. - misc: idle: if cursor blink if the _only_ visible animation, core imgui could rewrite vertex alpha to avoid CPU pass on ImGui:: calls. @@ -326,6 +335,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - remote: make a system like RemoteImGui first-class citizen/project (#75) - demo: find a way to demonstrate textures in the examples application, as it such a common issue for new users. + - demo: demonstrate using PushStyleVar() in more details. - demo: add vertical separator demo - demo: add virtual scrolling example? - demo: demonstrate Plot offset diff --git a/examples/README.txt b/examples/README.txt index 6a34c076..0be7ff6a 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.70 WIP + dear imgui, v1.70 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 1351d285..0bcaee50 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 WIP +// dear imgui, v1.70 // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index 774c1b51..423ba3ac 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.70 WIP +// dear imgui, v1.70 // (headers) // See imgui.cpp file for documentation. @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.70 WIP" -#define IMGUI_VERSION_NUM 16991 +#define IMGUI_VERSION "1.70" +#define IMGUI_VERSION_NUM 17000 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0d9c50a1..62196c64 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 WIP +// dear imgui, v1.70 // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5d493600..63d99a29 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 WIP +// dear imgui, v1.70 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 4130ab8a..cc98c20b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.70 WIP +// dear imgui, v1.70 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f146920d..5b3ea581 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 WIP +// dear imgui, v1.70 // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index a9f61cdb..5c475f2f 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.70 WIP +dear imgui, v1.70 (Font Readme) --------------------------------------- From 42fc563feda4acbac1c63336d4fdd1f50fd87a2d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 7 May 2019 16:36:08 +0200 Subject: [PATCH 327/566] Version 1.71 WIP + fixed minor typo --- docs/CHANGELOG.txt | 8 ++++++++ examples/README.txt | 4 ++-- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 9 files changed, 19 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cafaa6bb..9deed680 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -28,6 +28,14 @@ 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.71 (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + +Other Changes: + ----------------------------------------------------------------------- VERSION 1.70 (Released 2019-05-06) diff --git a/examples/README.txt b/examples/README.txt index 0be7ff6a..82d39ef1 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.70 + dear imgui, v1.71 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) @@ -175,7 +175,7 @@ example_empscripten: We provide this to make the Emscripten differences obvious, and have them not pollute all other examples. example_glfw_metal/ - GLFW (Mac) + Vulkan example. + GLFW (Mac) + Metal example. = main.mm + imgui_impl_glfw.cpp + imgui_impl_metal.mm. example_glfw_opengl2/ diff --git a/imgui.cpp b/imgui.cpp index 0bcaee50..1e6c8a3f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 +// dear imgui, v1.71 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index 423ba3ac..aafcb3a6 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.70 +// dear imgui, v1.71 WIP // (headers) // See imgui.cpp file for documentation. @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.70" -#define IMGUI_VERSION_NUM 17000 +#define IMGUI_VERSION "1.71" +#define IMGUI_VERSION_NUM 17001 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 62196c64..1f01cc4d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 +// dear imgui, v1.71 WIP // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 63d99a29..467555cf 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 +// dear imgui, v1.71 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index cc98c20b..7e91b5fc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.70 +// dear imgui, v1.71 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5b3ea581..42b28e09 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.70 +// dear imgui, v1.71 WIP // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index 5c475f2f..0fcc6c79 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.70 +dear imgui, v1.71 WIP (Font Readme) --------------------------------------- From 9bf3f910c8be3d2aaebcc61e61eb2d0dbfc944a9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 8 May 2019 18:20:13 +0200 Subject: [PATCH 328/566] Viewports: Fix to avoid SetNextWindowViewport being overrided by creation of a standalone viewport. (#2544, #1542) --- imgui.cpp | 63 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5ba23fd9..b5565e0b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10552,11 +10552,13 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) } } + bool lock_viewport = false; if (g.NextWindowData.ViewportCond) { // Code explicitly request a viewport window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId); window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet. + lock_viewport = true; } else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu)) { @@ -10590,40 +10592,45 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) window->Viewport = main_viewport; // Mark window as allowed to protrude outside of its viewport and into the current monitor - if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) - { - // We need to take account of the possibility that mouse may become invalid. - // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. - ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; - bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow); - bool mouse_valid = IsMousePosValid(&mouse_ref); - if ((window->Appearing || (flags & ImGuiWindowFlags_Tooltip)) && (!use_mouse_ref || mouse_valid)) - window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); - else - window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; - } - else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow)) + if (!lock_viewport) { - // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. - const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; - if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) + if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) { - // Steal/transfer ownership - //IMGUI_DEBUG_LOG("[%05d] Window '%s' steal Viewport %08X from Window '%s'\n", g.FrameCount, window->Name, window->Viewport->ID, window->Viewport->Window->Name); - window->Viewport->Window = window; - window->Viewport->ID = window->ID; - window->Viewport->LastNameHash = 0; + // We need to take account of the possibility that mouse may become invalid. + // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. + ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; + bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow); + bool mouse_valid = IsMousePosValid(&mouse_ref); + if ((window->Appearing || (flags & ImGuiWindowFlags_Tooltip)) && (!use_mouse_ref || mouse_valid)) + window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); + else + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; } - else if (!UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0])) // Merge? + else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow)) { - // New viewport - window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); + // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. + const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; + if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) + { + // Steal/transfer ownership + //IMGUI_DEBUG_LOG("[%05d] Window '%s' steal Viewport %08X from Window '%s'\n", g.FrameCount, window->Name, window->Viewport->ID, window->Viewport->Window->Name); + window->Viewport->Window = window; + window->Viewport->ID = window->ID; + window->Viewport->LastNameHash = 0; + } + else if (!UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0])) // Merge? + { + // New viewport + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); + } + } + else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) + { + // Regular (non-child, non-popup) windows by default are also allowed to protrude + // Child windows are kept contained within their parent. + window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; } } - // Regular (non-child, non-popup) windows by default are also allowed to protrude - // Child windows are kept contained within their parent. - else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) - window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; // Update flags window->ViewportOwned = (window == window->Viewport->Window); From 239c8732d72f147f9dc4124c73cca472f3cd6f0b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 8 May 2019 18:22:56 +0200 Subject: [PATCH 329/566] Viewports: Minor tweaks. (#2471) --- imgui.cpp | 11 +++++++++-- imgui.h | 3 ++- imgui_internal.h | 5 ----- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b5565e0b..8cde9de9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1099,6 +1099,7 @@ static void UpdateViewportsNewFrame(); static void UpdateViewportsEndFrame(); static void UpdateSelectWindowViewport(ImGuiWindow* window); static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport); +static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window); static void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* viewport); static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window); static int FindPlatformMonitorForPos(const ImVec2& pos); @@ -10233,6 +10234,12 @@ static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImG return true; } +static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); +} + // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) { @@ -10584,7 +10591,7 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) // We cannot test window->ViewportOwned as it set lower in the function. bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0); if (try_to_merge_into_host_viewport) - UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); + UpdateTryMergeWindowIntoHostViewports(window); } // Fallback to default viewport @@ -10618,7 +10625,7 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) window->Viewport->ID = window->ID; window->Viewport->LastNameHash = 0; } - else if (!UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0])) // Merge? + else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge? { // New viewport window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); diff --git a/imgui.h b/imgui.h index ae549e5d..895c6acd 100644 --- a/imgui.h +++ b/imgui.h @@ -2358,7 +2358,8 @@ enum ImGuiViewportFlags_ ImGuiViewportFlags_NoInputs = 1 << 4, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it. ImGuiViewportFlags_NoRendererClear = 1 << 5, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). ImGuiViewportFlags_TopMost = 1 << 6, // Platform Window: Display on top (for tooltips only) - ImGuiViewportFlags_Minimized = 1 << 7 // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + ImGuiViewportFlags_Minimized = 1 << 7, // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + ImGuiViewportFlags_CanHostOtherWindows = 1 << 8 // Main viewport: can host multiple imgui windows (secondary viewports are associated to a single window) }; // The viewports created and managed by imgui. The role of the platform back-end is to create the platform/OS windows corresponding to each viewport. diff --git a/imgui_internal.h b/imgui_internal.h index 2ec59755..743ede20 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -748,11 +748,6 @@ struct ImDrawDataBuilder IMGUI_API void FlattenIntoSingleLayer(); }; -enum ImGuiViewportFlagsPrivate_ -{ - ImGuiViewportFlags_CanHostOtherWindows = 1 << 10 // Normal viewports are associated to a single window. The main viewport can host multiple windows. -}; - // ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) // Note that every instance of ImGuiViewport is in fact a ImGuiViewportP. struct ImGuiViewportP : public ImGuiViewport From b7c2759f957dbcc6e48b6f12d59aeffb78ea0be7 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 May 2019 12:10:36 +0200 Subject: [PATCH 330/566] Columns: Fixed Separator from creating an extraneous draw command. Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 31 ++++++++++++++++++++++++++----- imgui_internal.h | 5 ++++- imgui_widgets.cpp | 12 ++++++------ 4 files changed, 38 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9deed680..8a137d4e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,8 @@ HOW TO UPDATE? Breaking Changes: Other Changes: +- Columns: Fixed Separator from creating an extraneous draw command. (#125) +- Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index 1e6c8a3f..1045ddd6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8400,13 +8400,13 @@ void ImGui::NextColumn() { // New column (columns 1+ cancels out IndentX) window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; - window->DrawList->ChannelsSetCurrent(columns->Current); + window->DrawList->ChannelsSetCurrent(columns->Current + 1); } else { // New row/line window->DC.ColumnsOffset.x = 0.0f; - window->DrawList->ChannelsSetCurrent(0); + window->DrawList->ChannelsSetCurrent(1); columns->Current = 0; columns->LineMinY = columns->LineMaxY; } @@ -8415,7 +8415,7 @@ void ImGui::NextColumn() window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrentLineTextBaseOffset = 0.0f; - PushColumnClipRect(); + PushColumnClipRect(columns->Current); PushItemWidth(GetColumnWidth() * 0.65f); // FIXME-COLUMNS: Move on columns setup } @@ -8543,6 +8543,25 @@ void ImGui::PushColumnClipRect(int column_index) PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); } +// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) +void ImGui::PushColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + window->DrawList->ChannelsSetCurrent(0); + int cmd_size = window->DrawList->CmdBuffer.Size; + PushClipRect(columns->BackupClipRect.Min, columns->BackupClipRect.Max, false); + IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd +} + +void ImGui::PopColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + window->DrawList->ChannelsSetCurrent(columns->Current + 1); + PopClipRect(); +} + ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) { // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. @@ -8593,6 +8612,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f); columns->BackupCursorPosY = window->DC.CursorPos.y; columns->BackupCursorMaxPosX = window->DC.CursorMaxPos.x; + columns->BackupClipRect = window->ClipRect; columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -8626,8 +8646,9 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag if (columns->Count > 1) { - window->DrawList->ChannelsSplit(columns->Count); - PushColumnClipRect(); + window->DrawList->ChannelsSplit(1 + columns->Count); + window->DrawList->ChannelsSetCurrent(1); + PushColumnClipRect(0); } PushItemWidth(GetColumnWidth() * 0.65f); } diff --git a/imgui_internal.h b/imgui_internal.h index 7e91b5fc..a56471db 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -683,6 +683,7 @@ struct ImGuiColumns float LineMinY, LineMaxY; float BackupCursorPosY; // Backup of CursorPos at the time of BeginColumns() float BackupCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() + ImRect BackupClipRect; ImVector Columns; ImGuiColumns() { Clear(); } @@ -1502,7 +1503,9 @@ namespace ImGui // New Columns API (FIXME-WIP) IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). IMGUI_API void EndColumns(); // close columns - IMGUI_API void PushColumnClipRect(int column_index = -1); + IMGUI_API void PushColumnClipRect(int column_index); + IMGUI_API void PushColumnsBackground(); + IMGUI_API void PopColumnsBackground(); IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count); IMGUI_API ImGuiColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 42b28e09..df9a7d87 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1216,7 +1216,7 @@ void ImGui::Separator() // Horizontal Separator if (window->DC.CurrentColumns) - PopClipRect(); + PushColumnsBackground(); float x1 = window->Pos.x; float x2 = window->Pos.x + window->Size.x; @@ -1228,7 +1228,7 @@ void ImGui::Separator() if (!ItemAdd(bb, 0)) { if (window->DC.CurrentColumns) - PushColumnClipRect(); + PopColumnsBackground(); return; } @@ -1239,7 +1239,7 @@ void ImGui::Separator() if (window->DC.CurrentColumns) { - PushColumnClipRect(); + PopColumnsBackground(); window->DC.CurrentColumns->LineMinY = window->DC.CursorPos.y; } } @@ -5311,7 +5311,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const ImGuiStyle& style = g.Style; if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped. - PopClipRect(); + PushColumnsBackground(); ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -5355,7 +5355,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (!item_add) { if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) - PushColumnClipRect(); + PopColumnsBackground(); return false; } @@ -5401,7 +5401,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) { - PushColumnClipRect(); + PopColumnsBackground(); bb.Max.x -= (GetContentRegionMax().x - max_x); } From a4d0b0efa49848bd1b54167ba4c57b95393aca2b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 May 2019 12:55:01 +0200 Subject: [PATCH 331/566] Internal: Refactored Separator into SeparatorEx(), exposed ImGuiSeparatorFlags_SpanAllColumns in imgui_internal.h and support without. (#759) + misc comments --- docs/TODO.txt | 4 +- imgui.cpp | 3 +- imgui_internal.h | 5 ++- imgui_widgets.cpp | 94 +++++++++++++++++++++++++---------------------- 4 files changed, 58 insertions(+), 48 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 4c89c8e3..97594ba4 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -133,7 +133,9 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - clipper: ability to disable the clipping through a simple flag/bool. - clipper: ability to run without knowing full count in advance. - - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) + - separator: expose flags (#759) + - separator: width, thickness, centering (#1643) + - splitter: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - dock: merge docking branch (#2109) - dock: dock out from a collapsing header? would work nicely but need emitting window to keep submitting the code. diff --git a/imgui.cpp b/imgui.cpp index 1045ddd6..779ea09e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5445,7 +5445,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); - // Inner clipping rectangle + // Inner clipping rectangle will extend a little bit outside the work region. + // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); diff --git a/imgui_internal.h b/imgui_internal.h index a56471db..01f805ba 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -354,7 +354,8 @@ enum ImGuiSeparatorFlags_ { ImGuiSeparatorFlags_None = 0, ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar - ImGuiSeparatorFlags_Vertical = 1 << 1 + ImGuiSeparatorFlags_Vertical = 1 << 1, + ImGuiSeparatorFlags_SpanAllColumns = 1 << 2 }; // Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). @@ -1551,7 +1552,7 @@ namespace ImGui IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags); IMGUI_API void Scrollbar(ImGuiAxis axis); IMGUI_API ImGuiID GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis); - IMGUI_API void VerticalSeparator(); // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. + IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags); // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index df9a7d87..2d505f56 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1146,8 +1146,8 @@ void ImGui::Bullet() // - Dummy() // - NewLine() // - AlignTextToFramePadding() +// - SeparatorEx() [Internal] // - Separator() -// - VerticalSeparator() [Internal] // - SplitterBehavior() [Internal] //------------------------------------------------------------------------- @@ -1198,69 +1198,75 @@ void ImGui::AlignTextToFramePadding() } // Horizontal/vertical separating line -void ImGui::Separator() +void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - ImGuiContext& g = *GImGui; - // Those flags should eventually be overrideable by the user - ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; + ImGuiContext& g = *GImGui; IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected + if (flags & ImGuiSeparatorFlags_Vertical) { - VerticalSeparator(); - return; - } - - // Horizontal Separator - if (window->DC.CurrentColumns) - PushColumnsBackground(); - - float x1 = window->Pos.x; - float x2 = window->Pos.x + window->Size.x; - if (!window->DC.GroupStack.empty()) - x1 += window->DC.Indent.x; + // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. + float y1 = window->DC.CursorPos.y; + float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y; + const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2)); + ItemSize(ImVec2(1.0f, 0.0f)); + if (!ItemAdd(bb, 0)) + return; - const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); - ItemSize(ImVec2(0.0f, 1.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit - if (!ItemAdd(bb, 0)) - { - if (window->DC.CurrentColumns) - PopColumnsBackground(); - return; + // Draw + window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator)); + if (g.LogEnabled) + LogText(" |"); } + else if (flags & ImGuiSeparatorFlags_Horizontal) + { + // Horizontal Separator + float x1 = window->Pos.x; + float x2 = window->Pos.x + window->Size.x; + if (!window->DC.GroupStack.empty()) + x1 += window->DC.Indent.x; - window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator)); + ImGuiColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL; + if (columns) + PushColumnsBackground(); - if (g.LogEnabled) - LogRenderedText(&bb.Min, "--------------------------------"); + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + 1.0f)); + ItemSize(ImVec2(0.0f, 1.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit + if (!ItemAdd(bb, 0)) + { + if (columns) + PopColumnsBackground(); + return; + } - if (window->DC.CurrentColumns) - { - PopColumnsBackground(); - window->DC.CurrentColumns->LineMinY = window->DC.CursorPos.y; + // Draw + window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator)); + if (g.LogEnabled) + LogRenderedText(&bb.Min, "--------------------------------"); + + if (columns) + { + PopColumnsBackground(); + columns->LineMinY = window->DC.CursorPos.y; + } } } -void ImGui::VerticalSeparator() +void ImGui::Separator() { - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return; ImGuiContext& g = *GImGui; - - float y1 = window->DC.CursorPos.y; - float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y; - const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2)); - ItemSize(ImVec2(1.0f, 0.0f)); - if (!ItemAdd(bb, 0)) + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) return; - window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator)); - if (g.LogEnabled) - LogText(" |"); + // Those flags should eventually be overridable by the user + ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; + flags |= ImGuiSeparatorFlags_SpanAllColumns; + SeparatorEx(flags); } // Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. From e29176df530c885a0c541f3691be76771fd222be Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 May 2019 12:56:03 +0200 Subject: [PATCH 332/566] Internals: Columns: Renamed fields. Comments and tweak. Moved a demo block. --- imgui.cpp | 45 ++++++++++++++++++++++------------------- imgui.h | 2 +- imgui_demo.cpp | 52 ++++++++++++++++++++++++------------------------ imgui_internal.h | 14 ++++++------- 4 files changed, 58 insertions(+), 55 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 779ea09e..a75829ef 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1140,7 +1140,7 @@ ImGuiStyle::ImGuiStyle() ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). - ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns + ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar @@ -5452,6 +5452,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); + // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; @@ -8434,12 +8435,12 @@ int ImGui::GetColumnsCount() static float OffsetNormToPixels(const ImGuiColumns* columns, float offset_norm) { - return offset_norm * (columns->MaxX - columns->MinX); + return offset_norm * (columns->OffMaxX - columns->OffMinX); } static float PixelsToOffsetNorm(const ImGuiColumns* columns, float offset) { - return offset / (columns->MaxX - columns->MinX); + return offset / (columns->OffMaxX - columns->OffMinX); } static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; @@ -8472,7 +8473,7 @@ float ImGui::GetColumnOffset(int column_index) IM_ASSERT(column_index < columns->Columns.Size); const float t = columns->Columns[column_index].OffsetNorm; - const float x_offset = ImLerp(columns->MinX, columns->MaxX, t); + const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); return x_offset; } @@ -8515,8 +8516,8 @@ void ImGui::SetColumnOffset(int column_index, float offset) const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) - offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); - columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX); + offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); + columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->OffMinX); if (preserve_width) SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); @@ -8551,7 +8552,7 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; window->DrawList->ChannelsSetCurrent(0); int cmd_size = window->DrawList->CmdBuffer.Size; - PushClipRect(columns->BackupClipRect.Min, columns->BackupClipRect.Max, false); + PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } @@ -8597,9 +8598,8 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag IM_ASSERT(columns_count >= 1); IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported - ImGuiID id = GetColumnsID(str_id, columns_count); - // Acquire storage for the columns set + ImGuiID id = GetColumnsID(str_id, columns_count); ImGuiColumns* columns = FindOrCreateColumns(window, id); IM_ASSERT(columns->ID == id); columns->Current = 0; @@ -8609,11 +8609,11 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag // Set state for first column const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x); - columns->MinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range - columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f); - columns->BackupCursorPosY = window->DC.CursorPos.y; - columns->BackupCursorMaxPosX = window->DC.CursorMaxPos.x; - columns->BackupClipRect = window->ClipRect; + columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range + columns->OffMaxX = ImMax(content_region_width - window->Scroll.x, columns->OffMinX + 1.0f); + columns->HostCursorPosY = window->DC.CursorPos.y; + columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; + columns->HostClipRect = window->ClipRect; columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -8622,7 +8622,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) columns->Columns.resize(0); - // Initialize defaults + // Initialize default widths columns->IsFirstFrame = (columns->Columns.Size == 0); if (columns->Columns.Size == 0) { @@ -8668,17 +8668,19 @@ void ImGui::EndColumns() window->DrawList->ChannelsMerge(); } + const ImGuiColumnsFlags flags = columns->Flags; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = columns->LineMaxY; - if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize)) - window->DC.CursorMaxPos.x = columns->BackupCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent + if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize)) + window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent // Draw columns borders and handle resize + // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy bool is_being_resized = false; - if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) + if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) { // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. - const float y1 = ImMax(columns->BackupCursorPosY, window->ClipRect.Min.y); + const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); int dragging_column = -1; for (int n = 1; n < columns->Count; n++) @@ -8693,7 +8695,7 @@ void ImGui::EndColumns() continue; bool hovered = false, held = false; - if (!(columns->Flags & ImGuiColumnsFlags_NoResize)) + if (!(flags & ImGuiColumnsFlags_NoResize)) { ButtonBehavior(column_hit_rect, column_id, &hovered, &held); if (hovered || held) @@ -8745,6 +8747,7 @@ void ImGui::Columns(int columns_count, const char* id, bool border) BeginColumns(id, columns_count, flags); } + //----------------------------------------------------------------------------- // [SECTION] DRAG AND DROP //----------------------------------------------------------------------------- @@ -9692,7 +9695,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) { if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) return; - ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX); + ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); for (int column_n = 0; column_n < columns->Columns.Size; column_n++) ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm)); ImGui::TreePop(); diff --git a/imgui.h b/imgui.h index aafcb3a6..0d46ec5d 100644 --- a/imgui.h +++ b/imgui.h @@ -1293,7 +1293,7 @@ struct ImGuiStyle ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). - float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. float ScrollbarRounding; // Radius of grab corners for scrollbar. float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1f01cc4d..e0d9c761 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2426,6 +2426,32 @@ static void ShowDemoWindowColumns() ImGui::TreePop(); } + if (ImGui::TreeNode("Borders")) + { + // NB: Future columns API should allow automatic horizontal borders. + static bool h_borders = true; + static bool v_borders = true; + ImGui::Checkbox("horizontal", &h_borders); + ImGui::SameLine(); + ImGui::Checkbox("vertical", &v_borders); + ImGui::Columns(4, NULL, v_borders); + for (int i = 0; i < 4 * 3; i++) + { + if (h_borders && ImGui::GetColumnIndex() == 0) + ImGui::Separator(); + ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i); + ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); + ImGui::Text("Long text that is likely to clip"); + ImGui::Button("Button", ImVec2(-1.0f, 0.0f)); + ImGui::NextColumn(); + } + ImGui::Columns(1); + if (h_borders) + ImGui::Separator(); + ImGui::TreePop(); + } + // Create multiple items in a same cell before switching to next column if (ImGui::TreeNode("Mixed items")) { @@ -2472,32 +2498,6 @@ static void ShowDemoWindowColumns() ImGui::TreePop(); } - if (ImGui::TreeNode("Borders")) - { - // NB: Future columns API should allow automatic horizontal borders. - static bool h_borders = true; - static bool v_borders = true; - ImGui::Checkbox("horizontal", &h_borders); - ImGui::SameLine(); - ImGui::Checkbox("vertical", &v_borders); - ImGui::Columns(4, NULL, v_borders); - for (int i = 0; i < 4*3; i++) - { - if (h_borders && ImGui::GetColumnIndex() == 0) - ImGui::Separator(); - ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); - ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); - ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); - ImGui::Text("Long text that is likely to clip"); - ImGui::Button("Button", ImVec2(-1.0f, 0.0f)); - ImGui::NextColumn(); - } - ImGui::Columns(1); - if (h_borders) - ImGui::Separator(); - ImGui::TreePop(); - } - // Scrolling columns /* if (ImGui::TreeNode("Vertical Scrolling")) diff --git a/imgui_internal.h b/imgui_internal.h index 01f805ba..b8bd9a6c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -680,11 +680,11 @@ struct ImGuiColumns bool IsBeingResized; int Current; int Count; - float MinX, MaxX; + float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x float LineMinY, LineMaxY; - float BackupCursorPosY; // Backup of CursorPos at the time of BeginColumns() - float BackupCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() - ImRect BackupClipRect; + float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() + float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() + ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns() ImVector Columns; ImGuiColumns() { Clear(); } @@ -696,10 +696,10 @@ struct ImGuiColumns IsBeingResized = false; Current = 0; Count = 1; - MinX = MaxX = 0.0f; + OffMinX = OffMaxX = 0.0f; LineMinY = LineMaxY = 0.0f; - BackupCursorPosY = 0.0f; - BackupCursorMaxPosX = 0.0f; + HostCursorPosY = 0.0f; + HostCursorMaxPosX = 0.0f; Columns.clear(); } }; From 9534ef9b26b1a3240c31f7bd643d8ebfdef01484 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 May 2019 17:52:56 +0200 Subject: [PATCH 333/566] Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change (c5d83d8a). It's not incorrect but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 11 +++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8a137d4e..f0d1cf05 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,8 @@ Breaking Changes: Other Changes: - Columns: Fixed Separator from creating an extraneous draw command. (#125) - Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) +- Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect + but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. ----------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2d505f56..2d00300e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1207,13 +1207,15 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) ImGuiContext& g = *GImGui; IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected + float thickness_draw = 1.0f; + float thickness_layout = 0.0f; if (flags & ImGuiSeparatorFlags_Vertical) { // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. float y1 = window->DC.CursorPos.y; float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y; - const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2)); - ItemSize(ImVec2(1.0f, 0.0f)); + const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness_draw, y2)); + ItemSize(ImVec2(thickness_layout, 0.0f)); if (!ItemAdd(bb, 0)) return; @@ -1234,8 +1236,9 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) if (columns) PushColumnsBackground(); - const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + 1.0f)); - ItemSize(ImVec2(0.0f, 1.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit + // We don't provide our width to the layout so that it doesn't get feed back into AutoFit + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness_draw)); + ItemSize(ImVec2(0.0f, thickness_layout)); if (!ItemAdd(bb, 0)) { if (columns) From 37174c85e270672526baf526f725e915029b0d77 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 May 2019 19:05:36 +0200 Subject: [PATCH 334/566] Internal: Scrollbar: Extracted scrollbar code for other uses (eg. table v2 scrolling without using a child window). --- imgui_internal.h | 5 +- imgui_widgets.cpp | 143 ++++++++++++++++++++++++---------------------- 2 files changed, 79 insertions(+), 69 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b8bd9a6c..fd579a37 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -956,7 +956,7 @@ struct ImGuiContext bool DragCurrentAccumDirty; float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio - ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? + float ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? int TooltipOverrideCount; ImVector PrivateClipboard; // If no custom clipboard handler is defined @@ -1092,7 +1092,7 @@ struct ImGuiContext DragCurrentAccumDirty = false; DragCurrentAccum = 0.0f; DragSpeedDefaultRatio = 1.0f / 100.0f; - ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); + ScrollbarClickDeltaToGrabCenter = 0.0f; TooltipOverrideCount = 0; MultiSelectScopeId = 0; @@ -1551,6 +1551,7 @@ namespace ImGui IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags); IMGUI_API void Scrollbar(ImGuiAxis axis); + IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float avail_v, float contents_v, ImDrawCornerFlags rounding_corners); IMGUI_API ImGuiID GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2d00300e..2b4368bc 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -380,6 +380,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // - ArrowButton() // - CloseButton() [Internal] // - CollapseButton() [Internal] +// - ScrollbarEx() [Internal] // - Scrollbar() [Internal] // - Image() // - ImageButton() @@ -777,125 +778,133 @@ ImGuiID ImGui::GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis) // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. -void ImGui::Scrollbar(ImGuiAxis axis) +// Still, the code should probably be made simpler.. +bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float size_avail_v, float size_contents_v, ImDrawCornerFlags rounding_corners) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; - const bool horizontal = (axis == ImGuiAxis_X); - const ImGuiStyle& style = g.Style; - const ImGuiID id = GetScrollbarID(window, axis); - KeepAliveID(id); - - // Render background - bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); - float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; - const ImRect host_rect = window->Rect(); - const float border_size = window->WindowBorderSize; - ImRect bb = horizontal - ? ImRect(host_rect.Min.x + border_size, host_rect.Max.y - style.ScrollbarSize, host_rect.Max.x - other_scrollbar_size_w - border_size, host_rect.Max.y - border_size) - : ImRect(host_rect.Max.x - style.ScrollbarSize, host_rect.Min.y + border_size, host_rect.Max.x - border_size, host_rect.Max.y - other_scrollbar_size_w - border_size); - bb.Min.x = ImMax(host_rect.Min.x, bb.Min.x); // Handle case where the host rectangle is smaller than the scrollbar - bb.Min.y = ImMax(host_rect.Min.y, bb.Min.y); - if (!horizontal) - bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); // FIXME: InnerRect? - - const float bb_width = bb.GetWidth(); - const float bb_height = bb.GetHeight(); - if (bb_width <= 0.0f || bb_height <= 0.0f) - return; + const float bb_frame_width = bb_frame.GetWidth(); + const float bb_frame_height = bb_frame.GetHeight(); + if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f) + return false; // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab) float alpha = 1.0f; - if ((axis == ImGuiAxis_Y) && bb_height < g.FontSize + g.Style.FramePadding.y * 2.0f) - { - alpha = ImSaturate((bb_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f)); - if (alpha <= 0.0f) - return; - } + if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f) + alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f)); + if (alpha <= 0.0f) + return false; + + const ImGuiStyle& style = g.Style; const bool allow_interaction = (alpha >= 1.0f); + const bool horizontal = (axis == ImGuiAxis_X); - int window_rounding_corners; - if (horizontal) - window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); - else - window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); - window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners); - bb.Expand(ImVec2(-ImClamp((float)(int)((bb_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb_height - 2.0f) * 0.5f), 0.0f, 3.0f))); + ImRect bb = bb_frame; + bb.Expand(ImVec2(-ImClamp((float)(int)((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f))); // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) - float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); - float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; - float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w; - float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; + const float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. - IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. - const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f); - const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v); + IM_ASSERT(ImMax(size_contents_v, size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. + const float win_size_v = ImMax(ImMax(size_contents_v, size_avail_v), 1.0f); + const float grab_h_pixels = ImClamp(scrollbar_size_v * (size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v); const float grab_h_norm = grab_h_pixels / scrollbar_size_v; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). bool held = false; bool hovered = false; - const bool previously_held = (g.ActiveId == id); ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus); - float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); - float scroll_ratio = ImSaturate(scroll_v / scroll_max); + float scroll_max = ImMax(1.0f, size_contents_v - size_avail_v); + float scroll_ratio = ImSaturate(*p_scroll_v / scroll_max); float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; if (held && allow_interaction && grab_h_norm < 1.0f) { float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; - float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; // Click position in scrollbar normalized space (0.0f->1.0f) const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); SetHoveredID(id); bool seek_absolute = false; - if (!previously_held) + if (g.ActiveIdIsJustActivated) { // On initial click calculate the distance between mouse and the center of the grab - if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) - { - *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; - } + seek_absolute = (clicked_v_norm < grab_v_norm || clicked_v_norm > grab_v_norm + grab_h_norm); + if (seek_absolute) + g.ScrollbarClickDeltaToGrabCenter = 0.0f; else - { - seek_absolute = true; - *click_delta_to_grab_center_v = 0.0f; - } + g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; } // Apply scroll // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position - const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); - scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); - if (horizontal) - window->Scroll.x = scroll_v; - else - window->Scroll.y = scroll_v; + const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm)); + *p_scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); // Update values for rendering - scroll_ratio = ImSaturate(scroll_v / scroll_max); + scroll_ratio = ImSaturate(*p_scroll_v / scroll_max); grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Update distance to grab now that we have seeked and saturated if (seek_absolute) - *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; + g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; } - // Render grab + // Render + window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, rounding_corners); const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha); ImRect grab_rect; if (horizontal) - grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, host_rect.Max.x), bb.Max.y); + grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y); else - grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, host_rect.Max.y)); + grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels); window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); + + return held; +} + +void ImGui::Scrollbar(ImGuiAxis axis) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + const bool horizontal = (axis == ImGuiAxis_X); + const ImGuiStyle& style = g.Style; + const ImGuiID id = GetScrollbarID(window, axis); + KeepAliveID(id); + + // Calculate our bounding box (FIXME: This is messy, should be made simpler using e.g. InnerRect/WorkRect data). + const float other_scrollbar_size = window->ScrollbarSizes[axis]; + const ImRect win_rect = window->Rect(); + const float border_size = window->WindowBorderSize; + ImRect bb = horizontal + ? ImRect(win_rect.Min.x + border_size, win_rect.Max.y - style.ScrollbarSize, win_rect.Max.x - other_scrollbar_size - border_size, win_rect.Max.y - border_size) + : ImRect(win_rect.Max.x - style.ScrollbarSize, win_rect.Min.y + border_size, win_rect.Max.x - border_size, win_rect.Max.y - other_scrollbar_size - border_size); + bb.Min.x = ImMax(win_rect.Min.x, bb.Min.x); // Handle case where the host rectangle is smaller than the scrollbar + bb.Min.y = ImMax(win_rect.Min.y, bb.Min.y); + if (!horizontal) + bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); // FIXME: InnerRect? + + // Select rounding + ImDrawCornerFlags rounding_corners; + if (horizontal) + rounding_corners = ImDrawCornerFlags_BotLeft; + else + rounding_corners = ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; + if (other_scrollbar_size <= 0.0f) + rounding_corners |= ImDrawCornerFlags_BotRight; + + if (horizontal) + ScrollbarEx(bb, id, axis, &window->Scroll.x, window->SizeFull.x - other_scrollbar_size, window->SizeContents.x, rounding_corners); + else + ScrollbarEx(bb, id, axis, &window->Scroll.y, window->SizeFull.y - other_scrollbar_size, window->SizeContents.y, rounding_corners); } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) From 39eeda0227892e5d616b622fe57f53cc9e824dc6 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 May 2019 19:30:13 +0200 Subject: [PATCH 335/566] Internal: Scrollbar: Further sane simplification (using InnerMainRect instead of duplicating calculations). --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 41 ++++++++++++++++------------------------- 2 files changed, 17 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f0d1cf05..366b695b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,7 @@ Other Changes: - Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. +- Scrollbar: Very minor bounding box adjustment to cope with various border size. ----------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2b4368bc..e0ebdbc2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -875,36 +875,27 @@ void ImGui::Scrollbar(ImGuiAxis axis) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - const bool horizontal = (axis == ImGuiAxis_X); - const ImGuiStyle& style = g.Style; const ImGuiID id = GetScrollbarID(window, axis); KeepAliveID(id); - // Calculate our bounding box (FIXME: This is messy, should be made simpler using e.g. InnerRect/WorkRect data). + // Calculate scrollbar bounding box + const ImRect outer_rect = window->Rect(); const float other_scrollbar_size = window->ScrollbarSizes[axis]; - const ImRect win_rect = window->Rect(); - const float border_size = window->WindowBorderSize; - ImRect bb = horizontal - ? ImRect(win_rect.Min.x + border_size, win_rect.Max.y - style.ScrollbarSize, win_rect.Max.x - other_scrollbar_size - border_size, win_rect.Max.y - border_size) - : ImRect(win_rect.Max.x - style.ScrollbarSize, win_rect.Min.y + border_size, win_rect.Max.x - border_size, win_rect.Max.y - other_scrollbar_size - border_size); - bb.Min.x = ImMax(win_rect.Min.x, bb.Min.x); // Handle case where the host rectangle is smaller than the scrollbar - bb.Min.y = ImMax(win_rect.Min.y, bb.Min.y); - if (!horizontal) - bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); // FIXME: InnerRect? - - // Select rounding - ImDrawCornerFlags rounding_corners; - if (horizontal) - rounding_corners = ImDrawCornerFlags_BotLeft; - else - rounding_corners = ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; - if (other_scrollbar_size <= 0.0f) - rounding_corners |= ImDrawCornerFlags_BotRight; - - if (horizontal) - ScrollbarEx(bb, id, axis, &window->Scroll.x, window->SizeFull.x - other_scrollbar_size, window->SizeContents.x, rounding_corners); + ImDrawCornerFlags rounding_corners = (other_scrollbar_size <= 0.0f) ? ImDrawCornerFlags_BotRight : 0; + ImRect bb; + if (axis == ImGuiAxis_X) + { + bb.Min = ImVec2(window->InnerMainRect.Min.x, window->InnerMainRect.Max.y); + bb.Max = ImVec2(window->InnerMainRect.Max.x, outer_rect.Max.y - window->WindowBorderSize); + rounding_corners |= ImDrawCornerFlags_BotLeft; + } else - ScrollbarEx(bb, id, axis, &window->Scroll.y, window->SizeFull.y - other_scrollbar_size, window->SizeContents.y, rounding_corners); + { + bb.Min = ImVec2(window->InnerMainRect.Max.x, window->InnerMainRect.Min.y); + bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerMainRect.Max.y); + rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; + } + ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->SizeFull[axis] - other_scrollbar_size, window->SizeContents[axis], rounding_corners); } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) From b50c61c961498e15b5a4c22c7e7e10df13a64e77 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 May 2019 22:30:33 +0200 Subject: [PATCH 336/566] Internal: Begin: Update rectangles before Scrollbar() which now uses them. Fixes 39eeda0. --- imgui.cpp | 66 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a75829ef..7f433ee5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5307,6 +5307,40 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) else window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); + // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars. + window->SizeFullAtLastBegin = window->SizeFull; + + // UPDATE RECTANGLES + + // Update various regions. Variables they depends on are set above in this function. + // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out. + window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; + window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); + window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); + + // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() + window->OuterRectClipped = window->Rect(); + window->OuterRectClipped.ClipWith(window->ClipRect); + + // Inner rectangle + // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame + // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + const ImRect title_bar_rect = window->TitleBarRect(); + window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; + window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); + window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); + + // Inner clipping rectangle will extend a little bit outside the work region. + // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. + // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); + window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); + // DRAWING // Setup draw list and outer clipping rectangle @@ -5342,7 +5376,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const float window_border_size = window->WindowBorderSize; const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); - const ImRect title_bar_rect = window->TitleBarRect(); if (window->Collapsed) { // Title bar only @@ -5422,37 +5455,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f); } - // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars. - window->SizeFullAtLastBegin = window->SizeFull; - - // Update various regions. Variables they depends on are set above in this function. - // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. - // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out. - window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; - window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); - window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); - window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); - - // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() - window->OuterRectClipped = window->Rect(); - window->OuterRectClipped.ClipWith(window->ClipRect); - - // Inner rectangle - // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame - // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. - window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; - window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); - window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); - window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); - - // Inner clipping rectangle will extend a little bit outside the work region. - // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. - // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. - window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); - window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); - // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; From 72951a1a85771b721a2011b51a01c6a146c9f1a2 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 May 2019 22:38:10 +0200 Subject: [PATCH 337/566] Internal: Extracted some of the Begin code into RenderWindowTitleBarContents(). --- imgui.cpp | 108 +++++++++++++++++++++++++++++------------------------- 1 file changed, 58 insertions(+), 50 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7f433ee5..d3ad06fa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1076,7 +1076,8 @@ static int FindWindowFocusIndex(ImGuiWindow* window); static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); -static void RenderOuterBorders(ImGuiWindow* window); +static void RenderWindowOuterBorders(ImGuiWindow* window); +static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); } @@ -4926,7 +4927,7 @@ static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, cons window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping); } -static void ImGui::RenderOuterBorders(ImGuiWindow* window) +static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { ImGuiContext& g = *GImGui; float rounding = window->WindowRounding; @@ -4963,6 +4964,58 @@ static void ImGui::RenderOuterBorders(ImGuiWindow* window) } } +void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + ImGuiWindowFlags flags = window->Flags; + + // Close & collapse button are on layer 1 (same as menus) and don't default focus + const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; + window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; + window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; + window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); + + // Collapse button + if (!(flags & ImGuiWindowFlags_NoCollapse)) + if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos)) + window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function + + // Close button + if (p_open != NULL) + { + const float rad = g.FontSize * 0.5f; + if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x - rad, window->Pos.y + style.FramePadding.y + rad), rad + 1)) + *p_open = false; + } + + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); + window->DC.ItemFlags = item_flags_backup; + + // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) + // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. + const char* UNSAVED_DOCUMENT_MARKER = "*"; + const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f; + const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); + ImRect text_r = title_bar_rect; + float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); + float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); + if (style.WindowTitleAlign.x > 0.0f) + pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); + text_r.Min.x += pad_left; + text_r.Max.x -= pad_right; + ImRect clip_rect = text_r; + clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton() + RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); + if (flags & ImGuiWindowFlags_UnsavedDocument) + { + ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f); + ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f)); + RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect); + } +} + void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) { window->ParentWindow = parent_window; @@ -4978,7 +5031,7 @@ void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags } } -// Push a new ImGui window to add widgets to. +// Push a new Dear ImGui window to add widgets to. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). @@ -5438,7 +5491,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } // Borders - RenderOuterBorders(window); + RenderWindowOuterBorders(window); } // Draw navigation selection/windowing rectangle border @@ -5508,52 +5561,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) - { - // Close & collapse button are on layer 1 (same as menus) and don't default focus - const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; - window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; - window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); - - // Collapse button - if (!(flags & ImGuiWindowFlags_NoCollapse)) - if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos)) - window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function - - // Close button - if (p_open != NULL) - { - const float rad = g.FontSize * 0.5f; - if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x - rad, window->Pos.y + style.FramePadding.y + rad), rad + 1)) - *p_open = false; - } - - window->DC.NavLayerCurrent = ImGuiNavLayer_Main; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); - window->DC.ItemFlags = item_flags_backup; - - // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) - // FIXME: Refactor text alignment facilities along with RenderText helpers, this is too much code.. - const char* UNSAVED_DOCUMENT_MARKER = "*"; - float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f; - ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); - ImRect text_r = title_bar_rect; - float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); - float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); - if (style.WindowTitleAlign.x > 0.0f) - pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); - text_r.Min.x += pad_left; - text_r.Max.x -= pad_right; - ImRect clip_rect = text_r; - clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton() - RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); - if (flags & ImGuiWindowFlags_UnsavedDocument) - { - ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f); - ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f)); - RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect); - } - } + RenderWindowTitleBarContents(window, title_bar_rect, name, p_open); // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. From 7c256fbd40f50683908a91e32610f07e243ac7e0 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 May 2019 22:45:52 +0200 Subject: [PATCH 338/566] Internal: Extracted some of the Begin code into RenderWindowDecorations(). --- imgui.cpp | 148 +++++++++++++++++++++++++++++------------------------- 1 file changed, 79 insertions(+), 69 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d3ad06fa..d7a75f96 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1077,6 +1077,7 @@ static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); static void RenderWindowOuterBorders(ImGuiWindow* window); +static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, 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); } @@ -4964,6 +4965,82 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) } } +void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + ImGuiWindowFlags flags = window->Flags; + + // Draw window + handle manual resize + // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame. + const float window_rounding = window->WindowRounding; + const float window_border_size = window->WindowBorderSize; + if (window->Collapsed) + { + // Title bar only + float backup_border_size = style.FrameBorderSize; + g.Style.FrameBorderSize = window->WindowBorderSize; + ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); + RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); + g.Style.FrameBorderSize = backup_border_size; + } + else + { + // Window background + if (!(flags & ImGuiWindowFlags_NoBackground)) + { + ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); + float alpha = 1.0f; + if (g.NextWindowData.BgAlphaCond != 0) + alpha = g.NextWindowData.BgAlphaVal; + if (alpha != 1.0f) + bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); + window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); + } + g.NextWindowData.BgAlphaCond = 0; + + // 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, ImDrawCornerFlags_Top); + } + + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) + { + 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 + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top); + if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) + window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); + } + + // Scrollbars + if (window->ScrollbarX) + Scrollbar(ImGuiAxis_X); + if (window->ScrollbarY) + Scrollbar(ImGuiAxis_Y); + + // Render resize grips (after their input handling so we don't have a frame of latency) + if (!(flags & ImGuiWindowFlags_NoResize)) + { + for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) + { + const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; + const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size))); + window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size))); + window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); + window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]); + } + } + + // Borders + RenderWindowOuterBorders(window); + } +} + void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) { ImGuiContext& g = *GImGui; @@ -5349,7 +5426,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) int border_held = -1; ImU32 resize_grip_col[4] = { 0 }; const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4 - const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); + const float resize_grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); if (!window->Collapsed) UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); window->ResizeBorderHeld = (signed char)border_held; @@ -5423,76 +5500,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding); } - // Draw window + handle manual resize - // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame. - const float window_rounding = window->WindowRounding; - const float window_border_size = window->WindowBorderSize; const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); - if (window->Collapsed) - { - // Title bar only - float backup_border_size = style.FrameBorderSize; - g.Style.FrameBorderSize = window->WindowBorderSize; - ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); - RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); - g.Style.FrameBorderSize = backup_border_size; - } - else - { - // Window background - if (!(flags & ImGuiWindowFlags_NoBackground)) - { - ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); - float alpha = 1.0f; - if (g.NextWindowData.BgAlphaCond != 0) - alpha = g.NextWindowData.BgAlphaVal; - if (alpha != 1.0f) - bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); - window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); - } - g.NextWindowData.BgAlphaCond = 0; - - // 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, ImDrawCornerFlags_Top); - } - - // Menu bar - if (flags & ImGuiWindowFlags_MenuBar) - { - 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+ImVec2(window_border_size,0), menu_bar_rect.Max-ImVec2(window_border_size,0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top); - if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) - window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); - } - - // Scrollbars - if (window->ScrollbarX) - Scrollbar(ImGuiAxis_X); - if (window->ScrollbarY) - Scrollbar(ImGuiAxis_Y); - - // Render resize grips (after their input handling so we don't have a frame of latency) - if (!(flags & ImGuiWindowFlags_NoResize)) - { - for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) - { - const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; - const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); - window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size))); - window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size))); - window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); - window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]); - } - } - - // Borders - RenderWindowOuterBorders(window); - } + RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size); // Draw navigation selection/windowing rectangle border if (g.NavWindowingTargetAnim == window) From b668726a3852ca82c8016166cd67871d6f75b7f5 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 May 2019 22:58:24 +0200 Subject: [PATCH 339/566] Fixed a PVS Studio static analyzer warning. --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index e123be0e..00fafdc8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11524,8 +11524,9 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) // Central node property needs to be moved to a leaf node, pick the last focused one. // FIXME-DOCKING: If we had to transfer other flags here, what would the policy be? ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeID); + IM_ASSERT(last_focused_node != NULL); ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node); - IM_ASSERT(last_focused_node != NULL && last_focused_root_node == DockNodeGetRootNode(payload_node)); + IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node)); last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode; last_focused_root_node->CentralNode = last_focused_node; From ef13d95466f27b4a955d6f95da90822001ace25f Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 11 May 2019 10:33:56 +0200 Subject: [PATCH 340/566] IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) --- docs/CHANGELOG.txt | 4 ++++ examples/imgui_impl_allegro5.cpp | 4 ++-- examples/imgui_impl_glfw.cpp | 4 ++-- examples/imgui_impl_glut.cpp | 2 +- examples/imgui_impl_marmalade.cpp | 4 ++-- examples/imgui_impl_osx.mm | 5 +++-- examples/imgui_impl_win32.cpp | 4 ++-- imgui.cpp | 8 +++++--- imgui.h | 2 +- 9 files changed, 22 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 366b695b..1e47efe2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -33,6 +33,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- Breaking Changes: +- IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). Other Changes: - Columns: Fixed Separator from creating an extraneous draw command. (#125) @@ -40,6 +41,9 @@ Other Changes: - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. - Scrollbar: Very minor bounding box adjustment to cope with various border size. +- Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), + the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode + support. (#2538, #2541) ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index b05fa2a3..46893390 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-11: Inputs: Don't filter character value from ALLEGRO_EVENT_KEY_CHAR before calling AddInputCharacter(). // 2019-04-30: Renderer: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-11-30: Platform: Added touchscreen support. // 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window. @@ -353,8 +354,7 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT *ev) return true; case ALLEGRO_EVENT_KEY_CHAR: if (ev->keyboard.display == g_Display) - if (ev->keyboard.unichar > 0 && ev->keyboard.unichar < 0x10000) - io.AddInputCharacter((unsigned short)ev->keyboard.unichar); + io.AddInputCharacter((unsigned int)ev->keyboard.unichar); return true; case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_UP: diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 0ed9f7d2..090b012d 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter(). // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them. @@ -120,8 +121,7 @@ void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c) g_PrevUserCallbackChar(window, c); ImGuiIO& io = ImGui::GetIO(); - if (c > 0 && c < 0x10000) - io.AddInputCharacter((unsigned short)c); + io.AddInputCharacter(c); } static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api) diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index af42d4ae..78b3c54a 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -118,7 +118,7 @@ void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) //printf("char_down_func %d '%c'\n", c, c); ImGuiIO& io = ImGui::GetIO(); if (c >= 32) - io.AddInputCharacter((unsigned short)c); + io.AddInputCharacter((unsigned int)c); // Store letters in KeysDown[] array as both uppercase and lowercase + Handle GLUT translating CTRL+A..CTRL+Z as 1..26. // This is a hacky mess but GLUT is unable to distinguish e.g. a TAB key from CTRL+I so this is probably the best we can do here. diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index 1f2307b2..a101c69a 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter(). // 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_Marmalade_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. @@ -166,8 +167,7 @@ int32 ImGui_Marmalade_CharCallback(void* system_data, void* user_data) { ImGuiIO& io = ImGui::GetIO(); s3eKeyboardCharEvent* e = (s3eKeyboardCharEvent*)system_data; - if ((e->m_Char > 0 && e->m_Char < 0x10000)) - io.AddInputCharacter((unsigned short)e->m_Char); + io.AddInputCharacter((unsigned int)e->m_Char); return 0; } diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 07381caf..34a61ff5 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-07-07: Initial version. @@ -189,8 +190,8 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) for (int i = 0; i < len; i++) { int c = [str characterAtIndex:i]; - if (c < 0xF700 && !io.KeyCtrl) - io.AddInputCharacter((unsigned short)c); + if (!io.KeyCtrl && !(c >= 0xF700 && c <= 0xFFFF)) + io.AddInputCharacter((unsigned int)c); // We must reset in case we're pressing a sequence of special keys while keeping the command pressed int key = mapCharacterToKey(c); diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 59cf88ce..85dede4e 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -18,6 +18,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter(). // 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. // 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. // 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application). @@ -305,8 +306,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA return 0; case WM_CHAR: // You can also use ToAscii()+GetKeyboardState() to retrieve characters. - if (wParam > 0 && wParam < 0x10000) - io.AddInputCharacter((unsigned short)wParam); + io.AddInputCharacter((unsigned int)wParam); return 0; case WM_SETCURSOR: if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) diff --git a/imgui.cpp b/imgui.cpp index d7a75f96..227b3ee1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,7 @@ CODE When you are not sure about a 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. + - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). @@ -1251,9 +1252,10 @@ ImGuiIO::ImGuiIO() // Pass in translated ASCII characters for text input. // - with glfw you can get those from the callback set in glfwSetCharCallback() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message -void ImGuiIO::AddInputCharacter(ImWchar c) +void ImGuiIO::AddInputCharacter(unsigned int c) { - InputQueueCharacters.push_back(c); + if (c > 0 && c < 0x10000) + InputQueueCharacters.push_back((ImWchar)c); } void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) @@ -1262,7 +1264,7 @@ void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) { unsigned int c = 0; utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL); - if (c > 0 && c <= 0xFFFF) + if (c > 0 && c < 0x10000) InputQueueCharacters.push_back((ImWchar)c); } } diff --git a/imgui.h b/imgui.h index 0d46ec5d..7c05d7c4 100644 --- a/imgui.h +++ b/imgui.h @@ -1402,7 +1402,7 @@ struct ImGuiIO float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs. Cleared back to zero by EndFrame(). Keyboard keys will be auto-mapped and be written here by NewFrame(). // Functions - IMGUI_API void AddInputCharacter(ImWchar c); // Queue new character input + IMGUI_API void AddInputCharacter(unsigned int c); // Queue new character input IMGUI_API void AddInputCharactersUTF8(const char* str); // Queue new characters input from an UTF-8 string IMGUI_API void ClearInputCharacters(); // Clear the text input buffer manually From 87c5356d977a07abfe05dc0fcdbcebcc73eb47dd Mon Sep 17 00:00:00 2001 From: HolyBlackCat Date: Thu, 9 May 2019 22:03:27 +0300 Subject: [PATCH 341/566] FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. --- docs/CHANGELOG.txt | 2 ++ misc/freetype/README.md | 1 + misc/freetype/imgui_freetype.cpp | 53 ++++++++++++++++++++++++++------ misc/freetype/imgui_freetype.h | 3 +- 4 files changed, 48 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1e47efe2..d7f4ca26 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ Other Changes: - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. - Scrollbar: Very minor bounding box adjustment to cope with various border size. +- ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) + Combine with RasterizerFlags::MonoHinting for best results. - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) diff --git a/misc/freetype/README.md b/misc/freetype/README.md index 397adec7..b62671ce 100644 --- a/misc/freetype/README.md +++ b/misc/freetype/README.md @@ -120,6 +120,7 @@ struct FreeTypeTest WantRebuild |= ImGui::CheckboxFlags("MonoHinting", &FontsFlags, ImGuiFreeType::MonoHinting); WantRebuild |= ImGui::CheckboxFlags("Bold", &FontsFlags, ImGuiFreeType::Bold); WantRebuild |= ImGui::CheckboxFlags("Oblique", &FontsFlags, ImGuiFreeType::Oblique); + WantRebuild |= ImGui::CheckboxFlags("Monochrome", &FontsFlags, ImGuiFreeType::Monochrome); } ImGui::End(); } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 4a579ed2..a184d78b 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -12,6 +12,7 @@ // - v0.56: (2018/06/08) added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX. // - v0.60: (2019/01/10) re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding. // - v0.61: (2019/01/15) added support for imgui allocators + added FreeType only override function SetAllocatorFunctions(). +// - v0.62: (2019/02/09) added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!) // Gamma Correct Blending: // FreeType assumes blending in linear space rather than gamma space. @@ -109,6 +110,7 @@ namespace FT_Face Face; unsigned int UserFlags; // = ImFontConfig::RasterizerFlags FT_Int32 LoadFlags; + FT_Render_Mode RenderMode; }; // From SDL_ttf: Handy routines for converting from fixed point @@ -142,6 +144,11 @@ namespace else LoadFlags |= FT_LOAD_TARGET_NORMAL; + if (UserFlags & ImGuiFreeType::Monochrome) + RenderMode = FT_RENDER_MODE_MONO; + else + RenderMode = FT_RENDER_MODE_NORMAL; + return true; } @@ -208,7 +215,7 @@ namespace const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info) { FT_GlyphSlot slot = Face->glyph; - FT_Error error = FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL); + FT_Error error = FT_Render_Glyph(slot, RenderMode); if (error != 0) return NULL; @@ -230,16 +237,42 @@ namespace const uint8_t* src = ft_bitmap->buffer; const uint32_t src_pitch = ft_bitmap->pitch; - if (multiply_table == NULL) - { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - memcpy(dst, src, w); - } - else + switch (ft_bitmap->pixel_mode) { - for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) - for (uint32_t x = 0; x < w; x++) - dst[x] = multiply_table[src[x]]; + case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel. + { + if (multiply_table == NULL) + { + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + memcpy(dst, src, w); + } + else + { + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + for (uint32_t x = 0; x < w; x++) + dst[x] = multiply_table[src[x]]; + } + break; + } + case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB. + { + uint8_t color0 = multiply_table ? multiply_table[0] : 0; + uint8_t color1 = multiply_table ? multiply_table[255] : 255; + for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) + { + uint8_t bits = 0; + const uint8_t* bits_ptr = src; + for (uint32_t x = 0; x < w; x++, bits <<= 1) + { + if ((x & 7) == 0) + bits = *bits_ptr++; + dst[x] = (bits & 0x80) ? color1 : color0; + } + } + break; + } + default: + IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!"); } } } diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index b4b0fd66..d65c7724 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -24,7 +24,8 @@ namespace ImGuiFreeType LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text. MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output. Bold = 1 << 5, // Styling: Should we artificially embolden the font? - Oblique = 1 << 6 // Styling: Should we slant the font, emulating italic style? + Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style? + Monochrome = 1 << 7 // Disable anti-aliasing. Combine this with MonoHinting for best results! }; IMGUI_API bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags = 0); From 02d6d2d487e33e6a7d81b1560374f93b5d881872 Mon Sep 17 00:00:00 2001 From: Alzathar Date: Sat, 11 May 2019 04:54:56 -0400 Subject: [PATCH 342/566] Platform Binding for GLFW updated with the release of GLFW 3.3 (#2547) * With the release of GLFW 3.3, it is now possible to detect correctly monitors working area (see GLFW_HAS_MONITOR_WORK_AREA). GLFW 3.3 also introduced the window hint GLFW_FOCUS_ON_SHOW. This fixed the case where a new created window (viewport) takes the focus even if not visible. * Disable a GLFW 3.2 windows hack when GLFW 3.3 is detected (related to window focused when shown). --- examples/imgui_impl_glfw.cpp | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 37a33cd4..a6aee9bb 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -44,12 +44,14 @@ #define GLFW_EXPOSE_NATIVE_WIN32 #include // for glfwGetWin32Window #endif -#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING -#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED -#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity -#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale -#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface -#define GLFW_HAS_FOCUS_WINDOW (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwFocusWindow +#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING +#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED +#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity +#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale +#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface +#define GLFW_HAS_FOCUS_WINDOW (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwFocusWindow +#define GLFW_HAS_FOCUS_ON_SHOW (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_FOCUS_ON_SHOW +#define GLFW_HAS_MONITOR_WORK_AREA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorWorkarea // Data enum GlfwClientApi @@ -428,8 +430,12 @@ static void ImGui_ImplGlfw_CreateWindow(ImGuiViewport* viewport) viewport->PlatformUserData = data; // GLFW 3.2 unfortunately always set focus on glfwCreateWindow() if GLFW_VISIBLE is set, regardless of GLFW_FOCUSED + // With GLFW 3.3, the hint GLFW_FOCUS_ON_SHOW fixes this problem glfwWindowHint(GLFW_VISIBLE, false); glfwWindowHint(GLFW_FOCUSED, false); +#if GLFW_HAS_FOCUS_ON_SHOW + glfwWindowHint(GLFW_FOCUS_ON_SHOW, false); + #endif glfwWindowHint(GLFW_DECORATED, (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? false : true); #if GLFW_HAS_WINDOW_TOPMOST glfwWindowHint(GLFW_FLOATING, (viewport->Flags & ImGuiViewportFlags_TopMost) ? true : false); @@ -515,6 +521,7 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) ::SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)WndProcNoInputs); #endif +#if !GLFW_HAS_FOCUS_ON_SHOW // GLFW hack: GLFW 3.2 has a bug where glfwShowWindow() also activates/focus the window. // The fix was pushed to GLFW repository on 2018/01/09 and should be included in GLFW 3.3 via a GLFW_FOCUS_ON_SHOW window attribute. // See https://github.com/glfw/glfw/issues/1189 @@ -524,6 +531,7 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) ::ShowWindow(hwnd, SW_SHOWNA); return; } +#endif #endif glfwShowWindow(data->Window); @@ -678,8 +686,17 @@ static void ImGui_ImplGlfw_UpdateMonitors() int x, y; glfwGetMonitorPos(glfw_monitors[n], &x, &y); const GLFWvidmode* vid_mode = glfwGetVideoMode(glfw_monitors[n]); +#if GLFW_HAS_MONITOR_WORK_AREA + monitor.MainPos = ImVec2((float)x, (float)y); + monitor.MainSize = ImVec2((float)vid_mode->width, (float)vid_mode->height); + int w, h; + glfwGetMonitorWorkarea(glfw_monitors[n], &x, &y, &w, &h); + monitor.WorkPos = ImVec2((float)x, (float)y);; + monitor.WorkSize = ImVec2((float)w, (float)h); +#else monitor.MainPos = monitor.WorkPos = ImVec2((float)x, (float)y); monitor.MainSize = monitor.WorkSize = ImVec2((float)vid_mode->width, (float)vid_mode->height); +#endif #if GLFW_HAS_PER_MONITOR_DPI // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime. float x_scale, y_scale; From aca6ee1a912fd6bf022cce15a5c25a2eb2c0f6df Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 11 May 2019 11:25:49 +0200 Subject: [PATCH 343/566] Cast ImTextureId to void* before printing in Metrics window. (#2548) --- imgui.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 227b3ee1..b9cce1f9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9670,7 +9670,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) continue; } ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; - bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), + "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered()) { ImRect clip_rect = pcmd->ClipRect; From b955e485f11c31a7005a3c88b73fe2143753a0d0 Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Sun, 12 May 2019 08:53:08 -0700 Subject: [PATCH 344/566] Fixed unused variables warnings when asserts are compiled out. (#2551) --- imgui.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 00fafdc8..a6683954 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3623,6 +3623,7 @@ void ImGui::NewFrame() for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) { ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n]; + IM_UNUSED(mon); IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor bounds not setup properly."); IM_ASSERT(mon.WorkSize.x > 0.0f && mon.WorkSize.y > 0.0f && "Monitor bounds not setup properly. If you don't have work area information, just copy Min/Max into them."); IM_ASSERT(mon.DpiScale != 0.0f); @@ -9242,7 +9243,8 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; window->DrawList->ChannelsSetCurrent(0); int cmd_size = window->DrawList->CmdBuffer.Size; - PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); + PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); + IM_UNUSED(cmd_size); IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } @@ -11130,6 +11132,7 @@ void ImGui::DockContextOnLoadSettings(ImGuiContext* ctx) void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references) { + IM_UNUSED(ctx); IM_ASSERT(ctx == GImGui); DockBuilderRemoveNodeDockedWindows(root_id, clear_persistent_docking_references); DockBuilderRemoveNodeChildNodes(root_id); @@ -11439,6 +11442,8 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL); ImGuiContext& g = *ctx; + IM_UNUSED(g); + ImGuiWindow* payload_window = req->DockPayload; // Optional ImGuiWindow* target_window = req->DockTargetWindow; ImGuiDockNode* node = req->DockTargetNode; From 7355c847016ec01f0c5b2186f56d7783e75ceb4c Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 12 May 2019 21:35:05 +0200 Subject: [PATCH 345/566] Tweak EndGroup() to facilitate fixing #2550 later (currently should have no side-effect0. Demo: Add extra widget to status query test. --- imgui.cpp | 9 ++++++--- imgui_demo.cpp | 21 +++++++++++++-------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b9cce1f9..9087752a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6825,10 +6825,13 @@ void ImGui::EndGroup() // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. - // (and if you grep for LastItemId you'll notice it is only used in that context. - if ((group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId) // && g.ActiveIdWindow->RootWindow == window->RootWindow) + // Also if you grep for LastItemId you'll notice it is only used in that context. + // (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.) + const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId; + const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive; + if (group_contains_curr_active_id) window->DC.LastItemId = g.ActiveId; - else if (!group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive) // && g.ActiveIdPreviousFrameWindow->RootWindow == window->RootWindow) + else if (group_contains_prev_active_id) window->DC.LastItemId = g.ActiveIdPreviousFrame; window->DC.LastItemRect = group_bb; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e0d9c761..f9cb7c6b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1533,10 +1533,11 @@ static void ShowDemoWindowWidgets() ImGui::RadioButton("Checkbox", &item_type, 2); ImGui::RadioButton("SliderFloat", &item_type, 3); ImGui::RadioButton("InputText", &item_type, 4); - ImGui::RadioButton("ColorEdit4", &item_type, 5); - ImGui::RadioButton("MenuItem", &item_type, 6); - ImGui::RadioButton("TreeNode (w/ double-click)", &item_type, 7); - ImGui::RadioButton("ListBox", &item_type, 8); + ImGui::RadioButton("InputFloat3", &item_type, 5); + ImGui::RadioButton("ColorEdit4", &item_type, 6); + ImGui::RadioButton("MenuItem", &item_type, 7); + ImGui::RadioButton("TreeNode (w/ double-click)", &item_type, 8); + ImGui::RadioButton("ListBox", &item_type, 9); ImGui::Separator(); bool ret = false; if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction @@ -1544,10 +1545,11 @@ static void ShowDemoWindowWidgets() if (item_type == 2) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox if (item_type == 3) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item if (item_type == 4) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) - if (item_type == 5) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) - if (item_type == 6) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) - if (item_type == 7) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. - if (item_type == 8) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } + if (item_type == 5) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 6) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 7) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) + if (item_type == 8) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. + if (item_type == 9) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } ImGui::BulletText( "Return value = %d\n" "IsItemFocused() = %d\n" @@ -1628,6 +1630,9 @@ static void ShowDemoWindowWidgets() if (embed_all_inside_a_child_window) ImGui::EndChild(); + static char dummy_str[] = "This is a dummy field to be able to tab-out of the widgets above."; + ImGui::InputText("dummy", dummy_str, IM_ARRAYSIZE(dummy_str), ImGuiInputTextFlags_ReadOnly); + // Calling IsItemHovered() after begin returns the hovered status of the title bar. // This is useful in particular if you want to create a context menu (with BeginPopupContextItem) associated to the title bar of a window. static bool test_window = false; From 0b485f12d7b420a12a53a9a2d685e0cb75532a87 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 May 2019 11:25:38 +0200 Subject: [PATCH 346/566] Internal: Minor tidying/reordering of sections within ImGuiContext / window DC. --- imgui.cpp | 16 +++++++++------- imgui_internal.h | 49 ++++++++++++++++++++++++++++++----------------- imgui_widgets.cpp | 2 +- 3 files changed, 41 insertions(+), 26 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9087752a..808594bc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6786,7 +6786,7 @@ void ImGui::BeginGroup() group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; - group_data.AdvanceCursor = true; + group_data.EmitItem = true; window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; window->DC.Indent = window->DC.GroupOffset; @@ -6804,8 +6804,7 @@ void ImGui::EndGroup() ImGuiGroupData& group_data = window->DC.GroupStack.back(); - ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); - group_bb.Max = ImMax(group_bb.Min, group_bb.Max); + ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos)); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); @@ -6816,13 +6815,16 @@ void ImGui::EndGroup() if (g.LogEnabled) g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return - if (group_data.AdvanceCursor) + if (!group_data.EmitItem) { - window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. - ItemSize(group_bb.GetSize(), 0.0f); - ItemAdd(group_bb, 0); + window->DC.GroupStack.pop_back(); + return; } + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize(), 0.0f); + ItemAdd(group_bb, 0); + // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. // Also if you grep for LastItemId you'll notice it is only used in that context. diff --git a/imgui_internal.h b/imgui_internal.h index fd579a37..868a3e98 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -575,7 +575,7 @@ struct ImGuiGroupData float BackupCurrentLineTextBaseOffset; ImGuiID BackupActiveIdIsAlive; bool BackupActiveIdPreviousFrameIsAlive; - bool AdvanceCursor; + bool EmitItem; }; // Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. @@ -818,11 +818,12 @@ struct ImGuiContext float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. ImDrawListSharedData DrawListSharedData; - double Time; int FrameCount; int FrameCountEnded; int FrameCountRendered; + + // Windows state ImVector Windows; // Windows, sorted in display order, back to front ImVector WindowsFocusOrder; // Windows, sorted in focus order, back to front ImVector WindowsSortBuffer; @@ -832,39 +833,45 @@ struct ImGuiContext ImGuiWindow* CurrentWindow; // Being drawn into ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. + + // Item/widgets state and tracking information ImGuiID HoveredId; // Hovered widget bool HoveredIdAllowOverlap; ImGuiID HoveredIdPreviousFrame; float HoveredIdTimer; // Measure contiguous hovering time float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active ImGuiID ActiveId; // Active widget - ImGuiID ActiveIdPreviousFrame; ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) float ActiveIdTimer; bool ActiveIdIsJustActivated; // Set at the time of activation for one frame bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) bool ActiveIdHasBeenPressed; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. bool ActiveIdHasBeenEdited; // Was the value associated to the widget Edited over the course of the Active state. - bool ActiveIdPreviousFrameIsAlive; - bool ActiveIdPreviousFrameHasBeenEdited; int ActiveIdAllowNavDirFlags; // Active widget allows using directional navigation (e.g. can activate a button and move away from it) int ActiveIdBlockNavInputFlags; ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) ImGuiWindow* ActiveIdWindow; - ImGuiWindow* ActiveIdPreviousFrameWindow; ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard) + ImGuiID ActiveIdPreviousFrame; + bool ActiveIdPreviousFrameIsAlive; + bool ActiveIdPreviousFrameHasBeenEdited; + ImGuiWindow* ActiveIdPreviousFrameWindow; + ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. - ImVec2 LastValidMousePos; - ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. + + // Next window/item data + ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions + bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions + ImGuiCond NextTreeNodeOpenCond; + + // Shared stacks ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() ImVector FontStack; // Stack for PushFont()/PopFont() ImVectorOpenPopupStack; // Which popups are open (persistent) ImVectorBeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) - ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions - bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions - ImGuiCond NextTreeNodeOpenCond; // Navigation data (for gamepad/keyboard) ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow' @@ -948,6 +955,7 @@ struct ImGuiContext ImVector TabSortByWidthBuffer; // Widget state + ImVec2 LastValidMousePos; ImGuiInputTextState InputTextState; ImFont InputTextPasswordFont; ImGuiID TempInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. @@ -1003,37 +1011,41 @@ struct ImGuiContext FontSize = FontBaseSize = 0.0f; FontAtlasOwnedByContext = shared_font_atlas ? false : true; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); - Time = 0.0f; FrameCount = 0; FrameCountEnded = FrameCountRendered = -1; + WindowsActiveCount = 0; CurrentWindow = NULL; HoveredWindow = NULL; HoveredRootWindow = NULL; + MovingWindow = NULL; + HoveredId = 0; HoveredIdAllowOverlap = false; HoveredIdPreviousFrame = 0; HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; ActiveId = 0; - ActiveIdPreviousFrame = 0; ActiveIdIsAlive = 0; ActiveIdTimer = 0.0f; ActiveIdIsJustActivated = false; ActiveIdAllowOverlap = false; ActiveIdHasBeenPressed = false; ActiveIdHasBeenEdited = false; - ActiveIdPreviousFrameIsAlive = false; - ActiveIdPreviousFrameHasBeenEdited = false; ActiveIdAllowNavDirFlags = 0x00; ActiveIdBlockNavInputFlags = 0x00; ActiveIdClickOffset = ImVec2(-1,-1); - ActiveIdWindow = ActiveIdPreviousFrameWindow = NULL; + ActiveIdWindow = NULL; ActiveIdSource = ImGuiInputSource_None; + + ActiveIdPreviousFrame = 0; + ActiveIdPreviousFrameIsAlive = false; + ActiveIdPreviousFrameHasBeenEdited = false; + ActiveIdPreviousFrameWindow = NULL; + LastActiveId = 0; LastActiveIdTimer = 0.0f; - LastValidMousePos = ImVec2(0.0f, 0.0f); - MovingWindow = NULL; + NextTreeNodeOpenVal = false; NextTreeNodeOpenCond = 0; @@ -1087,6 +1099,7 @@ struct ImGuiContext CurrentTabBar = NULL; + LastValidMousePos = ImVec2(0.0f, 0.0f); TempInputTextId = 0; ColorEditOptions = ImGuiColorEditFlags__OptionsDefault; DragCurrentAccumDirty = false; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e0ebdbc2..f09e80be 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5903,7 +5903,7 @@ void ImGui::EndMenuBar() PopClipRect(); PopID(); window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->MenuBarRect().Min.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. - window->DC.GroupStack.back().AdvanceCursor = false; + window->DC.GroupStack.back().EmitItem = false; EndGroup(); // Restore position on layer 0 window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; From 36e714a4590db3299cd72c695ff66c1fe62a47da Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 May 2019 14:45:41 +0200 Subject: [PATCH 347/566] Internal: Storing flags for NextWindowData so that we can clear everything with a single write and remove dummy condition fields. --- imgui.cpp | 38 ++++++++++---------- imgui_internal.h | 89 ++++++++++++++++++++++------------------------- imgui_widgets.cpp | 10 +++--- 3 files changed, 67 insertions(+), 70 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 808594bc..781614d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4636,7 +4636,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) { ImGuiContext& g = *GImGui; - if (g.NextWindowData.SizeConstraintCond != 0) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) { // Using -1,-1 on either X/Y axis to preserve the current size. ImRect cr = g.NextWindowData.SizeConstraintRect; @@ -4993,13 +4993,12 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar { ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); float alpha = 1.0f; - if (g.NextWindowData.BgAlphaCond != 0) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) alpha = g.NextWindowData.BgAlphaVal; if (alpha != 1.0f) bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); } - g.NextWindowData.BgAlphaCond = 0; // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) @@ -5130,7 +5129,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const bool window_just_created = (window == NULL); if (window_just_created) { - ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. + ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. window = CreateNewWindow(name, size_on_first_use, flags); } @@ -5194,7 +5193,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Process SetNextWindow***() calls bool window_pos_set_by_api = false; bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; - if (g.NextWindowData.PosCond) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) { window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) @@ -5210,13 +5209,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); } } - if (g.NextWindowData.SizeCond) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) { window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); } - if (g.NextWindowData.ContentSizeCond) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize) { // Adjust passed "client size" to become a "window size" window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal; @@ -5227,9 +5226,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); } - if (g.NextWindowData.CollapsedCond) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed) SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); - if (g.NextWindowData.FocusCond) + if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus) FocusWindow(window); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); @@ -5607,7 +5606,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->WriteAccessed = false; window->BeginCount++; - g.NextWindowData.Clear(); + g.NextWindowData.ClearFlags(); if (flags & ImGuiWindowFlags_ChildWindow) { @@ -6397,6 +6396,7 @@ void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pi { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos; g.NextWindowData.PosVal = pos; g.NextWindowData.PosPivotVal = pivot; g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; @@ -6406,6 +6406,7 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize; g.NextWindowData.SizeVal = size; g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; } @@ -6413,7 +6414,7 @@ void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data) { ImGuiContext& g = *GImGui; - g.NextWindowData.SizeConstraintCond = ImGuiCond_Always; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint; g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); g.NextWindowData.SizeCallback = custom_callback; g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; @@ -6422,14 +6423,15 @@ void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& s void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize; g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value. - g.NextWindowData.ContentSizeCond = ImGuiCond_Always; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed; g.NextWindowData.CollapsedVal = collapsed; g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; } @@ -6437,14 +6439,14 @@ void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) void ImGui::SetNextWindowFocus() { ImGuiContext& g = *GImGui; - g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus; } void ImGui::SetNextWindowBgAlpha(float alpha) { ImGuiContext& g = *GImGui; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha; g.NextWindowData.BgAlphaVal = alpha; - g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) } // FIXME: This is in window space (not screen space!). We should try to obsolete all those functions. @@ -7144,7 +7146,7 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) ImGuiContext& g = *GImGui; if (!IsPopupOpen(id)) { - g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } @@ -7166,7 +7168,7 @@ bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance { - g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; @@ -7182,13 +7184,13 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla const ImGuiID id = window->GetID(name); if (!IsPopupOpen(id)) { - g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values + g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } // Center modal windows by default // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. - if (g.NextWindowData.PosCond == 0) + if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings; diff --git a/imgui_internal.h b/imgui_internal.h index 868a3e98..494d5481 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -71,7 +71,7 @@ struct ImGuiInputTextState; // Internal state of the currently focused/e struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiNavMoveResult; // Result of a directional navigation move query result -struct ImGuiNextWindowData; // Storage for SetNexWindow** functions +struct ImGuiNextWindowData; // Storage for SetNextWindow** functions 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 @@ -82,17 +82,18 @@ struct ImGuiWindowTempData; // Temporary storage for one window (that's struct ImGuiWindowSettings; // Storage for window settings stored in .ini file (we keep one of those even if the actual window wasn't instanced during this session) // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. -typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical -typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() -typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() -typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() -typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags -typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() -typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d() -typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests -typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for Separator() - internal -typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior() -typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() +typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() +typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() +typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() +typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags +typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() +typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d() +typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests +typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions +typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx() +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior() +typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() //------------------------------------------------------------------------- // STB libraries includes @@ -743,44 +744,38 @@ struct ImGuiNavMoveResult void Clear() { ID = SelectScopeId = 0; Window = NULL; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); } }; +enum ImGuiNextWindowDataFlags_ +{ + ImGuiNextWindowDataFlags_None = 0, + ImGuiNextWindowDataFlags_HasPos = 1 << 0, + ImGuiNextWindowDataFlags_HasSize = 1 << 1, + ImGuiNextWindowDataFlags_HasContentSize = 1 << 2, + ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3, + ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4, + ImGuiNextWindowDataFlags_HasFocus = 1 << 5, + ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6 +}; + // Storage for SetNexWindow** functions struct ImGuiNextWindowData { - ImGuiCond PosCond; - ImGuiCond SizeCond; - ImGuiCond ContentSizeCond; - ImGuiCond CollapsedCond; - ImGuiCond SizeConstraintCond; - ImGuiCond FocusCond; - ImGuiCond BgAlphaCond; - ImVec2 PosVal; - ImVec2 PosPivotVal; - ImVec2 SizeVal; - ImVec2 ContentSizeVal; - bool CollapsedVal; - ImRect SizeConstraintRect; - ImGuiSizeCallback SizeCallback; - void* SizeCallbackUserData; - float BgAlphaVal; - ImVec2 MenuBarOffsetMinVal; // This is not exposed publicly, so we don't clear it. - - ImGuiNextWindowData() - { - PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0; - PosVal = PosPivotVal = SizeVal = ImVec2(0.0f, 0.0f); - ContentSizeVal = ImVec2(0.0f, 0.0f); - CollapsedVal = false; - SizeConstraintRect = ImRect(); - SizeCallback = NULL; - SizeCallbackUserData = NULL; - BgAlphaVal = FLT_MAX; - MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); - } - - void Clear() - { - PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0; - } + ImGuiNextWindowDataFlags Flags; + ImGuiCond PosCond; + ImGuiCond SizeCond; + ImGuiCond CollapsedCond; + ImVec2 PosVal; + ImVec2 PosPivotVal; + ImVec2 SizeVal; + ImVec2 ContentSizeVal; + bool CollapsedVal; + ImRect SizeConstraintRect; + ImGuiSizeCallback SizeCallback; + void* SizeCallbackUserData; + float BgAlphaVal; + ImVec2 MenuBarOffsetMinVal; // This is not exposed publicly, so we don't clear it. + + ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } + inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; } }; //----------------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f09e80be..490b672d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1350,8 +1350,8 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF { // Always consume the SetNextWindowSizeConstraint() call in our early return paths ImGuiContext& g = *GImGui; - ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond; - g.NextWindowData.SizeConstraintCond = 0; + bool has_window_size_constraint = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) != 0; + g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -1403,9 +1403,9 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF if (!popup_open) return false; - if (backup_next_window_size_constraint) + if (has_window_size_constraint) { - g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint; + g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint; g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w); } else @@ -1495,7 +1495,7 @@ bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(voi items_getter(data, *current_item, &preview_value); // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here. - if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond) + if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)) SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) From 632469d2e5533f2a3ffda2ccd5c96551b479a2b7 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 May 2019 15:11:25 +0200 Subject: [PATCH 348/566] Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Refactored SetNextItemXXX stuff to match SetNextWindowXXX code closely. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 24 ++++++++++++++---------- imgui.h | 7 +++++-- imgui_demo.cpp | 9 ++++++++- imgui_internal.h | 30 ++++++++++++++++++++++-------- imgui_widgets.cpp | 20 ++++++++++---------- 6 files changed, 60 insertions(+), 31 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d7f4ca26..641e11c1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -34,6 +34,7 @@ HOW TO UPDATE? Breaking Changes: - IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). +- Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). Other Changes: - Columns: Fixed Separator from creating an extraneous draw command. (#125) diff --git a/imgui.cpp b/imgui.cpp index 781614d2..3baeed9d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,7 @@ CODE When you are not sure about a 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. + - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). @@ -2840,6 +2841,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) window->DC.LastItemId = id; window->DC.LastItemRect = bb; window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None; + g.NextItemData.Flags = ImGuiNextItemDataFlags_None; #ifdef IMGUI_ENABLE_TEST_ENGINE if (id != 0) @@ -5794,8 +5796,9 @@ void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWind void ImGui::SetNextItemWidth(float item_width) { - ImGuiWindow* window = GetCurrentWindow(); - window->DC.NextItemWidth = item_width; + ImGuiContext& g = *GImGui; + g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth; + g.NextItemData.Width = item_width; } void ImGui::PushItemWidth(float item_width) @@ -5825,15 +5828,16 @@ void ImGui::PopItemWidth() } // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(), -// Then consume the +// Then _consume_ the SetNextItemWidth() data. float ImGui::GetNextItemWidth() { - ImGuiWindow* window = GImGui->CurrentWindow; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; float w; - if (window->DC.NextItemWidth != FLT_MAX) + if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth) { - w = window->DC.NextItemWidth; - window->DC.NextItemWidth = FLT_MAX; + w = g.NextItemData.Width; + g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; } else { @@ -5852,10 +5856,10 @@ float ImGui::GetNextItemWidth() // (rarely used, which is why we avoid calling this from GetNextItemWidth() and instead do a backup/restore here) float ImGui::CalcItemWidth() { - ImGuiWindow* window = GImGui->CurrentWindow; - float backup_next_item_width = window->DC.NextItemWidth; + ImGuiContext& g = *GImGui; + ImGuiNextItemDataFlags backup_flags = g.NextItemData.Flags; float w = GetNextItemWidth(); - window->DC.NextItemWidth = backup_next_item_width; + g.NextItemData.Flags = backup_flags; return w; } diff --git a/imgui.h b/imgui.h index 7c05d7c4..0bcea46b 100644 --- a/imgui.h +++ b/imgui.h @@ -494,9 +494,9 @@ namespace ImGui IMGUI_API void TreePop(); // ~ Unindent()+PopId() IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode - IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header + IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. @@ -1173,7 +1173,7 @@ enum ImGuiMouseCursor_ #endif }; -// Enumateration for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions +// Enumateration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions // Represent a condition. // Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. enum ImGuiCond_ @@ -1529,6 +1529,9 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.71 (from May 2019) + static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } + // OBSOLETED in 1.70 (from May 2019) static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.69 (from Mar 2019) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f9cb7c6b..7ce699d1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -568,13 +568,20 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Basic trees")) { for (int i = 0; i < 5; i++) + { + // Use SetNextItemOpen() so set the default state of a node to be open. + // We could also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing! + if (i == 0) + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i)) { ImGui::Text("blah blah"); ImGui::SameLine(); - if (ImGui::SmallButton("button")) { }; + if (ImGui::SmallButton("button")) {}; ImGui::TreePop(); } + } ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index 494d5481..d4508657 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -72,6 +72,7 @@ struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() intern struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiNavMoveResult; // Result of a directional navigation move query result struct ImGuiNextWindowData; // Storage for SetNextWindow** functions +struct ImGuiNextItemData; // Storage for SetNextItem** functions 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 @@ -90,6 +91,7 @@ typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // F typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d() typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests +typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx() typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior() @@ -778,6 +780,24 @@ struct ImGuiNextWindowData inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; } }; +enum ImGuiNextItemDataFlags_ +{ + ImGuiNextItemDataFlags_None = 0, + ImGuiNextItemDataFlags_HasWidth = 1 << 0, + ImGuiNextItemDataFlags_HasOpen = 1 << 1 +}; + +struct ImGuiNextItemData +{ + ImGuiNextItemDataFlags Flags; + float Width; // Set by SetNextItemWidth(). + bool OpenVal; // Set by SetNextItemOpen() function. + ImGuiCond OpenCond; + + ImGuiNextItemData() { memset(this, 0, sizeof(*this)); } + inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; } +}; + //----------------------------------------------------------------------------- // Tabs //----------------------------------------------------------------------------- @@ -858,8 +878,7 @@ struct ImGuiContext // Next window/item data ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions - bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions - ImGuiCond NextTreeNodeOpenCond; + ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions // Shared stacks ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() @@ -1041,9 +1060,6 @@ struct ImGuiContext LastActiveId = 0; LastActiveIdTimer = 0.0f; - NextTreeNodeOpenVal = false; - NextTreeNodeOpenCond = 0; - NavWindow = NULL; NavId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0; NavJustTabbedId = NavJustMovedToId = NavJustMovedToMultiSelectScopeId = NavNextActivateId = 0; @@ -1166,7 +1182,6 @@ struct IMGUI_API ImGuiWindowTempData // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default] float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window - float NextItemWidth; float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] ImVectorItemFlagsStack; ImVector ItemWidthStack; @@ -1202,7 +1217,6 @@ struct IMGUI_API ImGuiWindowTempData ItemFlags = ImGuiItemFlags_Default_; ItemWidth = 0.0f; - NextItemWidth = +FLT_MAX; TextWrapPos = -1.0f; memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); @@ -1569,7 +1583,7 @@ namespace ImGui IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f); IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); - IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging + IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging IMGUI_API void TreePushOverrideID(ImGuiID id); // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 490b672d..301634c9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4906,7 +4906,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl // - TreePop() // - TreeAdvanceToLabelPos() // - GetTreeNodeToLabelSpacing() -// - SetNextTreeNodeOpen() +// - SetNextItemOpen() // - CollapsingHeader() //------------------------------------------------------------------------- @@ -5000,17 +5000,17 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) if (flags & ImGuiTreeNodeFlags_Leaf) return true; - // We only write to the tree storage if the user clicks (or explicitly use SetNextTreeNode*** functions) + // We only write to the tree storage if the user clicks (or explicitly use the SetNextItemOpen function) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; bool is_open; - if (g.NextTreeNodeOpenCond != 0) + if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasOpen) { - if (g.NextTreeNodeOpenCond & ImGuiCond_Always) + if (g.NextItemData.OpenCond & ImGuiCond_Always) { - is_open = g.NextTreeNodeOpenVal; + is_open = g.NextItemData.OpenVal; storage->SetInt(id, is_open); } else @@ -5019,7 +5019,7 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { - is_open = g.NextTreeNodeOpenVal; + is_open = g.NextItemData.OpenVal; storage->SetInt(id, is_open); } else @@ -5027,7 +5027,6 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) is_open = stored_value != 0; } } - g.NextTreeNodeOpenCond = 0; } else { @@ -5256,13 +5255,14 @@ float ImGui::GetTreeNodeToLabelSpacing() return g.FontSize + (g.Style.FramePadding.x * 2.0f); } -void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond) +void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond) { ImGuiContext& g = *GImGui; if (g.CurrentWindow->SkipItems) return; - g.NextTreeNodeOpenVal = is_open; - g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always; + g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasOpen; + g.NextItemData.OpenVal = is_open; + g.NextItemData.OpenCond = cond ? cond : ImGuiCond_Always; } // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). From 64dbd932d2b8056a7ad7c85d68f76f2f7738e889 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 May 2019 15:29:00 +0200 Subject: [PATCH 349/566] Internal: Removed GetNextItemWidth(), relying on ItemAdd or NextItemData.ClearFlags() to clear the width data. Amend 5078fa20 and undo some of its effects of imgui_widgets.cpp --- imgui.cpp | 34 +++++++++++----------------------- imgui_internal.h | 1 - imgui_widgets.cpp | 42 ++++++++++++++++++++++++------------------ 3 files changed, 35 insertions(+), 42 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3baeed9d..e5b2da50 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5803,14 +5803,17 @@ void ImGui::SetNextItemWidth(float item_width) void ImGui::PushItemWidth(float item_width) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); + g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; } void ImGui::PushMultiItemsWidths(int components, float w_full) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; const ImGuiStyle& style = GImGui->Style; const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); @@ -5818,6 +5821,7 @@ void ImGui::PushMultiItemsWidths(int components, float w_full) for (int i = 0; i < components-1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); + g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; } void ImGui::PopItemWidth() @@ -5827,22 +5831,17 @@ void ImGui::PopItemWidth() window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } -// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(), -// Then _consume_ the SetNextItemWidth() data. -float ImGui::GetNextItemWidth() +// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(). +// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() +float ImGui::CalcItemWidth() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float w; if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth) - { w = g.NextItemData.Width; - g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; - } else - { w = window->DC.ItemWidth; - } if (w < 0.0f) { float region_max_x = GetWorkRectMax().x; @@ -5852,21 +5851,10 @@ float ImGui::GetNextItemWidth() return w; } -// Calculate item width *without* popping/consuming NextItemWidth if it was set. -// (rarely used, which is why we avoid calling this from GetNextItemWidth() and instead do a backup/restore here) -float ImGui::CalcItemWidth() -{ - ImGuiContext& g = *GImGui; - ImGuiNextItemDataFlags backup_flags = g.NextItemData.Flags; - float w = GetNextItemWidth(); - g.NextItemData.Flags = backup_flags; - return w; -} - -// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == GetNextItemWidth(). +// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. // Note that only CalcItemWidth() is publicly exposed. -// The 4.0f here may be changed to match GetNextItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) +// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui_internal.h b/imgui_internal.h index d4508657..71628f59 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1475,7 +1475,6 @@ namespace ImGui IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); - IMGUI_API float GetNextItemWidth(); IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 301634c9..c59558e4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -320,7 +320,7 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float w = GetNextItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); @@ -1091,7 +1091,7 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over const ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; - ImVec2 size = CalcItemSize(size_arg, GetNextItemWidth(), g.FontSize + style.FramePadding.y*2.0f); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f); ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, 0)) @@ -1364,7 +1364,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const float expected_w = GetNextItemWidth(); + const float expected_w = CalcItemWidth(); const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : expected_w; const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); @@ -1991,8 +1991,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = GetNextItemWidth(); - + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); @@ -2064,7 +2063,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int bool value_changed = false; BeginGroup(); PushID(label); - PushMultiItemsWidths(components, GetNextItemWidth()); + PushMultiItemsWidths(components, CalcItemWidth()); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { @@ -2111,7 +2110,7 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); - PushMultiItemsWidths(2, GetNextItemWidth()); + PushMultiItemsWidths(2, CalcItemWidth()); bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power); PopItemWidth(); @@ -2156,7 +2155,7 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); - PushMultiItemsWidths(2, GetNextItemWidth()); + PushMultiItemsWidths(2, CalcItemWidth()); bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format); PopItemWidth(); @@ -2434,7 +2433,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = GetNextItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); @@ -2512,7 +2511,7 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i bool value_changed = false; BeginGroup(); PushID(label); - PushMultiItemsWidths(components, GetNextItemWidth()); + PushMultiItemsWidths(components, CalcItemWidth()); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { @@ -2800,7 +2799,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() PushID(label); - SetNextItemWidth(ImMax(1.0f, GetNextItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); + SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format); @@ -2848,7 +2847,7 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, in bool value_changed = false; BeginGroup(); PushID(label); - PushMultiItemsWidths(components, GetNextItemWidth()); + PushMultiItemsWidths(components, CalcItemWidth()); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { @@ -3298,7 +3297,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ BeginGroup(); const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - ImVec2 size = CalcItemSize(size_arg, GetNextItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); @@ -4056,8 +4055,9 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag const ImGuiStyle& style = g.Style; const float square_sz = GetFrameHeight(); const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); - const float w_items_all = GetNextItemWidth() - w_extra; + const float w_items_all = CalcItemWidth() - w_extra; const char* label_display_end = FindRenderedTextEnd(label); + g.NextItemData.ClearFlags(); BeginGroup(); PushID(label); @@ -4337,6 +4337,9 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl ImGuiStyle& style = g.Style; ImGuiIO& io = g.IO; + const float width = CalcItemWidth(); + g.NextItemData.ClearFlags(); + PushID(label); BeginGroup(); @@ -4363,7 +4366,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl ImVec2 picker_pos = window->DC.CursorPos; float square_sz = GetFrameHeight(); float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars - float sv_picker_size = ImMax(bars_width * 1, GetNextItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box + float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x; float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x; float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f); @@ -5255,6 +5258,7 @@ float ImGui::GetTreeNodeToLabelSpacing() return g.FontSize + (g.Style.FramePadding.x * 2.0f); } +// Set next TreeNode/CollapsingHeader open state. void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond) { ImGuiContext& g = *GImGui; @@ -5452,20 +5456,22 @@ bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty" bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - const ImGuiStyle& style = GetStyle(); + const ImGuiStyle& style = g.Style; const ImGuiID id = GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. - ImVec2 size = CalcItemSize(size_arg, GetNextItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy. + g.NextItemData.ClearFlags(); if (!IsRectVisible(bb.Min, bb.Max)) { @@ -5578,7 +5584,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge const ImVec2 label_size = CalcTextSize(label, NULL, true); if (frame_size.x == 0.0f) - frame_size.x = GetNextItemWidth(); + frame_size.x = CalcItemWidth(); if (frame_size.y == 0.0f) frame_size.y = label_size.y + (style.FramePadding.y * 2); From 99a845053a815e7767b0d2c785a640b1cded871d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 May 2019 18:15:39 +0200 Subject: [PATCH 350/566] Internal: Renamed fields + minor tweaks (probably shallow break stack-layout pr, sorry!) --- docs/TODO.txt | 1 + imgui.cpp | 44 ++++++++++++++++++++++---------------------- imgui_internal.h | 26 +++++++++++++------------- imgui_widgets.cpp | 28 ++++++++++++++-------------- 4 files changed, 50 insertions(+), 49 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 97594ba4..79b170ad 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -67,6 +67,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: selectable: generic BeginSelectable()/EndSelectable() mechanism. - widgets: selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - widgets: checkbox with custom glyph inside frame. + - widgets: IsItemEdited() on InputScalar keeps returning true because InputText vs formatted output are mismatched. - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) diff --git a/imgui.cpp b/imgui.cpp index e5b2da50..7cf0ba6b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2679,8 +2679,8 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) if (g.ActiveIdIsJustActivated) { g.ActiveIdTimer = 0.0f; - g.ActiveIdHasBeenPressed = false; - g.ActiveIdHasBeenEdited = false; + g.ActiveIdHasBeenPressedBefore = false; + g.ActiveIdHasBeenEditedBefore = false; if (id != 0) { g.LastActiveId = id; @@ -2759,7 +2759,7 @@ void ImGui::MarkItemEdited(ImGuiID id) IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive); IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); - g.ActiveIdHasBeenEdited = true; + g.ActiveIdHasBeenEditedBefore = true; g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited; } @@ -2792,10 +2792,11 @@ void ImGui::ItemSize(const ImVec2& size, float text_offset_y) return; // Always align ourselves on pixel boundaries - const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y); - const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); + const float line_height = ImMax(window->DC.CurrLineSize.y, size.y); + const float text_base_offset = ImMax(window->DC.CurrLineTextBaseOffset, text_offset_y); //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG] - window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); + window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x; + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); @@ -2804,7 +2805,7 @@ void ImGui::ItemSize(const ImVec2& size, float text_offset_y) window->DC.PrevLineSize.y = line_height; window->DC.PrevLineTextBaseOffset = text_base_offset; - window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f; + window->DC.CurrLineSize.y = window->DC.CurrLineTextBaseOffset = 0.0f; // Horizontal layout mode if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) @@ -3529,7 +3530,7 @@ void ImGui::NewFrame() g.LastActiveIdTimer += g.IO.DeltaTime; g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow; - g.ActiveIdPreviousFrameHasBeenEdited = g.ActiveIdHasBeenEdited; + g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore; g.ActiveIdIsAlive = 0; g.ActiveIdPreviousFrameIsAlive = false; g.ActiveIdIsJustActivated = false; @@ -4341,7 +4342,7 @@ bool ImGui::IsItemDeactivated() bool ImGui::IsItemDeactivatedAfterEdit() { ImGuiContext& g = *GImGui; - return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEdited || (g.ActiveId == 0 && g.ActiveIdHasBeenEdited)); + return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore)); } bool ImGui::IsItemFocused() @@ -5530,8 +5531,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; - window->DC.CurrentLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); - window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.NavHideHighlightOneFrame = false; window->DC.NavHasScroll = (GetWindowScrollMaxY(window) > 0.0f); window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; @@ -6776,8 +6777,8 @@ void ImGui::BeginGroup() group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.BackupIndent = window->DC.Indent; group_data.BackupGroupOffset = window->DC.GroupOffset; - group_data.BackupCurrentLineSize = window->DC.CurrentLineSize; - group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; + group_data.BackupCurrLineSize = window->DC.CurrLineSize; + group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset; group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; group_data.EmitItem = true; @@ -6785,7 +6786,7 @@ void ImGui::BeginGroup() window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; window->DC.Indent = window->DC.GroupOffset; window->DC.CursorMaxPos = window->DC.CursorPos; - window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); if (g.LogEnabled) g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return } @@ -6804,8 +6805,8 @@ void ImGui::EndGroup() window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); window->DC.Indent = group_data.BackupIndent; window->DC.GroupOffset = group_data.BackupGroupOffset; - window->DC.CurrentLineSize = group_data.BackupCurrentLineSize; - window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; + window->DC.CurrLineSize = group_data.BackupCurrLineSize; + window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset; if (g.LogEnabled) g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return @@ -6815,7 +6816,7 @@ void ImGui::EndGroup() return; } - window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ItemSize(group_bb.GetSize(), 0.0f); ItemAdd(group_bb, 0); @@ -6832,7 +6833,6 @@ void ImGui::EndGroup() window->DC.LastItemRect = group_bb; window->DC.GroupStack.pop_back(); - //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] } @@ -6860,8 +6860,8 @@ void ImGui::SameLine(float offset_from_start_x, float spacing_w) window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } - window->DC.CurrentLineSize = window->DC.PrevLineSize; - window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; + window->DC.CurrLineSize = window->DC.PrevLineSize; + window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; } void ImGui::Indent(float indent_w) @@ -8435,8 +8435,8 @@ void ImGui::NextColumn() } window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->DC.CursorPos.y = columns->LineMinY; - window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); - window->DC.CurrentLineTextBaseOffset = 0.0f; + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = 0.0f; PushColumnClipRect(columns->Current); PushItemWidth(GetColumnWidth() * 0.65f); // FIXME-COLUMNS: Move on columns setup diff --git a/imgui_internal.h b/imgui_internal.h index 71628f59..048ee49d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -574,8 +574,8 @@ struct ImGuiGroupData ImVec2 BackupCursorMaxPos; ImVec1 BackupIndent; ImVec1 BackupGroupOffset; - ImVec2 BackupCurrentLineSize; - float BackupCurrentLineTextBaseOffset; + ImVec2 BackupCurrLineSize; + float BackupCurrLineTextBaseOffset; ImGuiID BackupActiveIdIsAlive; bool BackupActiveIdPreviousFrameIsAlive; bool EmitItem; @@ -774,7 +774,7 @@ struct ImGuiNextWindowData ImGuiSizeCallback SizeCallback; void* SizeCallbackUserData; float BgAlphaVal; - ImVec2 MenuBarOffsetMinVal; // This is not exposed publicly, so we don't clear it. + ImVec2 MenuBarOffsetMinVal; // *Always on* This is not exposed publicly, so we don't clear it. ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; } @@ -861,8 +861,8 @@ struct ImGuiContext float ActiveIdTimer; bool ActiveIdIsJustActivated; // Set at the time of activation for one frame bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) - bool ActiveIdHasBeenPressed; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. - bool ActiveIdHasBeenEdited; // Was the value associated to the widget Edited over the course of the Active state. + bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. + bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. int ActiveIdAllowNavDirFlags; // Active widget allows using directional navigation (e.g. can activate a button and move away from it) int ActiveIdBlockNavInputFlags; ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) @@ -870,7 +870,7 @@ struct ImGuiContext ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard) ImGuiID ActiveIdPreviousFrame; bool ActiveIdPreviousFrameIsAlive; - bool ActiveIdPreviousFrameHasBeenEdited; + bool ActiveIdPreviousFrameHasBeenEditedBefore; ImGuiWindow* ActiveIdPreviousFrameWindow; ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. @@ -1044,8 +1044,8 @@ struct ImGuiContext ActiveIdTimer = 0.0f; ActiveIdIsJustActivated = false; ActiveIdAllowOverlap = false; - ActiveIdHasBeenPressed = false; - ActiveIdHasBeenEdited = false; + ActiveIdHasBeenPressedBefore = false; + ActiveIdHasBeenEditedBefore = false; ActiveIdAllowNavDirFlags = 0x00; ActiveIdBlockNavInputFlags = 0x00; ActiveIdClickOffset = ImVec2(-1,-1); @@ -1054,7 +1054,7 @@ struct ImGuiContext ActiveIdPreviousFrame = 0; ActiveIdPreviousFrameIsAlive = false; - ActiveIdPreviousFrameHasBeenEdited = false; + ActiveIdPreviousFrameHasBeenEditedBefore = false; ActiveIdPreviousFrameWindow = NULL; LastActiveId = 0; @@ -1154,9 +1154,9 @@ struct IMGUI_API ImGuiWindowTempData ImVec2 CursorPosPrevLine; ImVec2 CursorStartPos; // Initial position in client area with padding ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Turned into window->SizeContents at the beginning of next frame - ImVec2 CurrentLineSize; - float CurrentLineTextBaseOffset; + ImVec2 CurrLineSize; ImVec2 PrevLineSize; + float CurrLineTextBaseOffset; float PrevLineTextBaseOffset; int TreeDepth; ImU32 TreeStoreMayJumpToParentOnPop; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary. @@ -1197,8 +1197,8 @@ struct IMGUI_API ImGuiWindowTempData ImGuiWindowTempData() { CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); - CurrentLineSize = PrevLineSize = ImVec2(0.0f, 0.0f); - CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; + CurrLineSize = PrevLineSize = ImVec2(0.0f, 0.0f); + CurrLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; TreeDepth = 0; TreeStoreMayJumpToParentOnPop = 0x00; LastItemId = 0; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c59558e4..117a047d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -139,7 +139,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) if (text_end == NULL) text_end = text + strlen(text); // FIXME-OPT - const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); + const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset); const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = (wrap_pos_x >= 0.0f); if (text_end - text > 2000 && !wrap_enabled) @@ -358,8 +358,8 @@ void ImGui::BulletTextV(const char* fmt, va_list args) const char* text_begin = g.TempBuffer; const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); - const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it - const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it + const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding ItemSize(bb); if (!ItemAdd(bb, 0)) @@ -563,7 +563,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool if (g.ActiveId == id) { if (pressed) - g.ActiveIdHasBeenPressed = true; + g.ActiveIdHasBeenPressedBefore = true; if (g.ActiveIdSource == ImGuiInputSource_Mouse) { if (g.ActiveIdIsJustActivated) @@ -611,8 +611,8 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 pos = window->DC.CursorPos; - if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) - pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); const ImRect bb(pos, pos + size); @@ -1125,7 +1125,7 @@ void ImGui::Bullet() ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); ItemSize(bb); if (!ItemAdd(bb, 0)) @@ -1179,7 +1179,7 @@ void ImGui::NewLine() ImGuiContext& g = *GImGui; const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; window->DC.LayoutType = ImGuiLayoutType_Vertical; - if (window->DC.CurrentLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. ItemSize(ImVec2(0,0)); else ItemSize(ImVec2(0.0f, g.FontSize)); @@ -1193,8 +1193,8 @@ void ImGui::AlignTextToFramePadding() return; ImGuiContext& g = *GImGui; - window->DC.CurrentLineSize.y = ImMax(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y * 2); - window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); + window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2); + window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); } // Horizontal/vertical separating line @@ -1213,7 +1213,7 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) { // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. float y1 = window->DC.CursorPos.y; - float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y; + float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y; const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness_draw, y2)); ItemSize(ImVec2(thickness_layout, 0.0f)); if (!ItemAdd(bb, 0)) @@ -5060,8 +5060,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const ImVec2 label_size = CalcTextSize(label, label_end, false); // We vertically grow up to current line height up the typical widget height. - const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it - const float frame_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + const float text_base_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it + const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(GetWorkRectMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { @@ -5330,7 +5330,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); ImVec2 pos = window->DC.CursorPos; - pos.y += window->DC.CurrentLineTextBaseOffset; + pos.y += window->DC.CurrLineTextBaseOffset; ImRect bb_inner(pos, pos + size); ItemSize(size); From d3a387cc1865b7d147a73f728b7823fb965a00f9 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 May 2019 19:04:57 +0200 Subject: [PATCH 351/566] Fixed InputFloatX, SliderFloatX, DragFloatX functions erroneously reporting IsItemEdited() multiple times when the text input doesn't match the formatted output value (e.g. input "1" shows "1.000"). It wasn't much of a problem because we typically use the return value instead of IsItemEdited() here. (#1875, #2034) --- docs/CHANGELOG.txt | 3 +++ docs/TODO.txt | 1 - imgui.h | 3 ++- imgui_widgets.cpp | 14 +++++++++++--- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 641e11c1..31c8ed8d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ Other Changes: - Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. +- Fixed InputFloatX, SliderFloatX, DragFloatX functions erroneously reporting IsItemEdited() multiple + times when the text input doesn't match the formatted output value (e.g. input "1" shows "1.000"). + It wasn't much of a problem because we typically use the return value instead of IsItemEdited() here. - Scrollbar: Very minor bounding box adjustment to cope with various border size. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. diff --git a/docs/TODO.txt b/docs/TODO.txt index 79b170ad..97594ba4 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -67,7 +67,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: selectable: generic BeginSelectable()/EndSelectable() mechanism. - widgets: selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - widgets: checkbox with custom glyph inside frame. - - widgets: IsItemEdited() on InputScalar keeps returning true because InputText vs formatted output are mismatched. - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) diff --git a/imgui.h b/imgui.h index 0bcea46b..75a2ae7f 100644 --- a/imgui.h +++ b/imgui.h @@ -763,7 +763,8 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input) ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) // [Internal] - ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() + ImGuiInputTextFlags_Multiline = 1 << 20, // For internal use by InputTextMultiline() + ImGuiInputTextFlags_NoMarkEdited = 1 << 21 // For internal use by functions using InputText() before reformatting data }; // Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 117a047d..bcd5d3b9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2760,7 +2760,8 @@ bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImStrTrimBlanks(data_buf); g.CurrentWindow->DC.CursorPos = bb.Min; - ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); + ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; + flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); bool value_changed = InputTextEx(label, NULL, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags); if (init) { @@ -2769,7 +2770,11 @@ bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, g.TempInputTextId = g.ActiveId; } if (value_changed) - return DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, NULL); + { + value_changed = DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, NULL); + if (value_changed) + MarkItemEdited(id); + } return false; } @@ -2792,6 +2797,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0) flags |= ImGuiInputTextFlags_CharsDecimal; flags |= ImGuiInputTextFlags_AutoSelectAll; + flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselve by comparing the actual data rather than the string. if (step != NULL) { @@ -2833,6 +2839,8 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p if (InputText(label, buf, IM_ARRAYSIZE(buf), flags)) value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format); } + if (value_changed) + MarkItemEdited(window->DC.LastItemId); return value_changed; } @@ -4012,7 +4020,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - if (value_changed) + if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited)) MarkItemEdited(id); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags); From fc3c3de551cbc5c13443f6e25977078006275713 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 13 May 2019 19:05:41 +0200 Subject: [PATCH 352/566] Fixed uses of IsItemDeactivated(), IsItemDeactivatedAfterEdit() on multi-components widgets and after EndGroup(). (#2550, #1875) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 14 ++++++++++++++ imgui_internal.h | 6 +++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 31c8ed8d..8a2d53c2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,8 @@ Other Changes: - Fixed InputFloatX, SliderFloatX, DragFloatX functions erroneously reporting IsItemEdited() multiple times when the text input doesn't match the formatted output value (e.g. input "1" shows "1.000"). It wasn't much of a problem because we typically use the return value instead of IsItemEdited() here. +- Fixed uses of IsItemDeactivated(), IsItemDeactivatedAfterEdit() on multi-components widgets and + after EndGroup(). (#2550, #1875) - Scrollbar: Very minor bounding box adjustment to cope with various border size. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. diff --git a/imgui.cpp b/imgui.cpp index 7cf0ba6b..20840931 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2692,6 +2692,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) g.ActiveIdBlockNavInputFlags = 0; g.ActiveIdAllowOverlap = false; g.ActiveIdWindow = window; + g.ActiveIdHasBeenEditedThisFrame = false; if (id) { g.ActiveIdIsAlive = id; @@ -2759,6 +2760,7 @@ void ImGui::MarkItemEdited(ImGuiID id) IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive); IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); + g.ActiveIdHasBeenEditedThisFrame = true; g.ActiveIdHasBeenEditedBefore = true; g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited; } @@ -3532,6 +3534,7 @@ void ImGui::NewFrame() g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow; g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore; g.ActiveIdIsAlive = 0; + g.ActiveIdHasBeenEditedThisFrame = false; g.ActiveIdPreviousFrameIsAlive = false; g.ActiveIdIsJustActivated = false; if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId) @@ -4336,6 +4339,8 @@ bool ImGui::IsItemDeactivated() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated) + return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0; return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId); } @@ -6832,6 +6837,15 @@ void ImGui::EndGroup() window->DC.LastItemId = g.ActiveIdPreviousFrame; window->DC.LastItemRect = group_bb; + // Forward Edited flag + if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame) + window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited; + + // Forward Deactivated flag + window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated; + if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame) + window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated; + window->DC.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] } diff --git a/imgui_internal.h b/imgui_internal.h index 048ee49d..a44e5667 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -381,7 +381,9 @@ enum ImGuiItemStatusFlags_ ImGuiItemStatusFlags_HoveredRect = 1 << 0, ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) - ImGuiItemStatusFlags_ToggledSelection = 1 << 3 // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues. + ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues. + ImGuiItemStatusFlags_HasDeactivated = 1 << 4, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. + ImGuiItemStatusFlags_Deactivated = 1 << 5 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. #ifdef IMGUI_ENABLE_TEST_ENGINE , // [imgui-test only] @@ -863,6 +865,7 @@ struct ImGuiContext bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. + bool ActiveIdHasBeenEditedThisFrame; int ActiveIdAllowNavDirFlags; // Active widget allows using directional navigation (e.g. can activate a button and move away from it) int ActiveIdBlockNavInputFlags; ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) @@ -1046,6 +1049,7 @@ struct ImGuiContext ActiveIdAllowOverlap = false; ActiveIdHasBeenPressedBefore = false; ActiveIdHasBeenEditedBefore = false; + ActiveIdHasBeenEditedThisFrame = false; ActiveIdAllowNavDirFlags = 0x00; ActiveIdBlockNavInputFlags = 0x00; ActiveIdClickOffset = ImVec2(-1,-1); From 679cf7434e1190e40e79da0734c3a1c3d0a44e81 Mon Sep 17 00:00:00 2001 From: Lionel Landwerlin Date: Sat, 18 May 2019 09:43:30 +0100 Subject: [PATCH 353/566] Fix undefined behavior (#2561) --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 467555cf..c352db05 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1779,7 +1779,7 @@ static void UnpackBoolVectorToFlatIndexList(const ImBoolVector* in, ImVectorpush_back((int)((it - it_begin) << 5) + bit_n); } From e6109a914547ab065acebfdd366779a3af130d50 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 18 May 2019 11:18:12 +0200 Subject: [PATCH 354/566] Fixed ColorEdit breakage introduced by d3a387c (#2557, #1875, #2034) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bcd5d3b9..d34f519c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2775,7 +2775,7 @@ bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, if (value_changed) MarkItemEdited(id); } - return false; + return value_changed; } bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_ptr, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags) From 2e5860b5a0c14412ae209819ca19891ba3f7276d Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 18 May 2019 13:00:00 +0200 Subject: [PATCH 355/566] Docking: Fixed incomplete merge of 36e714a leading to undocking. #2109 --- imgui.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 14a33004..26b39a98 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13724,8 +13724,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) // Calling SetNextWindowPos() undock windows by default (by setting PosUndock) bool want_undock = false; want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0; - want_undock |= (g.NextWindowData.PosCond && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock); - g.NextWindowData.PosUndock = false; + want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock; if (want_undock) { DockContextProcessUndockWindow(ctx, window); From 02de498a41d0a42f8996adba3157c3a622ee6303 Mon Sep 17 00:00:00 2001 From: Andrew Willmott Date: Sat, 18 May 2019 16:34:58 +0100 Subject: [PATCH 356/566] Add native mac copy/paste support to match win32 (#2546) --- .../project.pbxproj | 6 --- examples/imgui_impl_osx.mm | 26 --------- imgui.cpp | 54 +++++++++++++++++++ 3 files changed, 54 insertions(+), 32 deletions(-) diff --git a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj index 20504102..5bdf74b5 100644 --- a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj +++ b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj @@ -38,14 +38,11 @@ 4080A99F20B034280036BA46 /* imgui_impl_osx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_osx.mm; path = ../imgui_impl_osx.mm; sourceTree = ""; }; 4080A9A020B034280036BA46 /* imgui_impl_opengl2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_opengl2.h; path = ../imgui_impl_opengl2.h; sourceTree = ""; }; 4080A9A120B034280036BA46 /* imgui_impl_osx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_osx.h; path = ../imgui_impl_osx.h; sourceTree = ""; }; - 4080A9A420B0343C0036BA46 /* stb_truetype.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = stb_truetype.h; path = ../../stb_truetype.h; sourceTree = ""; }; 4080A9A520B0343C0036BA46 /* imgui_internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_internal.h; path = ../../imgui_internal.h; sourceTree = ""; }; 4080A9A620B0343C0036BA46 /* imgui_demo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_demo.cpp; path = ../../imgui_demo.cpp; sourceTree = ""; }; 4080A9A720B0343C0036BA46 /* imgui.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui.cpp; path = ../../imgui.cpp; sourceTree = ""; }; 4080A9A820B0343C0036BA46 /* imgui.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui.h; path = ../../imgui.h; sourceTree = ""; }; - 4080A9A920B0343C0036BA46 /* stb_rect_pack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = stb_rect_pack.h; path = ../../stb_rect_pack.h; sourceTree = ""; }; 4080A9AA20B0343C0036BA46 /* imgui_draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_draw.cpp; path = ../../imgui_draw.cpp; sourceTree = ""; }; - 4080A9AB20B0343C0036BA46 /* stb_textedit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = stb_textedit.h; path = ../../stb_textedit.h; sourceTree = ""; }; 4080A9AC20B0343C0036BA46 /* imconfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imconfig.h; path = ../../imconfig.h; sourceTree = ""; }; 4080A9B220B034E40036BA46 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; 4080A9B420B034EA0036BA46 /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; }; @@ -74,9 +71,6 @@ 4080A9A620B0343C0036BA46 /* imgui_demo.cpp */, 4080A9AA20B0343C0036BA46 /* imgui_draw.cpp */, 4080A9A520B0343C0036BA46 /* imgui_internal.h */, - 4080A9A920B0343C0036BA46 /* stb_rect_pack.h */, - 4080A9AB20B0343C0036BA46 /* stb_textedit.h */, - 4080A9A420B0343C0036BA46 /* stb_truetype.h */, 4080A99E20B034280036BA46 /* imgui_impl_opengl2.cpp */, 4080A9A020B034280036BA46 /* imgui_impl_opengl2.h */, 4080A9A120B034280036BA46 /* imgui_impl_osx.h */, diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 34a61ff5..a1713ea9 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -55,32 +55,6 @@ bool ImGui_ImplOSX_Init() io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; - io.SetClipboardTextFn = [](void*, const char* str) -> void - { - NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; - [pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil]; - [pasteboard setString:[NSString stringWithUTF8String:str] forType:NSPasteboardTypeString]; - }; - - io.GetClipboardTextFn = [](void*) -> const char* - { - NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; - NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]]; - if (![available isEqualToString:NSPasteboardTypeString]) - return NULL; - - NSString* string = [pasteboard stringForType:NSPasteboardTypeString]; - if (string == nil) - return NULL; - - const char* string_c = (const char*)[string UTF8String]; - size_t string_len = strlen(string_c); - static ImVector s_clipboard; - s_clipboard.resize((int)string_len + 1); - strcpy(s_clipboard.Data, string_c); - return s_clipboard.Data; - }; - return true; } diff --git a/imgui.cpp b/imgui.cpp index 20840931..1ae4fbbb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9524,6 +9524,8 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl #else #include #endif +#elif defined(__APPLE__) +#include #endif // Win32 API clipboard implementation @@ -9576,6 +9578,58 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) ::CloseClipboard(); } +#elif defined(__APPLE__) && TARGET_OS_OSX && !defined(IMGUI_DISABLE_OSX_FUNCTIONS) +#include // use ye olde worlde API to avoid need for separate .mm file +static PasteboardRef main_clipboard = 0; + +static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +{ + if (!main_clipboard) + PasteboardCreate(kPasteboardClipboard, &main_clipboard); + PasteboardClear(main_clipboard); + CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*) text, strlen(text)); + if (cf_data) + { + PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID) 1, CFSTR("public.utf8-plain-text"), cf_data, 0); + CFRelease(cf_data); + } +} + +static const char* GetClipboardTextFn_DefaultImpl(void*) +{ + if (!main_clipboard) + PasteboardCreate(kPasteboardClipboard, &main_clipboard); + PasteboardSynchronize(main_clipboard); + + ItemCount item_count = 0; + PasteboardGetItemCount(main_clipboard, &item_count); + + for (int i = 0; i < item_count; i++) + { + PasteboardItemID item_id = 0; + PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id); + CFArrayRef flavor_type_array = 0; + PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array); + for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++) + { + CFDataRef cf_data; + if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr) + { + static ImVector clipboard_text; + + int length = (int) CFDataGetLength(cf_data); + clipboard_text.resize(length + 1); + CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*) clipboard_text.Data); + clipboard_text[length] = 0; + + CFRelease(cf_data); + return clipboard_text.Data; + } + } + } + return ""; +} + #else // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers From 31e3e861ef02b5c5dc677de447d2579bb29e033e Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 18 May 2019 17:44:09 +0200 Subject: [PATCH 357/566] Update changelog, comments, made empty/no-text clipboard return NULL as with other implementation. Minor style tweaks. (#2546) Fixed IMGUI_DISABLE_WIN32_FUNCTIONS not disabling IME code. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_osx.mm | 4 ++++ imconfig.h | 3 ++- imgui.cpp | 24 +++++++++++------------- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8a2d53c2..d784c843 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: - Scrollbar: Very minor bounding box adjustment to cope with various border size. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. +- Add native Mac clipboard copy/paste default implementation in core library to match what we are + dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index a1713ea9..c5562b4d 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-18: Misc: Removed clipboard handlers as they are now supported by core imgui.cpp. // 2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-07-07: Initial version. @@ -55,6 +56,9 @@ bool ImGui_ImplOSX_Init() io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; + // We don't set the io.SetClipboardTextFn/io.GetClipboardTextFn handlers, + // because imgui.cpp has a default for them that works with OSX. + return true; } diff --git a/imconfig.h b/imconfig.h index 825505bf..b496ae91 100644 --- a/imconfig.h +++ b/imconfig.h @@ -31,7 +31,8 @@ //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow. -//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function. +//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). +//#define IMGUI_DISABLE_OSX_FUNCTIONS // [OSX] Won't use and link with any OSX function (clipboard). //#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf. //#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h. //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). diff --git a/imgui.cpp b/imgui.cpp index 1ae4fbbb..66a4008f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9528,13 +9528,13 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl #include #endif -// Win32 API clipboard implementation #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) #ifdef _MSC_VER #pragma comment(lib, "user32") #endif +// Win32 clipboard implementation static const char* GetClipboardTextFn_DefaultImpl(void*) { static ImVector buf_local; @@ -9579,18 +9579,20 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) } #elif defined(__APPLE__) && TARGET_OS_OSX && !defined(IMGUI_DISABLE_OSX_FUNCTIONS) -#include // use ye olde worlde API to avoid need for separate .mm file + +#include // Use old API to avoid need for separate .mm file static PasteboardRef main_clipboard = 0; +// OSX clipboard implementation static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!main_clipboard) PasteboardCreate(kPasteboardClipboard, &main_clipboard); PasteboardClear(main_clipboard); - CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*) text, strlen(text)); + CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text)); if (cf_data) { - PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID) 1, CFSTR("public.utf8-plain-text"), cf_data, 0); + PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0); CFRelease(cf_data); } } @@ -9603,7 +9605,6 @@ static const char* GetClipboardTextFn_DefaultImpl(void*) ItemCount item_count = 0; PasteboardGetItemCount(main_clipboard, &item_count); - for (int i = 0; i < item_count; i++) { PasteboardItemID item_id = 0; @@ -9616,30 +9617,27 @@ static const char* GetClipboardTextFn_DefaultImpl(void*) if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr) { static ImVector clipboard_text; - - int length = (int) CFDataGetLength(cf_data); + int length = (int)CFDataGetLength(cf_data); clipboard_text.resize(length + 1); - CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*) clipboard_text.Data); + CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data); clipboard_text[length] = 0; - CFRelease(cf_data); return clipboard_text.Data; } } } - return ""; + return NULL; } #else -// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers. static const char* GetClipboardTextFn_DefaultImpl(void*) { ImGuiContext& g = *GImGui; return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin(); } -// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { ImGuiContext& g = *GImGui; @@ -9653,7 +9651,7 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) #endif // Win32 API IME support (for Asian languages, etc.) -#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) +#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) #include #ifdef _MSC_VER From 7e772f6a51d0db5d00d9e9b4649cbe4cb0da79b9 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 18 May 2019 18:42:59 +0200 Subject: [PATCH 358/566] Docking: Fixed undocking whole node (from collapse/docking menu button) from losing its size/pos. Made collapose/docking menu id easier to compute for testing. --- imgui.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 26b39a98..e64b6d33 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11609,6 +11609,7 @@ void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) DockSettingsRenameNodeReferences(node->ID, new_node->ID); for (int n = 0; n < new_node->Windows.Size; n++) UpdateWindowParentAndRootLinks(new_node->Windows[n], new_node->Windows[n]->Flags, NULL); + new_node->AuthorityForPos = new_node->AuthorityForSize = ImGuiDataAuthority_Window; new_node->WantMouseMove = true; } else @@ -12348,7 +12349,10 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w host_window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); } - PushID(node->ID); + // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. + // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, + // as docked windows themselves will override the stack with their own root ID. + PushOverrideID(node->ID); ImGuiTabBar* tab_bar = node->TabBar; bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden if (tab_bar == NULL) @@ -12361,6 +12365,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w node->IsFocused = is_focused; // Collapse button changes shape and display a list + // FIXME-DOCK: Could we recycle popups id? if (IsPopupOpen("#TabListMenu")) { if (ImGuiID tab_id = DockNodeUpdateTabListMenu(node, tab_bar)) From 1575a3fbcdcea3ea85639cf098c7909f33270cae Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 19 May 2019 17:00:17 +0200 Subject: [PATCH 359/566] Docking: Fixed temporarily losing Dockspace flag when merging remaining sibling back into a parent node. (#2563, #2109) Would trigger an assert in the Passthru hole path. Broken by fd5859ed. --- imgui.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index e64b6d33..2d1e0d2a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12929,7 +12929,9 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG parent_node->SizeRef = backup_last_explicit_size; // Flags transfer - parent_node->LocalFlags = ((child_0 ? child_0->LocalFlags : 0) | (child_1 ? child_1->LocalFlags : 0)) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag + parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; + parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; if (child_0) { From f242cd4d8a516b8993fb55d61445b03cfde7fe78 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 19 May 2019 17:15:14 +0200 Subject: [PATCH 360/566] Fixed GCC mem-access warnings (#2565) + using "if defined" more consistently for Clang. --- imgui.cpp | 2 +- imgui_demo.cpp | 2 +- imgui_draw.cpp | 12 ++++++------ imgui_internal.h | 17 +++++++++++++---- imgui_widgets.cpp | 2 +- 5 files changed, 22 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 66a4008f..5334a35f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -995,7 +995,7 @@ CODE #endif // Clang/GCC warnings with -Weverything -#ifdef __clang__ +#if defined(__clang__) #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7ce699d1..1bc4a244 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -63,7 +63,7 @@ Index of this file: #ifdef _MSC_VER #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif -#ifdef __clang__ +#if defined(__clang__) #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c352db05..bcea633b 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -52,7 +52,7 @@ Index of this file: #endif // Clang/GCC warnings with -Weverything -#ifdef __clang__ +#if defined(__clang__) #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #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. @@ -100,7 +100,7 @@ namespace IMGUI_STB_NAMESPACE #pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration #endif -#ifdef __clang__ +#if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wmissing-prototypes" @@ -108,7 +108,7 @@ namespace IMGUI_STB_NAMESPACE #pragma clang diagnostic ignored "-Wcast-qual" // warning : cast from 'const xxxx *' to 'xxx *' drops const qualifier // #endif -#ifdef __GNUC__ +#if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers @@ -151,15 +151,15 @@ namespace IMGUI_STB_NAMESPACE #endif #endif -#ifdef __GNUC__ +#if defined(__GNUC__) #pragma GCC diagnostic pop #endif -#ifdef __clang__ +#if defined(__clang__) #pragma clang diagnostic pop #endif -#ifdef _MSC_VER +#if defined(_MSC_VER) #pragma warning (pop) #endif diff --git a/imgui_internal.h b/imgui_internal.h index a44e5667..8c4ef1d9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -36,15 +36,17 @@ Index of this file: #include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf #include // INT_MIN, INT_MAX +// Visual Studio warnings #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) #endif -#ifdef __clang__ +// Clang/GCC warnings with -Weverything +#if defined(__clang__) #pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h -#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h #pragma clang diagnostic ignored "-Wold-style-cast" #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" @@ -52,6 +54,11 @@ Index of this file: #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" #endif +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#if __GNUC__ >= 8 +#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif #endif //----------------------------------------------------------------------------- @@ -1645,8 +1652,10 @@ extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGu #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) #endif -#ifdef __clang__ +#if defined(__clang__) #pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop #endif #ifdef _MSC_VER diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d34f519c..8b05f772 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -51,7 +51,7 @@ Index of this file: #endif // Clang/GCC warnings with -Weverything -#ifdef __clang__ +#if defined(__clang__) #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #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. From 392ab0858062040133ba8896e30344bf8182a6bb Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 20 May 2019 16:46:26 +0200 Subject: [PATCH 361/566] BeginPopupContextItem(): Skip processing when SkipItems is set as LastItemId is unreliable and we assert when it is zero. + Minor comments on columns. --- imgui.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5334a35f..46ecb3ca 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7229,6 +7229,8 @@ void ImGui::EndPopup() bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; + if (window->SkipItems) + return false; ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) @@ -8435,7 +8437,8 @@ void ImGui::NextColumn() columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); if (++columns->Current < columns->Count) { - // New column (columns 1+ cancels out IndentX) + // Columns 1+ cancel out IndentX + // FIXME-COLUMNS: Unnecessary, could be locked? window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; window->DrawList->ChannelsSetCurrent(columns->Current + 1); } @@ -8452,7 +8455,7 @@ void ImGui::NextColumn() window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = 0.0f; - PushColumnClipRect(columns->Current); + PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? PushItemWidth(GetColumnWidth() * 0.65f); // FIXME-COLUMNS: Move on columns setup } From 882d2c3aea70065d35c9a3ed9b77a08dbfde3355 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 21 May 2019 12:18:34 +0200 Subject: [PATCH 362/566] Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) + comments --- docs/CHANGELOG.txt | 1 + imgui.cpp | 10 +++++++--- imgui_widgets.cpp | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d784c843..143168a7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,7 @@ Other Changes: It wasn't much of a problem because we typically use the return value instead of IsItemEdited() here. - Fixed uses of IsItemDeactivated(), IsItemDeactivatedAfterEdit() on multi-components widgets and after EndGroup(). (#2550, #1875) +- Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) - Scrollbar: Very minor bounding box adjustment to cope with various border size. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. diff --git a/imgui.cpp b/imgui.cpp index 46ecb3ca..1516d259 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2831,9 +2831,13 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) { // Navigation processing runs prior to clipping early-out // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget - // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window. - // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. - // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick) + // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests + // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of + // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. + // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able + // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). + // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null. + // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere. window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask; if (g.NavId == id || g.NavAnyRequest) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8b05f772..ab1f657f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5850,7 +5850,7 @@ void ImGui::EndMainMenuBar() // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window // FIXME: With this strategy we won't be able to restore a NULL focus. ImGuiContext& g = *GImGui; - if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0) + if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0 && !g.NavAnyRequest) FocusTopMostWindowUnderOne(g.NavWindow, NULL); End(); From 34b881eb12ef8246b011fa9344dc39399859744d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 21 May 2019 12:45:27 +0200 Subject: [PATCH 363/566] ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not fully cleared. Fixed edge case overflow when adding character 0xFFFF. (#2568) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 11 ++++++----- imgui_draw.cpp | 5 +++-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 143168a7..a955d1a8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Other Changes: - Scrollbar: Very minor bounding box adjustment to cope with various border size. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. +- ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not + fully cleared. Fixed edge case overflow when adding character 0xFFFF. (#2568). [@NIKE3500] - Add native Mac clipboard copy/paste default implementation in core library to match what we are dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), diff --git a/imgui.h b/imgui.h index 75a2ae7f..77fc9c8a 100644 --- a/imgui.h +++ b/imgui.h @@ -1997,12 +1997,13 @@ struct ImFontGlyph // This is essentially a tightly packed of vector of 64k booleans = 8KB storage. struct ImFontGlyphRangesBuilder { - ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) + ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) - ImFontGlyphRangesBuilder() { UsedChars.resize(0x10000 / sizeof(int)); memset(UsedChars.Data, 0, 0x10000 / sizeof(int)); } - bool GetBit(int n) const { int off = (n >> 5); int mask = 1 << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array - void SetBit(int n) { int off = (n >> 5); int mask = 1 << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array - void AddChar(ImWchar c) { SetBit(c); } // Add character + ImFontGlyphRangesBuilder() { Clear(); } + inline void Clear() { int size_in_bytes = 0x10000 / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } + inline bool GetBit(int n) const { int off = (n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array + inline void SetBit(int n) { int off = (n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array + inline void AddChar(ImWchar c) { SetBit(c); } // Add character IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bcea633b..dcbaae06 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2391,11 +2391,12 @@ void ImFontGlyphRangesBuilder::AddRanges(const ImWchar* ranges) void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) { - for (int n = 0; n < 0x10000; n++) + int max_codepoint = 0x10000; + for (int n = 0; n < max_codepoint; n++) if (GetBit(n)) { out_ranges->push_back((ImWchar)n); - while (n < 0x10000 && GetBit(n + 1)) + while (n < max_codepoint - 1 && GetBit(n + 1)) n++; out_ranges->push_back((ImWchar)n); } From a2eec8f5b54b50c0ed76aa9115ac41bca23a5270 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 May 2019 21:43:42 +0200 Subject: [PATCH 364/566] Fix OuterRectClipped not being clipped correctly, which resulted in child window outside visible bound to not be marked with SkipItems. Broken in b50c61c961498e15b5a4c22c7e7e10df13a64e77. + Comments on InnerClipRect being misleading. Demo: Tweak to sizing of child window in the Layout->Scrolling section. --- imgui.cpp | 19 +++++++++++-------- imgui_demo.cpp | 10 +++++++--- imgui_internal.h | 5 +++-- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1516d259..7baf6d8a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5463,10 +5463,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); - // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() - window->OuterRectClipped = window->Rect(); - window->OuterRectClipped.ClipWith(window->ClipRect); - // Inner rectangle // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. @@ -5476,13 +5472,23 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); + // Outer host rectangle for drawing background and borders + ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; + + // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() + window->OuterRectClipped = window->Rect(); + window->OuterRectClipped.ClipWith(host_rect); + // Inner clipping rectangle will extend a little bit outside the work region. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + // FIXME: This is currently not clipped by the host rectangle, which is misleading because our call to PushClipRect() below will do it anyway. + // If we fix the value in InnerClipRect, which is desirable, we need to fix the two lines of code relying on it. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); + //window->InnerClipRect.ClipWithFull(host_rect); // DRAWING @@ -5490,10 +5496,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DrawList->Clear(); window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); - if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) - PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); - else - PushClipRect(viewport_rect.Min, viewport_rect.Max, true); + PushClipRect(host_rect.Min, host_rect.Max, false); // Draw modal window background (darkens what is behind them, all viewports) const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1bc4a244..af0700c4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2056,14 +2056,17 @@ static void ShowDemoWindowLayout() bool scroll_to = ImGui::Button("Scroll To Pos"); ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "Y = %d px"); ImGui::PopItemWidth(); - if (scroll_to) track = false; + if (scroll_to) + track = false; + ImGuiStyle& style = ImGui::GetStyle(); + float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; for (int i = 0; i < 5; i++) { if (i > 0) ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); - ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(ImGui::GetWindowWidth() * 0.17f, 200.0f), true); + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true); if (scroll_to) ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f); for (int line = 0; line < 100; line++) @@ -2078,7 +2081,8 @@ static void ShowDemoWindowLayout() ImGui::Text("Line %d", line); } } - float scroll_y = ImGui::GetScrollY(), scroll_max_y = ImGui::GetScrollMaxY(); + float scroll_y = ImGui::GetScrollY(); + float scroll_max_y = ImGui::GetScrollMaxY(); ImGui::EndChild(); ImGui::Text("%.0f/%0.f", scroll_y, scroll_max_y); ImGui::EndGroup(); diff --git a/imgui_internal.h b/imgui_internal.h index 8c4ef1d9..199cda6a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1290,8 +1290,9 @@ struct IMGUI_API ImGuiWindow ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack ImRect ClipRect; // Current clipping rectangle. = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. - ImRect OuterRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window. - ImRect InnerMainRect, InnerClipRect; + ImRect OuterRectClipped; // == WindowRect just after setup in Begin(). == window->Rect() for root window. + ImRect InnerMainRect; // + ImRect InnerClipRect; // == InnerMainRect, minus WindowPadding on each side, clipped within viewport or parent. ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. Maximum visible content position ~~ Pos + (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis int LastFrameActive; // Last frame number the window was Active. float ItemWidthDefault; From b85e97137dfaa07ceed2d804adbb6a6c93182784 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 May 2019 23:51:20 +0200 Subject: [PATCH 365/566] Version tag is 1.71 WIP oops --- imgui.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 77fc9c8a..77fab495 100644 --- a/imgui.h +++ b/imgui.h @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.71" -#define IMGUI_VERSION_NUM 17001 +#define IMGUI_VERSION "1.71 WIP" +#define IMGUI_VERSION_NUM 17002 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) From 7bc03f7155c67b5081a8e154b3c642fa5db5b33b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 May 2019 23:54:32 +0200 Subject: [PATCH 366/566] Internals: Added InnerWorkRect equal to old InnerClipRect, added InnerWorkRectClipped actually clipped. --- imgui.cpp | 28 ++++++++++++++-------------- imgui_internal.h | 3 ++- imgui_widgets.cpp | 2 +- 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7baf6d8a..a8153a23 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5479,16 +5479,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->OuterRectClipped = window->Rect(); window->OuterRectClipped.ClipWith(host_rect); - // Inner clipping rectangle will extend a little bit outside the work region. + // Inner work/clipping rectangle will extend a little bit outside the work region. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. - // FIXME: This is currently not clipped by the host rectangle, which is misleading because our call to PushClipRect() below will do it anyway. - // If we fix the value in InnerClipRect, which is desirable, we need to fix the two lines of code relying on it. - window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); - window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); - //window->InnerClipRect.ClipWithFull(host_rect); + window->InnerWorkRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerWorkRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); + window->InnerWorkRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerWorkRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); + window->InnerWorkRectClipped = window->InnerWorkRect; + window->InnerWorkRectClipped.ClipWithFull(host_rect); // DRAWING @@ -5614,7 +5613,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetCurrentWindow(window); } - PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); + PushClipRect(window->InnerWorkRectClipped.Min, window->InnerWorkRectClipped.Max, true); // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) if (first_begin_of_the_frame) @@ -8653,7 +8652,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag window->DC.CurrentColumns = columns; // Set state for first column - const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x); + const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerWorkRect.Max.x - window->Pos.x); columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range columns->OffMaxX = ImMax(content_region_width - window->Scroll.x, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; @@ -9701,10 +9700,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; } - enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerMainRect, RT_InnerClipRect, RT_ContentsRegionRect, RT_ContentsFullRect }; + enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerMainRect, RT_InnerWorkRect, RT_InnerWorkRectClipped, RT_ContentsRegionRect, RT_ContentsFullRect }; static bool show_windows_begin_order = false; static bool show_windows_rects = false; - static int show_windows_rect_type = RT_ContentsRegionRect; + static int show_windows_rect_type = RT_InnerWorkRect; static bool show_drawcmd_clip_rects = true; ImGuiIO& io = ImGui::GetIO(); @@ -9918,7 +9917,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerMainRect\0" "InnerClipRect\0" "ContentsRegionRect\0"); + show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerMainRect\0" "InnerWorkRect\0" "InnerWorkRectClipped\0" "ContentsRegionRect\0"); ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects); ImGui::TreePop(); } @@ -9937,7 +9936,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (show_windows_rect_type == RT_OuterRect) { r = window->Rect(); } else if (show_windows_rect_type == RT_OuterRectClipped) { r = window->OuterRectClipped; } else if (show_windows_rect_type == RT_InnerMainRect) { r = window->InnerMainRect; } - else if (show_windows_rect_type == RT_InnerClipRect) { r = window->InnerClipRect; } + else if (show_windows_rect_type == RT_InnerWorkRect) { r = window->InnerWorkRect; } + else if (show_windows_rect_type == RT_InnerWorkRectClipped) { r = window->InnerWorkRectClipped; } else if (show_windows_rect_type == RT_ContentsRegionRect) { r = window->ContentsRegionRect; } draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } diff --git a/imgui_internal.h b/imgui_internal.h index 199cda6a..b59844c0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1292,7 +1292,8 @@ struct IMGUI_API ImGuiWindow ImRect ClipRect; // Current clipping rectangle. = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. ImRect OuterRectClipped; // == WindowRect just after setup in Begin(). == window->Rect() for root window. ImRect InnerMainRect; // - ImRect InnerClipRect; // == InnerMainRect, minus WindowPadding on each side, clipped within viewport or parent. + ImRect InnerWorkRect; // == InnerMainRect minus WindowPadding.x + ImRect InnerWorkRectClipped; // == InnerMainRect minus WindowPadding.x, clipped within viewport or parent clip rect. ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. Maximum visible content position ~~ Pos + (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis int LastFrameActive; // Last frame number the window was Active. float ItemWidthDefault; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ab1f657f..30f721b6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6227,7 +6227,7 @@ bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) ImGuiID id = window->GetID(str_id); ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); - ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->InnerClipRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); + ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->InnerWorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); tab_bar->ID = id; return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused); } From 3fda90d6a71ffafb816ad9bec472d03376aa350f Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 May 2019 14:31:53 +0200 Subject: [PATCH 367/566] Fixed InputScalar, InputScalarN, SliderScalarN, DragScalarN with non-visible label from inserting style.ItemInnerSpacing.x worth of trailing spacing. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 42 ++++++++++++++++++++++++++++++++++-------- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a955d1a8..457ce9df 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ Other Changes: - Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. +- Fixed InputScalar, InputScalarN, SliderScalarN, DragScalarN with non-visible label from inserting + style.ItemInnerSpacing.x worth of trailing spacing. - Fixed InputFloatX, SliderFloatX, DragFloatX functions erroneously reporting IsItemEdited() multiple times when the text input doesn't match the formatted output value (e.g. input "1" shows "1.000"). It wasn't much of a problem because we typically use the return value instead of IsItemEdited() here. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 30f721b6..d1fe8916 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2068,15 +2068,22 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int for (int i = 0; i < components; i++) { PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= DragScalar("", data_type, v, v_speed, v_min, v_max, format, power); - SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); } PopID(); - TextEx(label, FindRenderedTextEnd(label)); + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + EndGroup(); return value_changed; } @@ -2516,15 +2523,22 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i for (int i = 0; i < components; i++) { PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power); - SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); } PopID(); - TextEx(label, FindRenderedTextEnd(label)); + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + EndGroup(); return value_changed; } @@ -2827,8 +2841,13 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p DataTypeApplyOp(data_type, '+', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step); value_changed = true; } - SameLine(0, style.ItemInnerSpacing.x); - TextEx(label, FindRenderedTextEnd(label)); + + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0, style.ItemInnerSpacing.x); + TextEx(label, label_end); + } style.FramePadding = backup_frame_padding; PopID(); @@ -2860,15 +2879,22 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, in for (int i = 0; i < components; i++) { PushID(i); + if (i > 0) + SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= InputScalar("", data_type, v, step, step_fast, format, flags); - SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); } PopID(); - TextEx(label, FindRenderedTextEnd(label)); + const char* label_end = FindRenderedTextEnd(label); + if (label != label_end) + { + SameLine(0.0f, g.Style.ItemInnerSpacing.x); + TextEx(label, label_end); + } + EndGroup(); return value_changed; } From ec3ec24157a7cafac8ce37ac1df0d185514d9c91 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 May 2019 20:36:30 +0200 Subject: [PATCH 368/566] Internals: Extracted some of the tab bar shrinking code into a ShrinkWidths() function so columns/table can use it. --- imgui_internal.h | 5 ++-- imgui_widgets.cpp | 61 +++++++++++++++++++++++++---------------------- 2 files changed, 36 insertions(+), 30 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b59844c0..8b50003d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -811,7 +811,7 @@ struct ImGuiNextItemData // Tabs //----------------------------------------------------------------------------- -struct ImGuiTabBarSortItem +struct ImGuiShrinkWidthItem { int Index; float Width; @@ -976,7 +976,7 @@ struct ImGuiContext ImPool TabBars; ImGuiTabBar* CurrentTabBar; ImVector CurrentTabBarStack; - ImVector TabSortByWidthBuffer; + ImVector ShrinkWidthBuffer; // Widget state ImVec2 LastValidMousePos; @@ -1495,6 +1495,7 @@ namespace ImGui IMGUI_API void PopItemFlag(); IMGUI_API bool IsItemToggledSelection(); // was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) IMGUI_API ImVec2 GetWorkRectMax(); + IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); // Logging/Capture IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d1fe8916..b84052b2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1149,6 +1149,7 @@ void ImGui::Bullet() // - SeparatorEx() [Internal] // - Separator() // - SplitterBehavior() [Internal] +// - ShrinkWidths() [Internal] //------------------------------------------------------------------------- void ImGui::Spacing() @@ -1330,6 +1331,33 @@ bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float return held; } +static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) +{ + const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs; + const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs; + if (int d = (int)(b->Width - a->Width)) + return d; + return (b->Index - a->Index); +} + +// Shrink excess width from a set of item, by removing width from the larger items first. +void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess) +{ + if (count > 1) + ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); + int count_same_width = 1; + while (width_excess > 0.0f && count_same_width < count) + { + while (count_same_width < count && items[0].Width == items[count_same_width].Width) + count_same_width++; + float width_to_remove_per_item_max = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + float width_to_remove_per_item = ImMin(width_excess / count_same_width, width_to_remove_per_item_max); + for (int item_n = 0; item_n < count_same_width; item_n++) + items[item_n].Width -= width_to_remove_per_item; + width_excess -= width_to_remove_per_item * count_same_width; + } +} + //------------------------------------------------------------------------- // [SECTION] Widgets: ComboBox //------------------------------------------------------------------------- @@ -6221,15 +6249,6 @@ static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const voi return (int)(a->Offset - b->Offset); } -static int IMGUI_CDECL TabBarSortItemComparer(const void* lhs, const void* rhs) -{ - const ImGuiTabBarSortItem* a = (const ImGuiTabBarSortItem*)lhs; - const ImGuiTabBarSortItem* b = (const ImGuiTabBarSortItem*)rhs; - if (int d = (int)(b->Width - a->Width)) - return d; - return (b->Index - a->Index); -} - static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiTabBarRef& ref) { ImGuiContext& g = *GImGui; @@ -6403,10 +6422,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; - ImVector& width_sort_buffer = g.TabSortByWidthBuffer; - width_sort_buffer.resize(tab_bar->Tabs.Size); - // Compute ideal widths + g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); float width_total_contents = 0.0f; ImGuiTabItem* most_recently_selected_tab = NULL; bool found_selected_tab_id = false; @@ -6429,8 +6446,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->WidthContents; // Store data so we can build an array sorted by width if we need to shrink tabs down - width_sort_buffer[tab_n].Index = tab_n; - width_sort_buffer[tab_n].Width = tab->WidthContents; + g.ShrinkWidthBuffer[tab_n].Index = tab_n; + g.ShrinkWidthBuffer[tab_n].Width = tab->WidthContents; } // Compute width @@ -6439,21 +6456,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown)) { // If we don't have enough room, resize down the largest tabs first - if (tab_bar->Tabs.Size > 1) - ImQsort(width_sort_buffer.Data, (size_t)width_sort_buffer.Size, sizeof(ImGuiTabBarSortItem), TabBarSortItemComparer); - int tab_count_same_width = 1; - while (width_excess > 0.0f && tab_count_same_width < tab_bar->Tabs.Size) - { - while (tab_count_same_width < tab_bar->Tabs.Size && width_sort_buffer[0].Width == width_sort_buffer[tab_count_same_width].Width) - tab_count_same_width++; - float width_to_remove_per_tab_max = (tab_count_same_width < tab_bar->Tabs.Size) ? (width_sort_buffer[0].Width - width_sort_buffer[tab_count_same_width].Width) : (width_sort_buffer[0].Width - 1.0f); - float width_to_remove_per_tab = ImMin(width_excess / tab_count_same_width, width_to_remove_per_tab_max); - for (int tab_n = 0; tab_n < tab_count_same_width; tab_n++) - width_sort_buffer[tab_n].Width -= width_to_remove_per_tab; - width_excess -= width_to_remove_per_tab * tab_count_same_width; - } + ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess); for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) - tab_bar->Tabs[width_sort_buffer[tab_n].Index].Width = (float)(int)width_sort_buffer[tab_n].Width; + tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index].Width = (float)(int)g.ShrinkWidthBuffer[tab_n].Width; } else { From 6c3697f6f16870ab73c549b2c424069b523a0d77 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 May 2019 17:47:51 +0200 Subject: [PATCH 369/566] Internal: CloseButton takes an upper-left corner + a size to be consistent with similar widgets. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 4 ++-- imgui_internal.h | 2 +- imgui_widgets.cpp | 27 ++++++++++++++++----------- 4 files changed, 20 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 457ce9df..8106801a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other Changes: after EndGroup(). (#2550, #1875) - Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) - Scrollbar: Very minor bounding box adjustment to cope with various border size. +- Style: Made window close button cross is slightly smaller. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. - ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not diff --git a/imgui.cpp b/imgui.cpp index a8153a23..986412d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5074,8 +5074,8 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl // Close button if (p_open != NULL) { - const float rad = g.FontSize * 0.5f; - if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x - rad, window->Pos.y + style.FramePadding.y + rad), rad + 1)) + const float button_sz = g.FontSize; + if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x * 2.0f - button_sz, window->Pos.y))) *p_open = false; } diff --git a/imgui_internal.h b/imgui_internal.h index 8b50003d..8afa9206 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1582,7 +1582,7 @@ namespace ImGui // Widgets IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); - IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags); IMGUI_API void Scrollbar(ImGuiAxis axis); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b84052b2..892a37e7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -717,14 +717,14 @@ bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) } // Button to close a window -bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window. // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible). - const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); + const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); bool is_clipped = !ItemAdd(bb, id); bool hovered, held; @@ -733,11 +733,12 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) return pressed; // Render + ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); ImVec2 center = bb.GetCenter(); if (hovered) - window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered), 9); + window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col, 12); - float cross_extent = (radius * 0.7071f) - 1.0f; + float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; ImU32 cross_col = GetColorU32(ImGuiCol_Text); center -= ImVec2(0.5f, 0.5f); window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f); @@ -756,9 +757,11 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); + // Render ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImVec2 center = bb.GetCenter(); if (hovered || held) - window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0.0f, -0.5f), g.FontSize * 0.5f + 1.0f, col, 9); + window->DrawList->AddCircleFilled(center/* + ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, col, 12); RenderArrow(bb.Min + g.Style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); // Switch to moving the window after mouse is moved beyond the initial drag threshold @@ -5358,9 +5361,9 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. ImGuiContext& g = *GImGui; ImGuiItemHoveredDataBackup last_item_backup; - float button_radius = g.FontSize * 0.5f; - ImVec2 button_center = ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_radius, window->DC.LastItemRect.GetCenter().y); - if (CloseButton(window->GetID((void*)((intptr_t)id+1)), button_center, button_radius)) + float button_size = g.FontSize; + ImVec2 button_pos = ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x * 2.0f - button_size, window->DC.LastItemRect.Min.y); + if (CloseButton(window->GetID((void*)((intptr_t)id + 1)), button_pos)) *p_open = false; last_item_backup.Restore(); } @@ -7038,16 +7041,18 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, if (close_button_visible) { ImGuiItemHoveredDataBackup last_item_backup; - const float close_button_sz = g.FontSize * 0.5f; - if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x - close_button_sz, bb.Min.y + frame_padding.y + close_button_sz), close_button_sz)) + const float close_button_sz = g.FontSize; + PushStyleVar(ImGuiStyleVar_FramePadding, frame_padding); + if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x * 2.0f - close_button_sz, bb.Min.y))) close_button_pressed = true; + PopStyleVar(); last_item_backup.Restore(); // Close with middle mouse button if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2)) close_button_pressed = true; - text_pixel_clip_bb.Max.x -= close_button_sz * 2.0f; + text_pixel_clip_bb.Max.x -= close_button_sz; } // Label with ellipsis From 958d75c00ac83a98b6423e523d9b222bc94a0224 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 May 2019 20:59:41 +0200 Subject: [PATCH 370/566] Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 80 +++++++++++++++++++++++++++++++++------------- imgui.h | 1 + imgui_demo.cpp | 1 + imgui_widgets.cpp | 4 ++- 5 files changed, 65 insertions(+), 23 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8106801a..a27ed29d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Other Changes: after EndGroup(). (#2550, #1875) - Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) - Scrollbar: Very minor bounding box adjustment to cope with various border size. +- Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the + collapsing/docking button to the other side of the title bar. - Style: Made window close button cross is slightly smaller. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. diff --git a/imgui.cpp b/imgui.cpp index 986412d2..4ff123e3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1133,6 +1133,7 @@ ImGuiStyle::ImGuiStyle() WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. WindowMinSize = ImVec2(32,32); // Minimum window size WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text + WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows @@ -3453,6 +3454,8 @@ void ImGui::NewFrame() IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!"); IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); + IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); + for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); @@ -5054,30 +5057,54 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar } } +// Render title text, collapse button, close button void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; ImGuiWindowFlags flags = window->Flags; - // Close & collapse button are on layer 1 (same as menus) and don't default focus + const bool has_close_button = (p_open != NULL); + const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse); + + // Close & collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); - // Collapse button - if (!(flags & ImGuiWindowFlags_NoCollapse)) - if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos)) - window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function + // Layout buttons + // FIXME: Would be nice to generalize the subtleties expressed here into reusable code. + float pad_l = style.FramePadding.x; + float pad_r = style.FramePadding.x; + float button_sz = g.FontSize; + ImVec2 close_button_pos; + ImVec2 collapse_button_pos; + if (has_close_button) + { + pad_r += button_sz; + close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y); + } + if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right) + { + pad_r += button_sz; + collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y); + } + if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left) + { + collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y); + pad_l += button_sz; + } + + // Collapse button (submitting first so it gets priority when choosing a navigation init fallback) + if (has_collapse_button) + if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos)) + window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function // Close button - if (p_open != NULL) - { - const float button_sz = g.FontSize; - if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x * 2.0f - button_sz, window->Pos.y))) + if (has_close_button) + if (CloseButton(window->GetID("#CLOSE"), close_button_pos)) *p_open = false; - } window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); @@ -5088,21 +5115,30 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl const char* UNSAVED_DOCUMENT_MARKER = "*"; const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f; const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); - ImRect text_r = title_bar_rect; - float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); - float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); - if (style.WindowTitleAlign.x > 0.0f) - pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); - text_r.Min.x += pad_left; - text_r.Max.x -= pad_right; - ImRect clip_rect = text_r; - clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton() - RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); + + // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, + // while uncentered title text will still reach edges correct. + if (pad_l > style.FramePadding.x) + pad_l += g.Style.ItemInnerSpacing.x; + if (pad_r > style.FramePadding.x) + pad_r += g.Style.ItemInnerSpacing.x; + if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f) + { + float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center + float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x); + pad_l = ImMax(pad_l, pad_extend * centerness); + pad_r = ImMax(pad_r, pad_extend * centerness); + } + + ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y); + ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y); + //if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] + RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r); if (flags & ImGuiWindowFlags_UnsavedDocument) { - ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f); + ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f); ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f)); - RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect); + RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r); } } diff --git a/imgui.h b/imgui.h index 77fab495..188372f9 100644 --- a/imgui.h +++ b/imgui.h @@ -1283,6 +1283,7 @@ struct ImGuiStyle float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints(). ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left. float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index af0700c4..9b56e429 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2999,6 +2999,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); ImGui::Text("Alignment"); ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + ImGui::Combo("WindowMenuButtonPosition", (int*)&style.WindowMenuButtonPosition, "Left\0Right\0"); ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); ImGui::Text("Safe Area Padding"); ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 892a37e7..cbf7ff72 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5358,7 +5358,9 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label); if (p_open) { - // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + // Create a small overlapping close button + // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. ImGuiContext& g = *GImGui; ImGuiItemHoveredDataBackup last_item_backup; float button_size = g.FontSize; From e5dfa0855f8de98664dfc9502068a3e42da67bb6 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 May 2019 21:59:00 +0200 Subject: [PATCH 371/566] Docking: Honor style.WindowMenuButtonPosition setting in docking node. --- imgui.cpp | 46 +++++++++++++++++++++++++++++++++------------- imgui_widgets.cpp | 2 +- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1333bc29..cde3c4ab 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11125,7 +11125,7 @@ namespace ImGui static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window); static void DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking); static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data); - static ImRect DockNodeCalcTabBarRect(const ImGuiDockNode* node); + static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_collapse_button_pos); static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired); static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos); static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; } @@ -12322,8 +12322,12 @@ static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* r static ImGuiID ImGui::DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar) { // Try to position the menu so it is more likely to stays within the same viewport + ImGuiContext& g = *GImGui; ImGuiID ret_tab_id = 0; - SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight())); + if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left) + SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f)); + else + SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f)); if (BeginPopup("#TabListMenu")) { node->IsFocused = true; @@ -12419,15 +12423,19 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w is_focused |= node->IsFocused; } + // Layout + ImRect title_bar_rect, tab_bar_rect; + ImVec2 collapse_button_pos; + DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &collapse_button_pos); + // Title bar if (is_focused) node->LastFrameFocused = g.FrameCount; - ImRect title_bar_rect = ImRect(node->Pos, node->Pos + ImVec2(node->Size.x, g.FontSize + style.FramePadding.y * 2.0f)); ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, ImDrawCornerFlags_Top); // Collapse button - if (CollapseButton(host_window->GetID("#COLLAPSE"), title_bar_rect.Min, node)) + if (CollapseButton(host_window->GetID("#COLLAPSE"), collapse_button_pos, node)) OpenPopup("#TabListMenu"); if (IsItemActive()) focus_tab_id = tab_bar->SelectedTabId; @@ -12461,7 +12469,6 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->ID; // Begin tab bar - const ImRect tab_bar_rect = DockNodeCalcTabBarRect(node); ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons); tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode; if (!host_window->Collapsed && is_focused) @@ -12621,15 +12628,27 @@ static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* return false; } -static ImRect ImGui::DockNodeCalcTabBarRect(const ImGuiDockNode* node) +// FIXME: This is similar to RenderWindowTitleBarContents, may want to share code. +static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_collapse_button_pos) { ImGuiContext& g = *GImGui; - ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + (g.FontSize + g.Style.FramePadding.y * 2.0f)); - if (node->HasCollapseButton) - r.Min.x += g.Style.FramePadding.x + g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a tab bar. Instead we adjusted RenderArrowDockMenu() - // In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none. - r.Max.x -= g.Style.FramePadding.x + g.FontSize + 1.0f; - return r; + ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f); + if (out_title_rect) { *out_title_rect = r; } + + ImVec2 collapse_button_pos = r.Min; + r.Max.x -= g.Style.FramePadding.x + g.FontSize;// +1.0f; // In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none. + if (node->HasCollapseButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Left) + { + r.Min.x += g.Style.FramePadding.x + g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a docking tab bar. Instead we adjusted RenderArrowDockMenu() + } + else if (node->HasCollapseButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Right) + { + r.Min.x += g.Style.FramePadding.x; + r.Max.x -= g.FontSize + g.Style.FramePadding.x; + collapse_button_pos = ImVec2(r.Max.x, r.Min.y); + } + if (out_tab_bar_rect) { *out_tab_bar_rect = r; } + if (out_collapse_button_pos) { *out_collapse_button_pos = collapse_button_pos; } } void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired) @@ -12832,7 +12851,8 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable) { // Compute target tab bar geometry so we can locate our preview tabs - ImRect tab_bar_rect = DockNodeCalcTabBarRect(&data->FutureNode); + ImRect tab_bar_rect; + DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL); ImVec2 tab_pos = tab_bar_rect.Min; if (host_node && host_node->TabBar) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5e2acb13..22af6491 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -793,7 +793,7 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_no } else { - ImVec2 backup_active_click_offset = g.ActiveIdClickOffset; + ImVec2 backup_active_click_offset = g.ActiveIdClickOffset + (pos - window->Pos); StartMouseMovingWindow(window); g.ActiveIdClickOffset = backup_active_click_offset; } From affa7e24224b9078826b56c92347af83dcb9241e Mon Sep 17 00:00:00 2001 From: Mario Botsch <31275467+mbotsch@users.noreply.github.com> Date: Mon, 27 May 2019 10:47:18 +0200 Subject: [PATCH 372/566] Examples: imgui_impl_opengl3: Fix empty printout on shader load. (#2584) Fixed minor bug in CheckShader and CheckProgram The log_length reported by glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length) will at least return 1, since the string delimiter is also counted. The old version would always print and empty string to stderr. This is annoying in the emscripten port, since it prints a red error message to the Javascript console. The new version fixes this behavior. --- examples/imgui_impl_opengl3.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 364b9ccf..d992f001 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -384,7 +384,7 @@ static bool CheckShader(GLuint handle, const char* desc) glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length); if ((GLboolean)status == GL_FALSE) fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s!\n", desc); - if (log_length > 0) + if (log_length > 1) { ImVector buf; buf.resize((int)(log_length + 1)); @@ -402,7 +402,7 @@ static bool CheckProgram(GLuint handle, const char* desc) glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length); if ((GLboolean)status == GL_FALSE) fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! (with GLSL '%s')\n", desc, g_GlslVersionString); - if (log_length > 0) + if (log_length > 1) { ImVector buf; buf.resize((int)(log_length + 1)); From 511e32e8ca7dcae9fbca4bf3a899597a13bfbf59 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 May 2019 12:12:11 +0200 Subject: [PATCH 373/566] Docking: Clarified terminology of docking/tablist/collapse button into Window Menu button matching master. Added private ImGuiDockNodeFlags_NoWindowMenuButton, ImGuiDockNodeFlags_NoCloseButton flags. (#2583, #2109) --- imgui.cpp | 86 ++++++++++++++++++++++++++++-------------------- imgui.h | 3 +- imgui_internal.h | 7 ++-- 3 files changed, 58 insertions(+), 38 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cde3c4ab..62bf4d94 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5438,6 +5438,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar } // Render title text, collapse button, close button +// When inside a dock node, this is handled in DockNodeUpdateTabBar() instead. void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) { ImGuiContext& g = *GImGui; @@ -5447,7 +5448,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl const bool has_close_button = (p_open != NULL); const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse); - // Close & collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) + // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; @@ -11119,13 +11120,13 @@ namespace ImGui static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window); static void DockNodeAddTabBar(ImGuiDockNode* node); static void DockNodeRemoveTabBar(ImGuiDockNode* node); - static ImGuiID DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar); + static ImGuiID DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar); static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node); static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window); static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window); static void DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking); static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data); - static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_collapse_button_pos); + static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos); static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired); static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos); static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; } @@ -11713,7 +11714,7 @@ ImGuiDockNode::ImGuiDockNode(ImGuiID id) AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode; AuthorityForViewport = ImGuiDataAuthority_Auto; IsVisible = true; - IsFocused = HasCloseButton = HasCollapseButton = false; + IsFocused = HasCloseButton = HasWindowMenuButton = EnableCloseButton = false; WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; } @@ -12112,7 +12113,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) DockNodeHideHostWindow(node); node->WantCloseAll = false; node->WantCloseTabID = 0; - node->HasCloseButton = node->HasCollapseButton = false; + node->HasCloseButton = node->HasWindowMenuButton = node->EnableCloseButton = false; node->LastFrameActive = g.FrameCount; if (node->WantMouseMove && node->Windows.Size == 1) @@ -12120,27 +12121,31 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) return; } + const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); + ImGuiWindow* host_window = NULL; bool beginned_into_host_window = false; if (node->IsDockSpace()) { // [Explicit root dockspace node] IM_ASSERT(node->HostWindow); - node->HasCloseButton = false; - node->HasCollapseButton = true; + node->EnableCloseButton = false; + node->HasCloseButton = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0; + node->HasWindowMenuButton = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; host_window = node->HostWindow; } else { // [Automatic root or child nodes] - node->HasCloseButton = false; - node->HasCollapseButton = (node->Windows.Size > 0); + node->EnableCloseButton = false; + node->HasCloseButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; + node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; for (int window_n = 0; window_n < node->Windows.Size; window_n++) { // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. ImGuiWindow* window = node->Windows[window_n]; window->DockIsActive = (node->Windows.Size > 1); - node->HasCloseButton |= window->HasCloseButton; + node->EnableCloseButton |= window->HasCloseButton; } if (node->IsRootNode() && node->IsVisible) @@ -12217,7 +12222,6 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size after // processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! - const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; if (render_dockspace_bg) { @@ -12319,7 +12323,7 @@ static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* r return (a->BeginOrderWithinContext - b->BeginOrderWithinContext); } -static ImGuiID ImGui::DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar) +static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar) { // Try to position the menu so it is more likely to stays within the same viewport ImGuiContext& g = *GImGui; @@ -12328,7 +12332,7 @@ static ImGuiID ImGui::DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f)); else SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f)); - if (BeginPopup("#TabListMenu")) + if (BeginPopup("#WindowMenu")) { node->IsFocused = true; if (tab_bar->Tabs.Size == 1) @@ -12414,19 +12418,23 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w ImGuiID focus_tab_id = 0; node->IsFocused = is_focused; - // Collapse button changes shape and display a list - // FIXME-DOCK: Could we recycle popups id? - if (IsPopupOpen("#TabListMenu")) + const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); + const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; + const bool has_close_button = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0; + + // In a dock node, the Collapse Button turns into the Window Menu button. + // FIXME-DOCK FIXME-OPT: Could we recycle popups id accross multiple dock nodes? + if (has_window_menu_button && IsPopupOpen("#WindowMenu")) { - if (ImGuiID tab_id = DockNodeUpdateTabListMenu(node, tab_bar)) + if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar)) focus_tab_id = tab_bar->NextSelectedTabId = tab_id; is_focused |= node->IsFocused; } // Layout ImRect title_bar_rect, tab_bar_rect; - ImVec2 collapse_button_pos; - DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &collapse_button_pos); + ImVec2 window_menu_button_pos; + DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos); // Title bar if (is_focused) @@ -12434,11 +12442,14 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, ImDrawCornerFlags_Top); - // Collapse button - if (CollapseButton(host_window->GetID("#COLLAPSE"), collapse_button_pos, node)) - OpenPopup("#TabListMenu"); - if (IsItemActive()) - focus_tab_id = tab_bar->SelectedTabId; + // Docking/Collapse button + if (has_window_menu_button) + { + if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) + OpenPopup("#WindowMenu"); + if (IsItemActive()) + focus_tab_id = tab_bar->SelectedTabId; + } // Submit new tabs and apply NavWindow focus back to the tab bar. They will be added as Unsorted and sorted below based on relative DockOrder value. const int tabs_count_old = tab_bar->Tabs.Size; @@ -12515,7 +12526,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w // Close button (after VisibleWindow was updated) // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->ID may be != from tab_bar->SelectedTabId - if (node->VisibleWindow) + if (has_close_button && node->VisibleWindow) { if (!node->VisibleWindow->HasCloseButton) { @@ -12628,27 +12639,32 @@ static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* return false; } +// window menu button == collapse button when not in a dock node. // FIXME: This is similar to RenderWindowTitleBarContents, may want to share code. -static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_collapse_button_pos) +static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos) { ImGuiContext& g = *GImGui; ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f); if (out_title_rect) { *out_title_rect = r; } - ImVec2 collapse_button_pos = r.Min; - r.Max.x -= g.Style.FramePadding.x + g.FontSize;// +1.0f; // In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none. - if (node->HasCollapseButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Left) + ImVec2 window_menu_button_pos = r.Min; + r.Min.x += g.Style.FramePadding.x; + r.Max.x -= g.Style.FramePadding.x; + if (node->HasCloseButton) + { + r.Max.x -= g.FontSize;// +1.0f; // In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none. + } + if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Left) { - r.Min.x += g.Style.FramePadding.x + g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a docking tab bar. Instead we adjusted RenderArrowDockMenu() + r.Min.x += g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a docking tab bar. Instead we adjusted RenderArrowDockMenu() } - else if (node->HasCollapseButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Right) + else if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Right) { - r.Min.x += g.Style.FramePadding.x; r.Max.x -= g.FontSize + g.Style.FramePadding.x; - collapse_button_pos = ImVec2(r.Max.x, r.Min.y); + window_menu_button_pos = ImVec2(r.Max.x, r.Min.y); } if (out_tab_bar_rect) { *out_tab_bar_rect = r; } - if (out_collapse_button_pos) { *out_collapse_button_pos = collapse_button_pos; } + if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; } } void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired) @@ -12751,7 +12767,7 @@ static void ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNo // Build a tentative future node (reuse same structure because it is practical) data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton); - data->FutureNode.HasCollapseButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0); + data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0); data->FutureNode.Pos = host_node ? ref_node_for_rect->Pos : host_window->Pos; data->FutureNode.Size = host_node ? ref_node_for_rect->Size : host_window->Size; diff --git a/imgui.h b/imgui.h index 506b8977..ecd425a2 100644 --- a/imgui.h +++ b/imgui.h @@ -745,7 +745,7 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programmatically) ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. - ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it. Also referred to as "window menu button" within a docking node. ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file @@ -886,6 +886,7 @@ enum ImGuiTabItemFlags_ // Flags for ImGui::DockSpace(), shared/inherited by child nodes. // (Some flags can be applied to individual nodes directly) +// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. enum ImGuiDockNodeFlags_ { ImGuiDockNodeFlags_None = 0, diff --git a/imgui_internal.h b/imgui_internal.h index 783b3b0f..68dc280e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -891,8 +891,10 @@ enum ImGuiDockNodeFlagsPrivate_ ImGuiDockNodeFlags_CentralNode = 1 << 11, // Local ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Local // Tab bar is completely unavailable. No triangle in the corner to enable it back. ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Local // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) + ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Local // Disable window/docking menu (that one that appears instead of the collapse button) + ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Local ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, - ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar, + ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace // When splitting those flags are moved to the inheriting child, never duplicated }; @@ -936,7 +938,8 @@ struct ImGuiDockNode bool IsVisible :1; // Set to false when the node is hidden (usually disabled as it has no active window) bool IsFocused :1; bool HasCloseButton :1; - bool HasCollapseButton :1; + bool HasWindowMenuButton :1; + bool EnableCloseButton :1; bool WantCloseAll :1; // Set when closing all tabs at once. bool WantLockSizeOnce :1; bool WantMouseMove :1; // After a node extraction we need to transition toward moving the newly created host window From 70a4be07df0c9802a5d987c802adabb35b175306 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 May 2019 14:57:39 +0200 Subject: [PATCH 374/566] ColorEdit: Fixed the color picker popup only displaying inputs as HSV instead of showing multiple options. (#2587, broken in 1.69 by #2384). --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a27ed29d..1ac44f40 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: - Fixed uses of IsItemDeactivated(), IsItemDeactivatedAfterEdit() on multi-components widgets and after EndGroup(). (#2550, #1875) - Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) +- ColorEdit: Fixed the color picker popup only displaying inputs as HSV instead of showing multiple + options. (#2587, broken in 1.69 by #2384). - Scrollbar: Very minor bounding box adjustment to cope with various border size. - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9b56e429..11422252 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1235,8 +1235,8 @@ static void ShowDemoWindowWidgets() ImGui::Text("HSV encoded colors"); ImGui::SameLine(); HelpMarker("By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); ImGui::Text("Color widget with InputHSV:"); - ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); - ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); ImGui::DragFloat4("Raw HSV values", (float*)&color_stored_as_hsv, 0.01f, 0.0f, 1.0f); ImGui::TreePop(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cbf7ff72..e5dc8c2b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4258,7 +4258,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag Spacing(); } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; - ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); EndPopup(); From 9c35344175fd2d319771df66e07825ba3c5ca3fc Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 May 2019 15:18:34 +0200 Subject: [PATCH 375/566] Comments, todo entries, moved ImGuiSelectableFlagsPrivate in higher ranges to match others. --- docs/TODO.txt | 19 +++++++++++++------ imgui.h | 4 ++-- imgui_internal.h | 13 ++++++++----- 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 97594ba4..f32c944d 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -25,6 +25,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window: using SetWindowPos() inside Begin() and moving the window with the mouse reacts a very ugly glitch. We should just defer the SetWindowPos() call. - window: GetWindowSize() returns (0,0) when not calculated? (#1045) - window: investigate better auto-positioning for new windows. + - window: top most window flag? (#2574) - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - window/child: the first draw command of a child window could be moved into the current draw command of the parent window (unless child+tooltip?). - window/child: border could be emitted in parent as well. @@ -66,7 +67,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: a way to represent "mixed" values, so e.g. all values replaced with **, including check-boxes, colors, etc. with support for multi-components widgets (e.g. SliderFloat3, make only "Y" mixed) - widgets: selectable: generic BeginSelectable()/EndSelectable() mechanism. - widgets: selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - - widgets: checkbox with custom glyph inside frame. + - widgets: checkbox: checkbox with custom glyph inside frame. + - widgets: coloredit: keep reporting as active when picker is on? - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) @@ -81,7 +83,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input text: display bug when clicking a drag/slider after an input text in a different window has all-selected text (order dependent). actually a very old bug but no one appears to have noticed it. - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. - input text: decorrelate layout from inputs - e.g. what's the easiest way to implement a nice IP/Mac address input editor? - - input text: global callback system so user can plug in an expression evaluator easily. + - input text: global callback system so user can plug in an expression evaluator easily. (#1691) - input text: force scroll to end or scroll to a given line/contents (so user can implement a log or a search feature) - input text: a side bar that could e.g. preview where errors are. probably left to the user to draw but we'd need to give them the info there. - input text: a way for the user to provide syntax coloring. @@ -103,9 +105,12 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - layout: horizontal flow until no space left (#404) - layout: more generic alignment state (left/right/centered) for single items? - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. - - layout: BeginGroup() needs a border option. (~#1496) - layout: vertical alignment of mixed height items (e.g. buttons) within a same line (#1284) + - group: BeginGroup() needs a border option. (~#1496) + - group: IsHovered() after EndGroup() covers whole aabb rather than the intersection of individual items. Is that desirable? + - group: merge deactivation/activation within same group (fwd WasEdited flag). (#2550) + - columns: sizing policy (e.g. for each column: fixed size, %, fill, distribute default size among fills) (#513, #125) - columns: add a conditional parameter to SetColumnOffset() (#513, #125) - columns: headers. re-orderable. (#513, #125) @@ -132,6 +137,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - clipper: ability to force display 1 item in the list would be convenient (for patterns where we need to set active id etc.) - clipper: ability to disable the clipping through a simple flag/bool. - clipper: ability to run without knowing full count in advance. + - clipper: horizontal clipping support. (#2580) - separator: expose flags (#759) - separator: width, thickness, centering (#1643) @@ -264,6 +270,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font: a CalcTextHeight() helper could run faster than CalcTextSize().y - font: enforce monospace through ImFontConfig (for icons?) + create dual ImFont output from same input, reusing rasterized data but with different glyphs/AdvanceX - font: finish CustomRectRegister() to allow mapping Unicode codepoint to custom texture data + - font: make it easier to submit own bitmap font (same texture, another texture?). (#2127, #2575) - font: PushFontSize API (#1018) - font: MemoryTTF taking ownership confusing/not obvious, maybe default should be opposite? - font: storing MinAdvanceX per font would allow us to skip calculating line width (under a threshold of character count) in loops looking for block width @@ -272,7 +279,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font/atlas: add a missing Glyphs.reserve() - font/atlas: incremental updates - font/atlas: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. - - font/atlas: allow user to submit its own primitive to be rectpacked, and allow to map them on a Unicode point. - font/draw: vertical and/or rotated text renderer (#705) - vertical is easier clipping wise - font/draw: need to be able to specify wrap start position. - font/draw: better reserve policy for large horizontal block of text (shouldn't reserve for all clipped lines) @@ -280,8 +286,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font: optimization: for monospace font (like the default one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance (need to make sure TAB is still correct), would save on cache line. - font: add support for kerning, probably optional. A) perhaps default to (32..128)^2 matrix ~ 9K entries = 36KB, then hash for non-ascii?. B) or sparse lookup into per-char list? - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) - - font: fix AddRemapChar() to work before font has been built. - - font: what would it take to support codepoint higher than 0xFFFF? (smileys, etc.) + - font: fix AddRemapChar() to work before atlas has been built. + - font: what would it take to support codepoint higher than 0xFFFF? (smileys, etc.) (#2538, #2541) - font: (api breaking) remove "TTF" from symbol names. also because it now supports OTF. - font/opt: Considering storing standalone AdvanceX table as 16-bit fixed point integer? - font/opt: Glyph currently 40 bytes (2+9*4). Consider storing UV as 16 bits integer? (->32 bytes). X0/Y0/X1/Y1 as 16 fixed-point integers? Or X0/Y0 as float and X1/Y1 as fixed8_8? @@ -320,6 +326,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - inputs/io: backspace and arrows in the context of a text input could use system repeat rate. - inputs/io: clarify/standardize/expose repeat rate and repeat delays (#1808) - inputs: add mouse cursor for unavailable/no? IDC_NO/SDL_SYSTEM_CURSOR_NO. + - inputs/scrolling: support for smooth scrolling (#2462, #2569) - misc: idle: expose "woken up" boolean (set by inputs) and/or animation time (for cursor blink) for back-end to be able stop refreshing easily. - misc: idle: if cursor blink if the _only_ visible animation, core imgui could rewrite vertex alpha to avoid CPU pass on ImGui:: calls. diff --git a/imgui.h b/imgui.h index 188372f9..e0dcaecb 100644 --- a/imgui.h +++ b/imgui.h @@ -823,9 +823,9 @@ enum ImGuiTabBarFlags_ ImGuiTabBarFlags_None = 0, ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear - ImGuiTabBarFlags_TabListPopupButton = 1 << 2, + ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. - ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, + ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit ImGuiTabBarFlags_FittingPolicyScroll = 1 << 7, // Add scroll buttons when tabs don't fit diff --git a/imgui_internal.h b/imgui_internal.h index 8afa9206..b1fa060a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -350,14 +350,15 @@ enum ImGuiColumnsFlags_ ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. }; +// Extend ImGuiSelectableFlags_ enum ImGuiSelectableFlagsPrivate_ { // NB: need to be in sync with last value of ImGuiSelectableFlags_ - ImGuiSelectableFlags_NoHoldingActiveID = 1 << 10, - ImGuiSelectableFlags_PressedOnClick = 1 << 11, - ImGuiSelectableFlags_PressedOnRelease = 1 << 12, - ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 13, // FIXME: We may be able to remove this (added in 6251d379 for menus) - ImGuiSelectableFlags_AllowItemOverlap = 1 << 14 + ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, + ImGuiSelectableFlags_PressedOnClick = 1 << 21, + ImGuiSelectableFlags_PressedOnRelease = 1 << 22, + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 23, // FIXME: We may be able to remove this (added in 6251d379 for menus) + ImGuiSelectableFlags_AllowItemOverlap = 1 << 24 }; enum ImGuiSeparatorFlags_ @@ -1350,6 +1351,7 @@ struct ImGuiItemHoveredDataBackup // Tab bar, tab item //----------------------------------------------------------------------------- +// Extend ImGuiTabBarFlags_ enum ImGuiTabBarFlagsPrivate_ { ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] @@ -1357,6 +1359,7 @@ enum ImGuiTabBarFlagsPrivate_ ImGuiTabBarFlags_SaveSettings = 1 << 22 // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs }; +// Extend ImGuiTabItemFlags_ enum ImGuiTabItemFlagsPrivate_ { ImGuiTabItemFlags_NoCloseButton = 1 << 20 // Store whether p_open is set or not, which we need to recompute WidthContents during layout. From 7c06d9f04319c3e4e8831263aafbbfcc82d5c525 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 May 2019 17:04:33 +0200 Subject: [PATCH 376/566] Docking: Saving the NoTabBar, NoWindowMenuButton, NoCloseButton fields of dock node into the .ini file. Added them to the Metrics window. (#2583, #2423, #2109). --- imgui.cpp | 67 +++++++++++++++++++++++++----------------------- imgui_internal.h | 16 +++++++----- 2 files changed, 44 insertions(+), 39 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 62bf4d94..befe4e5c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11065,18 +11065,16 @@ struct ImGuiDockPreviewData // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes) struct ImGuiDockNodeSettings { - ImGuiID ID; - ImGuiID ParentID; - ImGuiID SelectedTabID; - signed char SplitAxis; - char Depth; - char IsDockSpace; - char IsCentralNode; - char IsHiddenTabBar; - ImVec2ih Pos; - ImVec2ih Size; - ImVec2ih SizeRef; - ImGuiDockNodeSettings() { ID = ParentID = SelectedTabID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; IsDockSpace = IsCentralNode = IsHiddenTabBar = 0; } + ImGuiID ID; + ImGuiID ParentID; + ImGuiID SelectedTabID; + signed char SplitAxis; + char Depth; + ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_) + ImVec2ih Pos; + ImVec2ih Size; + ImVec2ih SizeRef; + ImGuiDockNodeSettings() { ID = ParentID = SelectedTabID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } }; struct ImGuiDockContext @@ -11394,7 +11392,7 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) ImGuiDockContextPruneNodeData* data_root = (data->RootID == settings->ID) ? data : pool.GetByKey(data->RootID); bool remove = false; - remove |= (data->CountWindows == 1 && settings->ParentID == 0 && data->CountChildNodes == 0 && !settings->IsCentralNode); // Floating root node with only 1 window + remove |= (data->CountWindows == 1 && settings->ParentID == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window remove |= (data->CountWindows == 0 && settings->ParentID == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window remove |= (data_root->CountChildWindows == 0); if (remove) @@ -11425,12 +11423,7 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc node->ParentNode->ChildNodes[1] = node; node->SelectedTabID = settings->SelectedTabID; node->SplitAxis = settings->SplitAxis; - if (settings->IsDockSpace) - node->LocalFlags |= ImGuiDockNodeFlags_DockSpace; - if (settings->IsCentralNode) - node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; - if (settings->IsHiddenTabBar) - node->LocalFlags |= ImGuiDockNodeFlags_HiddenTabBar; + node->LocalFlags |= (settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_); // Bind host window immediately if it already exist (in case of a rebuild) // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set. @@ -14076,10 +14069,11 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings // Parsing, e.g. // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " // " DockNode ID=0x00000002 Parent=0x00000001 " + // Important: this code expect currently fields in a fixed order. ImGuiDockNodeSettings node; line = ImStrSkipBlank(line); if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); } - else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.IsDockSpace = true; } + else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; } else return; if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return; if (sscanf(line, " Parent=0x%08X%n", &node.ParentID, &r) == 1) { line += r; if (node.ParentID == 0) return; } @@ -14093,8 +14087,11 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); } } if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; } - if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; node.IsCentralNode = (x != 0); } - if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; node.IsHiddenTabBar = (x != 0); } + if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; } + if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; } + if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; } + if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; } + if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; } if (sscanf(line, " SelectedTab=0x%08X%n", &node.SelectedTabID,&r) == 1) { line += r; } ImGuiDockContext* dc = ctx->DockContext; if (node.ParentID != 0) @@ -14112,9 +14109,7 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo node_settings.SelectedTabID = node->SelectedTabID; node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None; node_settings.Depth = (char)depth; - node_settings.IsDockSpace = (char)node->IsDockSpace(); - node_settings.IsCentralNode = (char)node->IsCentralNode(); - node_settings.IsHiddenTabBar = (char)node->IsHiddenTabBar(); + node_settings.Flags = node->GetMergedFlags() & ImGuiDockNodeFlags_SavedFlagsMask_; node_settings.Pos = ImVec2ih((short)node->Pos.x, (short)node->Pos.y); node_settings.Size = ImVec2ih((short)node->Size.x, (short)node->Size.y); node_settings.SizeRef = ImVec2ih((short)node->SizeRef.x, (short)node->SizeRef.y); @@ -14151,7 +14146,7 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings { const int line_start_pos = buf->size(); (void)line_start_pos; const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n]; - buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", node_settings->IsDockSpace ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file + buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file buf->appendf(" ID=0x%08X", node_settings->ID); if (node_settings->ParentID) buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentID, node_settings->SizeRef.x, node_settings->SizeRef.y); @@ -14159,10 +14154,16 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); if (node_settings->SplitAxis != ImGuiAxis_None) buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y'); - if (node_settings->IsCentralNode) + if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode) buf->appendf(" CentralNode=1"); - if (node_settings->IsHiddenTabBar) + if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar) + buf->appendf(" NoTabBar=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar) buf->appendf(" HiddenTabBar=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton) + buf->appendf(" NoWindowMenuButton=1"); + if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton) + buf->appendf(" NoCloseButton=1"); if (node_settings->SelectedTabID) buf->appendf(" SelectedTab=0x%08X", node_settings->SelectedTabID); @@ -14700,10 +14701,12 @@ void ImGui::ShowDockingDebug() ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : ""); if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) { - ImGui::CheckboxFlags("LocalFlags: NoSplit", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); - ImGui::CheckboxFlags("LocalFlags: NoResize", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); - ImGui::CheckboxFlags("LocalFlags: NoTabBar", (unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar); - ImGui::CheckboxFlags("LocalFlags: HiddenTabBar",(unsigned int*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); + ImGui::CheckboxFlags("LocalFlags: NoSplit", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); + ImGui::CheckboxFlags("LocalFlags: NoResize", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("LocalFlags: NoTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar); + ImGui::CheckboxFlags("LocalFlags: HiddenTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); + ImGui::CheckboxFlags("LocalFlags: NoWindowMenuButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton); + ImGui::CheckboxFlags("LocalFlags: NoCloseButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoCloseButton); ImGui::TreePop(); } if (node->ChildNodes[0]) diff --git a/imgui_internal.h b/imgui_internal.h index 68dc280e..726a0b2a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -884,18 +884,20 @@ struct ImGuiTabBarRef ImGuiTabBarRef(int index_in_main_pool) { Ptr = NULL; IndexInMainPool = index_in_main_pool; } }; +// Extend ImGuiDockNodeFlags_ enum ImGuiDockNodeFlagsPrivate_ { // [Internal] - ImGuiDockNodeFlags_DockSpace = 1 << 10, // Local // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. - ImGuiDockNodeFlags_CentralNode = 1 << 11, // Local - ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Local // Tab bar is completely unavailable. No triangle in the corner to enable it back. - ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Local // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) - ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Local // Disable window/docking menu (that one that appears instead of the collapse button) - ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Local + ImGuiDockNodeFlags_DockSpace = 1 << 10, // Local, Saved // A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + ImGuiDockNodeFlags_CentralNode = 1 << 11, // Local, Saved // + ImGuiDockNodeFlags_NoTabBar = 1 << 12, // Local, Saved // Tab bar is completely unavailable. No triangle in the corner to enable it back. + ImGuiDockNodeFlags_HiddenTabBar = 1 << 13, // Local, Saved // Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) + ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Local, Saved // Disable window/docking menu (that one that appears instead of the collapse button) + ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Local, Saved // ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, - ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace // When splitting those flags are moved to the inheriting child, never duplicated + ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace, // When splitting those flags are moved to the inheriting child, never duplicated + ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton }; // Store the source authority (dock node vs window) of a field From 2d68e892a8161112932d08a14d8f36f2d1be2b34 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 May 2019 17:28:18 +0200 Subject: [PATCH 377/566] Added full "Dear ImGui" prefix to the title of "Dear ImGui Demo" and "Dear ImGui Metrics" windows. Shortened amount of nodes in columns>tree demo. --- docs/CHANGELOG.txt | 7 ++++--- imgui.cpp | 2 +- imgui_demo.cpp | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1ac44f40..830c05be 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,12 +54,13 @@ Other Changes: - Scrollbar: Very minor bounding box adjustment to cope with various border size. - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. -- Style: Made window close button cross is slightly smaller. +- Style: Made window close button cross slightly smaller. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. - ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not - fully cleared. Fixed edge case overflow when adding character 0xFFFF. (#2568). [@NIKE3500] -- Add native Mac clipboard copy/paste default implementation in core library to match what we are + fully cleared. Fixed edge-case overflow when adding character 0xFFFF. (#2568). [@NIKE3500] +- Demo: Added full "Dear ImGui" prefix to the title of "Dear ImGui Demo" and "Dear ImGui Metrics" windows. +- Backends: Add native Mac clipboard copy/paste default implementation in core library to match what we are dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode diff --git a/imgui.cpp b/imgui.cpp index 4ff123e3..b6f61779 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9730,7 +9730,7 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} void ImGui::ShowMetricsWindow(bool* p_open) { - if (!ImGui::Begin("ImGui Metrics", p_open)) + if (!ImGui::Begin("Dear ImGui Metrics", p_open)) { ImGui::End(); return; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 11422252..78327e74 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -246,7 +246,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); // Main body of the Demo window starts here. - if (!ImGui::Begin("ImGui Demo", p_open, window_flags)) + if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags)) { // Early out if the window is collapsed, as an optimization. ImGui::End(); @@ -2572,7 +2572,7 @@ static void ShowDemoWindowColumns() ImGui::NextColumn(); if (open1) { - for (int y = 0; y < 5; y++) + for (int y = 0; y < 3; y++) { bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y); ImGui::NextColumn(); From 5b0e59d9d5582bb450dc922405d177bdc3e252ea Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 May 2019 22:11:21 +0200 Subject: [PATCH 378/566] Docking: Saving local _NoResize flag. (#2583) --- imgui.cpp | 5 ++++- imgui.h | 2 +- imgui_internal.h | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index befe4e5c..c3806d4b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14087,6 +14087,7 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); } } if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; } + if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; } if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; } if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; } if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; } @@ -14109,7 +14110,7 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo node_settings.SelectedTabID = node->SelectedTabID; node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None; node_settings.Depth = (char)depth; - node_settings.Flags = node->GetMergedFlags() & ImGuiDockNodeFlags_SavedFlagsMask_; + node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_); node_settings.Pos = ImVec2ih((short)node->Pos.x, (short)node->Pos.y); node_settings.Size = ImVec2ih((short)node->Size.x, (short)node->Size.y); node_settings.SizeRef = ImVec2ih((short)node->SizeRef.x, (short)node->SizeRef.y); @@ -14154,6 +14155,8 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); if (node_settings->SplitAxis != ImGuiAxis_None) buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y'); + if (node_settings->Flags & ImGuiDockNodeFlags_NoResize) + buf->appendf(" NoResize=1"); if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode) buf->appendf(" CentralNode=1"); if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar) diff --git a/imgui.h b/imgui.h index ecd425a2..5a18b99b 100644 --- a/imgui.h +++ b/imgui.h @@ -895,7 +895,7 @@ enum ImGuiDockNodeFlags_ ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Shared // Disable docking inside the Central Node, which will be always kept empty. ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // Shared // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. ImGuiDockNodeFlags_NoSplit = 1 << 4, // Shared/Local // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. - ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing child nodes using the splitter/separators. Useful with programatically setup dockspaces. + ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing node using the splitter/separators. Useful with programatically setup dockspaces. ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Shared/Local // Tab bar will automatically hide when there is a single window in the dock node. }; diff --git a/imgui_internal.h b/imgui_internal.h index 726a0b2a..30396d2d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -897,7 +897,7 @@ enum ImGuiDockNodeFlagsPrivate_ ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton, ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace, // When splitting those flags are moved to the inheriting child, never duplicated - ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton + ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton }; // Store the source authority (dock node vs window) of a field From c7c1bf177b5bb4a3495a6b82e91c45eed46986f7 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 00:06:21 +0200 Subject: [PATCH 379/566] Docking: Fixed DockBuilderRemoveNode() from overwriting other parent node flags when trying to move the CentralNode flag. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index c3806d4b..7d50ce60 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13492,7 +13492,7 @@ void ImGui::DockBuilderRemoveNode(ImGuiID node_id) DockBuilderRemoveNodeDockedWindows(node_id, true); DockBuilderRemoveNodeChildNodes(node_id); if (node->IsCentralNode() && node->ParentNode) - node->ParentNode->LocalFlags = ImGuiDockNodeFlags_CentralNode; + node->ParentNode->LocalFlags |= ImGuiDockNodeFlags_CentralNode; DockContextRemoveNode(ctx, node, true); } From c0e690318ae82fc9b8fd53f553d90deb374db2e1 Mon Sep 17 00:00:00 2001 From: actboy168 Date: Tue, 28 May 2019 17:15:59 +0800 Subject: [PATCH 380/566] Examples: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) --- examples/imgui_impl_osx.mm | 60 +++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index c5562b4d..c3dac8d7 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -19,6 +19,16 @@ // Data static CFAbsoluteTime g_Time = 0.0; +static NSCursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = { 0 }; +static bool g_MouseCursorHidden = false; + +// Undocumented methods for creating cursors. +@interface NSCursor() ++ (id)_windowResizeNorthWestSouthEastCursor; ++ (id)_windowResizeNorthEastSouthWestCursor; ++ (id)_windowResizeNorthSouthCursor; ++ (id)_windowResizeEastWestCursor; +@end // Functions bool ImGui_ImplOSX_Init() @@ -26,7 +36,7 @@ bool ImGui_ImplOSX_Init() ImGuiIO& io = ImGui::GetIO(); // Setup back-end capabilities flags - //io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) //io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) //io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy) @@ -56,6 +66,24 @@ bool ImGui_ImplOSX_Init() io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; + g_MouseCursorHidden = false; + g_MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor]; + g_MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor]; + g_MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] + ? [NSCursor _windowResizeNorthSouthCursor] + : [NSCursor resizeUpDownCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] + ? [NSCursor _windowResizeEastWestCursor] + : [NSCursor resizeLeftRightCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] + ? [NSCursor _windowResizeNorthEastSouthWestCursor] + : [NSCursor closedHandCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] + ? [NSCursor _windowResizeNorthWestSouthEastCursor] + : [NSCursor closedHandCursor]; + // We don't set the io.SetClipboardTextFn/io.GetClipboardTextFn handlers, // because imgui.cpp has a default for them that works with OSX. @@ -66,6 +94,34 @@ void ImGui_ImplOSX_Shutdown() { } +static void ImGui_ImplOSX_UpdateMouseCursor() +{ + ImGuiIO& io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) + return; + + ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + if (!g_MouseCursorHidden) + { + g_MouseCursorHidden = true; + [NSCursor hide]; + } + } + else + { + // Show OS mouse cursor + [g_MouseCursors[g_MouseCursors[imgui_cursor]? imgui_cursor: ImGuiMouseCursor_Arrow] set]; + if (g_MouseCursorHidden) + { + g_MouseCursorHidden = false; + [NSCursor unhide]; + } + } +} + void ImGui_ImplOSX_NewFrame(NSView* view) { // Setup display size @@ -80,6 +136,8 @@ void ImGui_ImplOSX_NewFrame(NSView* view) CFAbsoluteTime current_time = CFAbsoluteTimeGetCurrent(); io.DeltaTime = current_time - g_Time; g_Time = current_time; + + ImGui_ImplOSX_UpdateMouseCursor(); } static int mapCharacterToKey(int c) From 2742663ad267d39703f156c80cb73eac5829da65 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 11:22:17 +0200 Subject: [PATCH 381/566] Changelog, minor tweaks. (#2585) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_osx.h | 8 +++++--- examples/imgui_impl_osx.mm | 28 ++++++++++++---------------- 3 files changed, 18 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 830c05be..059950eb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,7 @@ Other Changes: - Demo: Added full "Dear ImGui" prefix to the title of "Dear ImGui Demo" and "Dear ImGui Metrics" windows. - Backends: Add native Mac clipboard copy/paste default implementation in core library to match what we are dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] +- Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) diff --git a/examples/imgui_impl_osx.h b/examples/imgui_impl_osx.h index b7f41cbc..66df2527 100644 --- a/examples/imgui_impl_osx.h +++ b/examples/imgui_impl_osx.h @@ -1,10 +1,12 @@ // dear imgui: Platform Binding for OSX / Cocoa // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) -// [BETA] Beta bindings, not well tested. If you want a portable application, prefer using the Glfw or SDL platform bindings on Mac. +// [ALPHA] Early bindings, not well tested. If you want a portable application, prefer using the GLFW or SDL platform bindings on Mac. +// Implemented features: +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this back-end). // Issues: -// [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. -// [ ] Platform: Mouse cursor shapes and visibility are not supported (see end of https://github.com/glfw/glfw/issues/427) +// [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. @class NSEvent; @class NSView; diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index c3dac8d7..cfcd3a74 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -1,10 +1,12 @@ // dear imgui: Platform Binding for OSX / Cocoa // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) -// [BETA] Beta bindings, not well tested. If you want a portable application, prefer using the Glfw or SDL platform bindings on Mac. +// [ALPHA] Early bindings, not well tested. If you want a portable application, prefer using the GLFW or SDL platform bindings on Mac. +// Implemented features: +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this back-end). // Issues: -// [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. -// [ ] Platform: Mouse cursor shapes and visibility are not supported (see end of https://github.com/glfw/glfw/issues/427) +// [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. #include "imgui.h" #include "imgui_impl_osx.h" @@ -12,6 +14,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-28: Inputs: Added mouse cursor shape and visibility support. // 2019-05-18: Misc: Removed clipboard handlers as they are now supported by core imgui.cpp. // 2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. @@ -66,23 +69,16 @@ bool ImGui_ImplOSX_Init() io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; + // Load cursors. Some of them are undocumented. g_MouseCursorHidden = false; g_MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor]; g_MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor]; g_MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor]; g_MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] - ? [NSCursor _windowResizeNorthSouthCursor] - : [NSCursor resizeUpDownCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] - ? [NSCursor _windowResizeEastWestCursor] - : [NSCursor resizeLeftRightCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] - ? [NSCursor _windowResizeNorthEastSouthWestCursor] - : [NSCursor closedHandCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] - ? [NSCursor _windowResizeNorthWestSouthEastCursor] - : [NSCursor closedHandCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor]; + g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor]; // We don't set the io.SetClipboardTextFn/io.GetClipboardTextFn handlers, // because imgui.cpp has a default for them that works with OSX. @@ -113,7 +109,7 @@ static void ImGui_ImplOSX_UpdateMouseCursor() else { // Show OS mouse cursor - [g_MouseCursors[g_MouseCursors[imgui_cursor]? imgui_cursor: ImGuiMouseCursor_Arrow] set]; + [g_MouseCursors[g_MouseCursors[imgui_cursor] ? imgui_cursor : ImGuiMouseCursor_Arrow] set]; if (g_MouseCursorHidden) { g_MouseCursorHidden = false; From 70d9f79312233622a4f9e683177105a226b27b8c Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 May 2019 22:41:17 +0200 Subject: [PATCH 382/566] Internal: Renamed InnerMainRect to InnerVisibleRect. Printing coordinates in Metrics window. --- imgui.cpp | 57 ++++++++++++++++++++++++++++------------------- imgui_internal.h | 6 ++--- imgui_widgets.cpp | 8 +++---- 3 files changed, 41 insertions(+), 30 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b6f61779..cdcb0955 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3056,7 +3056,7 @@ void ImGui::SetCurrentContext(ImGuiContext* ctx) // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui. // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code -// may see different structures thanwhat imgui.cpp sees, which is problematic. +// may see different structures than what imgui.cpp sees, which is problematic. // We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui. bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) { @@ -5503,10 +5503,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); - window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; - window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); - window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); - window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); + window->InnerVisibleRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; + window->InnerVisibleRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + window->InnerVisibleRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); + window->InnerVisibleRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); // Outer host rectangle for drawing background and borders ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; @@ -5518,10 +5518,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Inner work/clipping rectangle will extend a little bit outside the work region. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. - window->InnerWorkRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerWorkRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); - window->InnerWorkRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerWorkRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); + window->InnerWorkRect.Min.x = ImFloor(0.5f + window->InnerVisibleRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerWorkRect.Min.y = ImFloor(0.5f + window->InnerVisibleRect.Min.y); + window->InnerWorkRect.Max.x = ImFloor(0.5f + window->InnerVisibleRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->InnerWorkRect.Max.y = ImFloor(0.5f + window->InnerVisibleRect.Max.y); window->InnerWorkRectClipped = window->InnerWorkRect; window->InnerWorkRectClipped.ClipWithFull(host_rect); @@ -7830,7 +7830,7 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput // NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated. static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) { - ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1)); + ImRect window_rect(window->InnerVisibleRect.Min - ImVec2(1, 1), window->InnerVisibleRect.Max + ImVec2(1, 1)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] if (window_rect.Contains(item_rect)) return; @@ -8104,7 +8104,7 @@ static void ImGui::NavUpdate() if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0) { ImGuiWindow* window = g.NavWindow; - ImRect window_rect_rel(window->InnerMainRect.Min - window->Pos - ImVec2(1,1), window->InnerMainRect.Max - window->Pos + ImVec2(1,1)); + ImRect window_rect_rel(window->InnerVisibleRect.Min - window->Pos - ImVec2(1,1), window->InnerVisibleRect.Max - window->Pos + ImVec2(1,1)); if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { float pad = window->CalcFontSize() * 0.5f; @@ -8205,14 +8205,14 @@ static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) - SetWindowScrollY(window, window->Scroll.y - window->InnerMainRect.GetHeight()); + SetWindowScrollY(window, window->Scroll.y - window->InnerVisibleRect.GetHeight()); else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) - SetWindowScrollY(window, window->Scroll.y + window->InnerMainRect.GetHeight()); + SetWindowScrollY(window, window->Scroll.y + window->InnerVisibleRect.GetHeight()); } else { const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; - const float page_offset_y = ImMax(0.0f, window->InnerMainRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); + const float page_offset_y = ImMax(0.0f, window->InnerVisibleRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); float nav_scoring_rect_offset_y = 0.0f; if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) { @@ -9736,7 +9736,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; } - enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerMainRect, RT_InnerWorkRect, RT_InnerWorkRectClipped, RT_ContentsRegionRect, RT_ContentsFullRect }; + enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerVisibleRect, RT_InnerWorkRect, RT_InnerWorkRectClipped, RT_ContentsRegionRect, RT_ContentsFullRect }; static bool show_windows_begin_order = false; static bool show_windows_rects = false; static int show_windows_rect_type = RT_InnerWorkRect; @@ -9752,6 +9752,18 @@ void ImGui::ShowMetricsWindow(bool* p_open) struct Funcs { + static ImRect GetRect(ImGuiWindow* window, int rect_type) + { + if (rect_type == RT_OuterRect) { return window->Rect(); } + else if (rect_type == RT_OuterRectClipped) { return window->OuterRectClipped; } + else if (rect_type == RT_InnerVisibleRect) { return window->InnerVisibleRect; } + else if (rect_type == RT_InnerWorkRect) { return window->InnerWorkRect; } + else if (rect_type == RT_InnerWorkRectClipped) { return window->InnerWorkRectClipped; } + else if (rect_type == RT_ContentsRegionRect) { return window->ContentsRegionRect; } + IM_ASSERT(0); + return ImRect(); + } + static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label) { bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); @@ -9953,7 +9965,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerMainRect\0" "InnerWorkRect\0" "InnerWorkRectClipped\0" "ContentsRegionRect\0"); + show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerVisibleRect\0" "InnerWorkRect\0" "InnerWorkRectClipped\0" "ContentsRegionRect\0"); + if (show_windows_rects && g.NavWindow) + { + ImRect r = Funcs::GetRect(g.NavWindow, show_windows_rect_type); + ImGui::BulletText("'%s': (%.1f,%.1f) (%.1f,%.1f) Size (%.1f,%.1f)", g.NavWindow->Name, r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight()); + } ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects); ImGui::TreePop(); } @@ -9968,13 +9985,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImDrawList* draw_list = GetForegroundDrawList(window); if (show_windows_rects) { - ImRect r; - if (show_windows_rect_type == RT_OuterRect) { r = window->Rect(); } - else if (show_windows_rect_type == RT_OuterRectClipped) { r = window->OuterRectClipped; } - else if (show_windows_rect_type == RT_InnerMainRect) { r = window->InnerMainRect; } - else if (show_windows_rect_type == RT_InnerWorkRect) { r = window->InnerWorkRect; } - else if (show_windows_rect_type == RT_InnerWorkRectClipped) { r = window->InnerWorkRectClipped; } - else if (show_windows_rect_type == RT_ContentsRegionRect) { r = window->ContentsRegionRect; } + ImRect r = Funcs::GetRect(window, show_windows_rect_type); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow)) diff --git a/imgui_internal.h b/imgui_internal.h index b1fa060a..cbefc9ea 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1249,8 +1249,8 @@ struct IMGUI_API ImGuiWindow ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) ImVec2 SizeFull; // Size when non collapsed ImVec2 SizeFullAtLastBegin; // Copy of SizeFull at the end of Begin. This is the reference value we'll use on the next frame to decide if we need scrollbars. - ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame. Include decoration, window title, border, menu, etc. - ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize() + ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame. FIXME: Include decoration, window title, border, menu, etc. Ideally should remove them from this value? + ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize(). EXCLUDE decorations. Making this not consistent with the above! ImVec2 WindowPadding; // Window padding at the time of begin. float WindowRounding; // Window rounding at the time of begin. float WindowBorderSize; // Window border size at the time of begin. @@ -1292,7 +1292,7 @@ struct IMGUI_API ImGuiWindow ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack ImRect ClipRect; // Current clipping rectangle. = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. ImRect OuterRectClipped; // == WindowRect just after setup in Begin(). == window->Rect() for root window. - ImRect InnerMainRect; // + ImRect InnerVisibleRect; // Inner visible rectangle ImRect InnerWorkRect; // == InnerMainRect minus WindowPadding.x ImRect InnerWorkRectClipped; // == InnerMainRect minus WindowPadding.x, clipped within viewport or parent clip rect. ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. Maximum visible content position ~~ Pos + (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e5dc8c2b..a691185a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -888,14 +888,14 @@ void ImGui::Scrollbar(ImGuiAxis axis) ImRect bb; if (axis == ImGuiAxis_X) { - bb.Min = ImVec2(window->InnerMainRect.Min.x, window->InnerMainRect.Max.y); - bb.Max = ImVec2(window->InnerMainRect.Max.x, outer_rect.Max.y - window->WindowBorderSize); + bb.Min = ImVec2(window->InnerVisibleRect.Min.x, window->InnerVisibleRect.Max.y); + bb.Max = ImVec2(window->InnerVisibleRect.Max.x, outer_rect.Max.y - window->WindowBorderSize); rounding_corners |= ImDrawCornerFlags_BotLeft; } else { - bb.Min = ImVec2(window->InnerMainRect.Max.x, window->InnerMainRect.Min.y); - bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerMainRect.Max.y); + bb.Min = ImVec2(window->InnerVisibleRect.Max.x, window->InnerVisibleRect.Min.y); + bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerVisibleRect.Max.y); rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; } ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->SizeFull[axis] - other_scrollbar_size, window->SizeContents[axis], rounding_corners); From c487bc52a2790f54cc53c0f8d5138ac7e30bad2d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 20:17:15 +0200 Subject: [PATCH 383/566] Fonts: Added some details about using custom colorful icons. --- imgui.h | 10 ++++++---- misc/fonts/README.txt | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/imgui.h b/imgui.h index e0dcaecb..b1d18633 100644 --- a/imgui.h +++ b/imgui.h @@ -2077,11 +2077,14 @@ struct ImFontAtlas IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietname characters //------------------------------------------- - // Custom Rectangles/Glyphs API + // [BETA] Custom Rectangles/Glyphs API //------------------------------------------- - // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels. - // You can also 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. + // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. + // After calling Build(), you can query the rectangle position and render your pixels. + // You can also 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. + // Read misc/fonts/README.txt for more details about using colorful icons. struct CustomRect { unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data. @@ -2093,7 +2096,6 @@ struct ImFontAtlas CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } bool IsPacked() const { return X != 0xFFFF; } }; - IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font. const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index 0fcc6c79..e658ac67 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -26,6 +26,7 @@ If you have other loading/merging/adding fonts, you can post on the Dear ImGui " - Fonts Loading Instructions - FreeType rasterizer, Small font sizes - Building Custom Glyph Ranges +- Using custom colorful icons - Embedding Fonts in Source Code - Credits/Licences for fonts included in this folder - Fonts Links @@ -198,6 +199,43 @@ For example: for a game where your script is known, if you can feed your entire io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. +--------------------------------------- + USING CUSTOM COLORFUL ICONS +--------------------------------------- + +(This is a BETA api, use if you are familiar with dear imgui and with your rendering back-end) + +You can use the ImFontAtlas::AddCustomRect() and ImFontAtlas::AddCustomRectFontGlyph() api to register rectangles +that will be packed into the font atlas texture. Register them before building the atlas, then call Build(). +You can then use ImFontAtlas::GetCustomRectByIndex(int) to query the position/size of your rectangle within the +texture, and blit/copy any graphics data of your choice into those rectangles. + +Pseudo-code: + + // Add font, then register one custom 13x13 rectangle mapped to glyph 'a' of this font + ImFont* font = io.Fonts->AddFontDefault(); + int rect_id = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1); + + // Build atlas + io.Fonts->Build(); + + // Retrieve texture in RGBA format + unsigned char* tex_pixels = NULL; + int tex_width, tex_height; + io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); + + // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here) + if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) + { + for (int y = 0; y < rect->Height; y++) + { + ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X); + for (int x = rect->Width; x > 0; x--) + *p++ = IM_COL32(255, 0, 0, 255); + } + } + + --------------------------------------- EMBEDDING FONTS IN SOURCE CODE --------------------------------------- From cb7ba60d3f7d691c698c4a7499ed64757664d7b8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 21:22:18 +0200 Subject: [PATCH 384/566] CollapsingHeader: When a close button is enabled, better clip the label to avoid overlap. (#600) --- docs/CHANGELOG.txt | 1 + imgui_internal.h | 6 ++++++ imgui_widgets.cpp | 14 +++++++++----- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 059950eb..acd43c0e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: - Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) - ColorEdit: Fixed the color picker popup only displaying inputs as HSV instead of showing multiple options. (#2587, broken in 1.69 by #2384). +- CollapsingHeader: Better clipping when a close button is enabled and it overlaps the label. (#600) - Scrollbar: Very minor bounding box adjustment to cope with various border size. - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. diff --git a/imgui_internal.h b/imgui_internal.h index cbefc9ea..ef25cda1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -361,6 +361,12 @@ enum ImGuiSelectableFlagsPrivate_ ImGuiSelectableFlags_AllowItemOverlap = 1 << 24 }; +// Extend ImGuiTreeNodeFlags_ +enum ImGuiTreeNodeFlagsPrivate_ +{ + ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20 +}; + enum ImGuiSeparatorFlags_ { ImGuiSeparatorFlags_None = 0, diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a691185a..e806eec0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5131,8 +5131,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (display_frame) { // Framed header expand a little outside the default padding - frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; - frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; + frame_bb.Min.x -= (float)(int)(window->WindowPadding.x * 0.5f) - 1; + frame_bb.Max.x += (float)(int)(window->WindowPadding.x * 0.5f) - 1; } const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing @@ -5229,6 +5229,8 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding); RenderNavHighlight(frame_bb, id, nav_highlight_flags); RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); + if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton) + frame_bb.Max.x -= g.FontSize + style.FramePadding.x; if (g.LogEnabled) { // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. @@ -5355,7 +5357,8 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags return false; ImGuiID id = window->GetID(label); - bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label); + flags |= ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton : 0); + bool is_open = TreeNodeBehavior(id, flags, label); if (p_open) { // Create a small overlapping close button @@ -5364,8 +5367,9 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags ImGuiContext& g = *GImGui; ImGuiItemHoveredDataBackup last_item_backup; float button_size = g.FontSize; - ImVec2 button_pos = ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x * 2.0f - button_size, window->DC.LastItemRect.Min.y); - if (CloseButton(window->GetID((void*)((intptr_t)id + 1)), button_pos)) + float button_x = ImMax(window->DC.LastItemRect.Min.x, window->DC.LastItemRect.Max.x - g.Style.FramePadding.x * 2.0f - button_size); + float button_y = window->DC.LastItemRect.Min.y; + if (CloseButton(window->GetID((void*)((intptr_t)id + 1)), ImVec2(button_x, button_y))) *p_open = false; last_item_backup.Restore(); } From 40b9e5e0b42bdc4849482cd248b17e49ab707edb Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 May 2019 12:52:29 +0200 Subject: [PATCH 385/566] ImDrawList: Store initial flags for the frame in ImDrawListSharedData, reducing code duplication in setting up the flags. --- imgui.cpp | 4 +--- imgui.h | 6 +++--- imgui_draw.cpp | 3 ++- imgui_internal.h | 5 ++--- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cdcb0955..c200f480 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3502,16 +3502,15 @@ void ImGui::NewFrame() IM_ASSERT(g.Font->IsLoaded()); g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; + g.DrawListSharedData.InitialFlags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); g.BackgroundDrawList.Clear(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); - g.BackgroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); g.ForegroundDrawList.Clear(); g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.ForegroundDrawList.PushClipRectFullScreen(); - g.ForegroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); // Mark rendering data as invalid to prevent user who may have a handle on it to use it. g.DrawData.Clear(); @@ -5529,7 +5528,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Setup draw list and outer clipping rectangle window->DrawList->Clear(); - window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); diff --git a/imgui.h b/imgui.h index b1d18633..b3f979bf 100644 --- a/imgui.h +++ b/imgui.h @@ -218,9 +218,9 @@ namespace ImGui IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render. // Demo, Debug, Information - IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! - IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create about window. display Dear ImGui version, credits and build/system information. - IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics/debug window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. + IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! + IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debug window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index dcbaae06..09e4473e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -348,6 +348,7 @@ ImDrawListSharedData::ImDrawListSharedData() FontSize = 0.0f; CurveTessellationTol = 0.0f; ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f); + InitialFlags = ImDrawListFlags_None; // Const data for (int i = 0; i < IM_ARRAYSIZE(CircleVtx12); i++) @@ -362,7 +363,7 @@ void ImDrawList::Clear() CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); - Flags = ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill; + Flags = _Data->InitialFlags; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; diff --git a/imgui_internal.h b/imgui_internal.h index ef25cda1..6d396460 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -731,6 +731,7 @@ struct IMGUI_API ImDrawListSharedData float FontSize; // Current/default font size (optional, for simplified AddText overload) float CurveTessellationTol; ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() + ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) // Const data // FIXME: Bake rounded corners fill/borders in atlas @@ -1034,7 +1035,7 @@ struct ImGuiContext int WantTextInputNextFrame; char TempBuffer[1024*3+1]; // Temporary text buffer - ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(NULL), ForegroundDrawList(NULL) + ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(&DrawListSharedData), ForegroundDrawList(&DrawListSharedData) { Initialized = false; FrameScopeActive = FrameScopePushedImplicitWindow = false; @@ -1109,9 +1110,7 @@ struct ImGuiContext FocusTabPressed = false; DimBgRatio = 0.0f; - BackgroundDrawList._Data = &DrawListSharedData; BackgroundDrawList._OwnerName = "##Background"; // Give it a name for debugging - ForegroundDrawList._Data = &DrawListSharedData; ForegroundDrawList._OwnerName = "##Foreground"; // Give it a name for debugging MouseCursor = ImGuiMouseCursor_Arrow; From d1e8b698d0e1c26744817490f8ee4f91182dcb9d Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 May 2019 15:25:53 +0200 Subject: [PATCH 386/566] ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bits indices. To enable the feature, the renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset' and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not support 32-bits indices. ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. This is provided for convenience and consistency with VtxOffset. (#2591) --- docs/CHANGELOG.txt | 7 +++++++ imconfig.h | 5 ++++- imgui.cpp | 44 ++++++++++++++++++++++++++++++-------------- imgui.h | 27 ++++++++++++++++++--------- imgui_demo.cpp | 2 ++ imgui_draw.cpp | 13 ++++++++++++- 6 files changed, 73 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index acd43c0e..cbd3febf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,13 @@ Other Changes: - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. - Style: Made window close button cross slightly smaller. +- ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bits indices. + To enable the feature, the renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset' + and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. + This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not + support 32-bits indices. Most examples back-ends have been modified to support the VtxOffset field. +- ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. + This is provided for convenience and consistency with VtxOffset. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. - ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not diff --git a/imconfig.h b/imconfig.h index b496ae91..5476dd66 100644 --- a/imconfig.h +++ b/imconfig.h @@ -62,7 +62,10 @@ operator MyVec4() const { return MyVec4(x,y,z,w); } */ -//---- Use 32-bit vertex indices (default is 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it. +//---- Using 32-bits vertex indices (default is 16-bits) is one way to allow large meshes with more than 64K vertices. +// Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bits indices). +// Another way to allow large meshes while keeping 16-bits indices is to handle ImDrawCmd::VtxOffset in your renderer. +// Read about ImGuiBackendFlags_HasVtxOffset for details. //#define ImDrawIdx unsigned int //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. diff --git a/imgui.cpp b/imgui.cpp index c200f480..2b0cbf4f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3502,7 +3502,13 @@ void ImGui::NewFrame() IM_ASSERT(g.Font->IsLoaded()); g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; - g.DrawListSharedData.InitialFlags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); + g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; + if (g.Style.AntiAliasedLines) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; + if (g.Style.AntiAliasedFill) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; + if (g.IO.BackendFlags & ImGuiBackendFlags_HasVtxOffset) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; g.BackgroundDrawList.Clear(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); @@ -3774,19 +3780,28 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d return; } - // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly. + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + // 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); - IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset)) + 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) // If this assert triggers because you are drawing lots of stuff manually: - // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents. - // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes. - // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing: - // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); - // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API. - // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists. + // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds. + // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents. + // - If you want large meshes with more than 64K vertices, you can either: + // (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset'. + // Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't. + // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them. + // (B) Or handle 32-bits indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. + // Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time: + // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + // Your own engine or render API may use different parameters or function calls to specify index sizes. + // 2 and 4 bytes indices are generally supported by most graphics API. + // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching + // the 64K limit to split your draw commands in multiple draw lists. if (sizeof(ImDrawIdx) == 2) IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above"); @@ -9790,9 +9805,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) continue; } ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; - bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), - "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", - pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + char buf[300]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "Draw %4d triangles, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered()) { ImRect clip_rect = pcmd->ClipRect; @@ -9806,11 +9822,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) continue; // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. + ImGui::Text("ElemCount: %d, ElemCount/3: %d, VtxOffset: +%d, IdxOffset: +%d", pcmd->ElemCount, pcmd->ElemCount/3, pcmd->VtxOffset, pcmd->IdxOffset); ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) { - char buf[300]; char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangles_pos[3]; for (int n = 0; n < 3; n++, idx_i++) @@ -9819,7 +9835,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImDrawVert& v = draw_list->VtxBuffer[vtx_i]; triangles_pos[n] = v.pos; buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", - (n == 0) ? "idx" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + (n == 0) ? "elem" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); } ImGui::Selectable(buf, false); if (fg_draw_list && ImGui::IsItemHovered()) diff --git a/imgui.h b/imgui.h index b3f979bf..4580a181 100644 --- a/imgui.h +++ b/imgui.h @@ -47,7 +47,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.71 WIP" -#define IMGUI_VERSION_NUM 17002 +#define IMGUI_VERSION_NUM 17003 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -1003,9 +1003,10 @@ enum ImGuiConfigFlags_ enum ImGuiBackendFlags_ { ImGuiBackendFlags_None = 0, - ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end supports gamepad and currently has one connected. - ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end supports honoring GetMouseCursor() value to change the OS cursor shape. - ImGuiBackendFlags_HasSetMousePos = 1 << 2 // Back-end supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). + ImGuiBackendFlags_HasGamepad = 1 << 0, // Platform Back-end supports gamepad and currently has one connected. + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Platform Back-end supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Platform Back-end supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). + ImGuiBackendFlags_HasVtxOffset = 1 << 3 // Renderer Back-end supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bits indices. }; // Enumeration for PushStyleColor() / PopStyleColor() @@ -1771,25 +1772,31 @@ struct ImColor // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); -// Special Draw Callback value to request renderer back-end to reset the graphics/render state. +// Special Draw callback value to request renderer back-end to reset the graphics/render state. // The renderer back-end needs to handle this special value, otherwise it will crash trying to call a function at this address. // This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored. // It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call). #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) // Typically, 1 command = 1 GPU draw call (unless command is a callback) +// Pre 1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. When (io.BackendFlags & ImGuiBackendFlags_HasVtxOffset) +// is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bits indices. struct ImDrawCmd { unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_HasVtxOffset: always 0. With ImGuiBackendFlags_HasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bits indices. + unsigned int IdxOffset; // Start offset in index buffer. Always equal to sum of ElemCount drawn so far. ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // The draw callback code can access this. - ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = (ImTextureID)NULL; UserCallback = NULL; UserCallbackData = NULL; } + ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; } }; -// Vertex index (override with '#define ImDrawIdx unsigned int' in imconfig.h) +// Vertex index +// (to allow large meshes with 16-bits indices: set 'io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer back-end) +// (to use 32-bits indices: override with '#define ImDrawIdx unsigned int' in imconfig.h) #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; #endif @@ -1835,7 +1842,8 @@ enum ImDrawListFlags_ { ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles) - ImDrawListFlags_AntiAliasedFill = 1 << 1 // Filled shapes have anti-aliased edges (*2 the number of vertices) + ImDrawListFlags_AntiAliasedFill = 1 << 1, // Filled shapes have anti-aliased edges (*2 the number of vertices) + ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'io.BackendFlags & ImGuiBackendFlags_HasVtxOffset' is enabled. }; // Draw command list @@ -1855,7 +1863,8 @@ struct ImDrawList // [Internal, used while building lists] const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) const char* _OwnerName; // Pointer to owner window's name for debugging - unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size + unsigned int _VtxCurrentOffset; // [Internal] Always 0 unless 'Flags & ImDrawListFlags_AllowVtxOffset'. + unsigned int _VtxCurrentIdx; // [Internal] Generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImVector _ClipRectStack; // [Internal] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 78327e74..82aa7431 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -350,6 +350,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasSetMousePos); + ImGui::CheckboxFlags("io.BackendFlags: HasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasVtxOffset); ImGui::TreePop(); ImGui::Separator(); } @@ -2862,6 +2863,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); + if (io.BackendFlags & ImGuiBackendFlags_HasVtxOffset) ImGui::Text(" HasVtxOffset"); ImGui::Separator(); ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 09e4473e..442c0e18 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -364,6 +364,7 @@ void ImDrawList::Clear() IdxBuffer.resize(0); VtxBuffer.resize(0); Flags = _Data->InitialFlags; + _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -416,6 +417,8 @@ void ImDrawList::AddDrawCmd() ImDrawCmd draw_cmd; draw_cmd.ClipRect = GetCurrentClipRect(); draw_cmd.TextureId = GetCurrentTextureId(); + draw_cmd.VtxOffset = _VtxCurrentOffset; + draw_cmd.IdxOffset = IdxBuffer.Size; IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); CmdBuffer.push_back(draw_cmd); @@ -604,6 +607,14 @@ void ImDrawList::ChannelsSetCurrent(int idx) // NB: this can be called with negative count for removing primitives (as long as the result does not underflow) void ImDrawList::PrimReserve(int idx_count, int vtx_count) { + // Large mesh support (when enabled) + if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) + { + _VtxCurrentOffset = VtxBuffer.Size; + _VtxCurrentIdx = 0; + AddDrawCmd(); + } + ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; draw_cmd.ElemCount += idx_count; @@ -2950,7 +2961,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); draw_list->_VtxWritePtr = vtx_write; draw_list->_IdxWritePtr = idx_write; - draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size; + draw_list->_VtxCurrentIdx = vtx_current_idx; } //----------------------------------------------------------------------------- From b3dd03f5822aa34be03008db3dd1ad35618cb141 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 May 2019 15:53:36 +0200 Subject: [PATCH 387/566] Examples/Backends: DirectX9/10/11/12, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_HasVtxOffset' config flag in back-end. (#2591) --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_dx10.cpp | 14 +++++++++----- examples/imgui_impl_dx10.h | 1 + examples/imgui_impl_dx11.cpp | 14 +++++++++----- examples/imgui_impl_dx11.h | 1 + examples/imgui_impl_dx12.cpp | 14 +++++++++----- examples/imgui_impl_dx12.h | 1 + examples/imgui_impl_dx9.cpp | 14 +++++++++----- examples/imgui_impl_dx9.h | 1 + examples/imgui_impl_opengl3.cpp | 17 ++++++++++++++--- examples/imgui_impl_opengl3.h | 1 + examples/imgui_impl_vulkan.cpp | 15 ++++++++++----- examples/imgui_impl_vulkan.h | 2 ++ 13 files changed, 69 insertions(+), 28 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cbd3febf..80792ca8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,8 @@ Other Changes: - Backends: Add native Mac clipboard copy/paste default implementation in core library to match what we are dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] +- Examples/Backends: DirectX9/10/11/12, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes + (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_HasVtxOffset' config flag in back-end. - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 235428fc..0d37e8e3 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -10,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. // 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. @@ -208,8 +210,9 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX10_SetupRenderState(draw_data, ctx); // Render command lists - int vtx_offset = 0; - int idx_offset = 0; + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -235,11 +238,11 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) // Bind texture, Draw ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->TextureId; ctx->PSSetShaderResources(0, 1, &texture_srv); - ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset); + ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset); } - idx_offset += pcmd->ElemCount; } - vtx_offset += cmd_list->VtxBuffer.Size; + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; } // Restore modified DX state @@ -485,6 +488,7 @@ bool ImGui_ImplDX10_Init(ID3D10Device* device) { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx10"; + io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device IDXGIDevice* pDXGIDevice = NULL; diff --git a/examples/imgui_impl_dx10.h b/examples/imgui_impl_dx10.h index 6e0ff4af..db156e17 100644 --- a/examples/imgui_impl_dx10.h +++ b/examples/imgui_impl_dx10.h @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 18c32e6c..d7ddd8a6 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp @@ -10,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. @@ -213,8 +215,9 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX11_SetupRenderState(draw_data, ctx); // Render command lists - int vtx_offset = 0; - int idx_offset = 0; + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_idx_offset = 0; + int global_vtx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -240,11 +243,11 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) // Bind texture, Draw ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->TextureId; ctx->PSSetShaderResources(0, 1, &texture_srv); - ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset); + ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset); } - idx_offset += pcmd->ElemCount; } - vtx_offset += cmd_list->VtxBuffer.Size; + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; } // Restore modified DX state @@ -492,6 +495,7 @@ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_co { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx11"; + io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device IDXGIDevice* pDXGIDevice = NULL; diff --git a/examples/imgui_impl_dx11.h b/examples/imgui_impl_dx11.h index 8eda59f5..1741a5d3 100644 --- a/examples/imgui_impl_dx11.h +++ b/examples/imgui_impl_dx11.h @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 358b2e55..8831adb5 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // Issues: // [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See github.com/ocornut/imgui/pull/301 @@ -12,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Various minor tidying up. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). @@ -200,8 +202,9 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); // Render command lists - int vtx_offset = 0; - int idx_offset = 0; + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -224,11 +227,11 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) }; ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId); ctx->RSSetScissorRects(1, &r); - ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, idx_offset, vtx_offset, 0); + ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } - idx_offset += pcmd->ElemCount; } - vtx_offset += cmd_list->VtxBuffer.Size; + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; } } @@ -604,6 +607,7 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx12"; + io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. g_pd3dDevice = device; g_RTVFormat = rtv_format; diff --git a/examples/imgui_impl_dx12.h b/examples/imgui_impl_dx12.h index e5b9dc4e..8ae75e53 100644 --- a/examples/imgui_impl_dx12.h +++ b/examples/imgui_impl_dx12.h @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // Issues: // [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See github.com/ocornut/imgui/pull/301 diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index fd4522cd..886de1f6 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -10,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. @@ -172,8 +174,9 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX9_SetupRenderState(draw_data); // Render command lists - int vtx_offset = 0; - int idx_offset = 0; + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -196,11 +199,11 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId; g_pd3dDevice->SetTexture(0, texture); g_pd3dDevice->SetScissorRect(&r); - g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, idx_offset, pcmd->ElemCount/3); + g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount/3); } - idx_offset += pcmd->ElemCount; } - vtx_offset += cmd_list->VtxBuffer.Size; + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; } // Restore the DX9 transform @@ -217,6 +220,7 @@ bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx9"; + io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. g_pd3dDevice = device; g_pd3dDevice->AddRef(); diff --git a/examples/imgui_impl_dx9.h b/examples/imgui_impl_dx9.h index 95902f74..3af22d3f 100644 --- a/examples/imgui_impl_dx9.h +++ b/examples/imgui_impl_dx9.h @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index d992f001..06e9948c 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -5,6 +5,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -12,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. // 2019-03-15: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. @@ -102,6 +104,13 @@ #endif #endif +// Desktop GL has glDrawElementsBaseVertex() which GL ES and WebGL don't have. +#if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) +#define IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX 1 +#else +#define IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX 0 +#endif + // OpenGL Data static char g_GlslVersionString[32] = ""; static GLuint g_FontTexture = 0; @@ -263,7 +272,6 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; - size_t idx_buffer_offset = 0; // Upload vertex/index buffers glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); @@ -300,10 +308,13 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); - glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)idx_buffer_offset); +#if IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX + glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)pcmd->IdxOffset, (GLint)pcmd->VtxOffset); +#else + glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)pcmd->IdxOffset); +#endif } } - idx_buffer_offset += pcmd->ElemCount * sizeof(ImDrawIdx); } } diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index 9fe2a88d..0f7eef74 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -5,6 +5,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index e5c95079..ef6afcd2 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -1,6 +1,8 @@ // dear imgui: Renderer for Vulkan // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// Implemented features: +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // Missing features: // [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914 @@ -20,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). // 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. @@ -375,8 +378,9 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists - int vtx_offset = 0; - int idx_offset = 0; + // (Because we merged all buffers into a single one, we maintain our own offset into them) + int global_vtx_offset = 0; + int global_idx_offset = 0; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -418,12 +422,12 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm vkCmdSetScissor(command_buffer, 0, 1, &scissor); // Draw - vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0); + vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } } - idx_offset += pcmd->ElemCount; } - vtx_offset += cmd_list->VtxBuffer.Size; + global_idx_offset += cmd_list->IdxBuffer.Size; + global_vtx_offset += cmd_list->VtxBuffer.Size; } } @@ -801,6 +805,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_vulkan"; + io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. IM_ASSERT(info->Instance != VK_NULL_HANDLE); IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index cff866d9..80356b96 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -1,6 +1,8 @@ // dear imgui: Renderer for Vulkan // This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// Implemented features: +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // Missing features: // [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914 From 7755cbbef2fcccba35bd46a8defad2d9d36c20f5 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 May 2019 16:29:17 +0200 Subject: [PATCH 388/566] Renamed ImGuiBackendFlags_HasVtxOffset to ImGuiBackendFlags_RendererHasVtxOffset to match naming convention already used in viewport/docking branch. (#2591) + Fix OpenGL3 code missing flag. --- docs/CHANGELOG.txt | 6 +++--- examples/imgui_impl_dx10.cpp | 4 ++-- examples/imgui_impl_dx11.cpp | 4 ++-- examples/imgui_impl_dx12.cpp | 4 ++-- examples/imgui_impl_dx9.cpp | 4 ++-- examples/imgui_impl_opengl3.cpp | 5 ++++- examples/imgui_impl_vulkan.cpp | 4 ++-- imconfig.h | 2 +- imgui.cpp | 4 ++-- imgui.h | 16 ++++++++-------- imgui_demo.cpp | 4 ++-- 11 files changed, 30 insertions(+), 27 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 80792ca8..ef8e2310 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,8 +57,8 @@ Other Changes: collapsing/docking button to the other side of the title bar. - Style: Made window close button cross slightly smaller. - ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bits indices. - To enable the feature, the renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset' - and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. + The renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' to enable + this, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not support 32-bits indices. Most examples back-ends have been modified to support the VtxOffset field. - ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. @@ -72,7 +72,7 @@ Other Changes: dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] - Examples/Backends: DirectX9/10/11/12, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes - (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_HasVtxOffset' config flag in back-end. + (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 0d37e8e3..4c3e5bbb 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -11,7 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. +// 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. @@ -488,7 +488,7 @@ bool ImGui_ImplDX10_Init(ID3D10Device* device) { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx10"; - io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device IDXGIDevice* pDXGIDevice = NULL; diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index d7ddd8a6..685b83fc 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -11,7 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. +// 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. @@ -495,7 +495,7 @@ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_co { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx11"; - io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device IDXGIDevice* pDXGIDevice = NULL; diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 8831adb5..9bfa6a87 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -13,7 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. +// 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Various minor tidying up. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). @@ -607,7 +607,7 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx12"; - io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. g_pd3dDevice = device; g_RTVFormat = rtv_format; diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 886de1f6..9dc9d92f 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -11,7 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. +// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. @@ -220,7 +220,7 @@ bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx9"; - io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. g_pd3dDevice = device; g_pd3dDevice->AddRef(); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 06e9948c..152929cc 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,7 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. +// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. // 2019-03-15: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. @@ -124,6 +124,9 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_opengl3"; +#if IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. +#endif // Store GLSL version string so we can refer to it later in case we recreate shaders. Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure. #if defined(IMGUI_IMPL_OPENGL_ES2) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index ef6afcd2..0cd6a77d 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -22,7 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_HasVtxOffset flag. +// 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). // 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. @@ -805,7 +805,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_vulkan"; - io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. IM_ASSERT(info->Instance != VK_NULL_HANDLE); IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); diff --git a/imconfig.h b/imconfig.h index 5476dd66..6eaffd74 100644 --- a/imconfig.h +++ b/imconfig.h @@ -65,7 +65,7 @@ //---- Using 32-bits vertex indices (default is 16-bits) is one way to allow large meshes with more than 64K vertices. // Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bits indices). // Another way to allow large meshes while keeping 16-bits indices is to handle ImDrawCmd::VtxOffset in your renderer. -// Read about ImGuiBackendFlags_HasVtxOffset for details. +// Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. diff --git a/imgui.cpp b/imgui.cpp index 2b0cbf4f..33e53453 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3507,7 +3507,7 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; - if (g.IO.BackendFlags & ImGuiBackendFlags_HasVtxOffset) + if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; g.BackgroundDrawList.Clear(); @@ -3792,7 +3792,7 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds. // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents. // - If you want large meshes with more than 64K vertices, you can either: - // (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset'. + // (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. // Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't. // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them. // (B) Or handle 32-bits indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. diff --git a/imgui.h b/imgui.h index 4580a181..0cc13fbd 100644 --- a/imgui.h +++ b/imgui.h @@ -1003,10 +1003,10 @@ enum ImGuiConfigFlags_ enum ImGuiBackendFlags_ { ImGuiBackendFlags_None = 0, - ImGuiBackendFlags_HasGamepad = 1 << 0, // Platform Back-end supports gamepad and currently has one connected. - ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Platform Back-end supports honoring GetMouseCursor() value to change the OS cursor shape. - ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Platform Back-end supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). - ImGuiBackendFlags_HasVtxOffset = 1 << 3 // Renderer Back-end supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bits indices. + ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end Platform supports gamepad and currently has one connected. + ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Back-end Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). + ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3 // Back-end Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bits indices. }; // Enumeration for PushStyleColor() / PopStyleColor() @@ -1779,14 +1779,14 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) // Typically, 1 command = 1 GPU draw call (unless command is a callback) -// Pre 1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. When (io.BackendFlags & ImGuiBackendFlags_HasVtxOffset) +// Pre 1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' // is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bits indices. struct ImDrawCmd { unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. - unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_HasVtxOffset: always 0. With ImGuiBackendFlags_HasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bits indices. + unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bits indices. unsigned int IdxOffset; // Start offset in index buffer. Always equal to sum of ElemCount drawn so far. ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // The draw callback code can access this. @@ -1795,7 +1795,7 @@ struct ImDrawCmd }; // Vertex index -// (to allow large meshes with 16-bits indices: set 'io.BackendFlags |= ImGuiBackendFlags_HasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer back-end) +// (to allow large meshes with 16-bits indices: set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer back-end) // (to use 32-bits indices: override with '#define ImDrawIdx unsigned int' in imconfig.h) #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; @@ -1843,7 +1843,7 @@ enum ImDrawListFlags_ ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1, // Filled shapes have anti-aliased edges (*2 the number of vertices) - ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'io.BackendFlags & ImGuiBackendFlags_HasVtxOffset' is enabled. + ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; // Draw command list diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 82aa7431..b38fadc7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -350,7 +350,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasSetMousePos); - ImGui::CheckboxFlags("io.BackendFlags: HasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasVtxOffset); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); ImGui::TreePop(); ImGui::Separator(); } @@ -2863,7 +2863,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos"); - if (io.BackendFlags & ImGuiBackendFlags_HasVtxOffset) ImGui::Text(" HasVtxOffset"); + if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset"); ImGui::Separator(); ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight); ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y); From ed79b4d22ed2b2ef08ab41be918ad1851325d3d9 Mon Sep 17 00:00:00 2001 From: Max Thrun Date: Wed, 29 May 2019 10:35:41 -0700 Subject: [PATCH 389/566] Examples/Backends: Metal: Added support for large meshes (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_HasVtxOffset' config flag in back-end. (#2591, #2592) --- docs/CHANGELOG.txt | 2 +- examples/imgui_impl_metal.h | 1 + examples/imgui_impl_metal.mm | 11 ++++++----- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ef8e2310..010fc805 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,7 +71,7 @@ Other Changes: - Backends: Add native Mac clipboard copy/paste default implementation in core library to match what we are dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] -- Examples/Backends: DirectX9/10/11/12, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes +- Examples/Backends: DirectX9/10/11/12, Metal, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode diff --git a/examples/imgui_impl_metal.h b/examples/imgui_impl_metal.h index f6846851..869c3e52 100644 --- a/examples/imgui_impl_metal.h +++ b/examples/imgui_impl_metal.h @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index c4947893..f3f1b126 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -3,6 +3,7 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. +// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -10,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. @@ -76,6 +78,7 @@ bool ImGui_ImplMetal_Init(id device) { ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_metal"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ @@ -478,13 +481,10 @@ void ImGui_ImplMetal_DestroyDeviceObjects() for (int n = 0; n < drawData->CmdListsCount; n++) { const ImDrawList* cmd_list = drawData->CmdLists[n]; - ImDrawIdx idx_buffer_offset = 0; memcpy((char *)vertexBuffer.buffer.contents + vertexBufferOffset, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy((char *)indexBuffer.buffer.contents + indexBufferOffset, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); - [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0]; - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; @@ -522,14 +522,15 @@ void ImGui_ImplMetal_DestroyDeviceObjects() // Bind texture, Draw if (pcmd->TextureId != NULL) [commandEncoder setFragmentTexture:(__bridge id)(pcmd->TextureId) atIndex:0]; + + [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0]; [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:pcmd->ElemCount indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 indexBuffer:indexBuffer.buffer - indexBufferOffset:indexBufferOffset + idx_buffer_offset]; + indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)]; } } - idx_buffer_offset += pcmd->ElemCount * sizeof(ImDrawIdx); } vertexBufferOffset += cmd_list->VtxBuffer.Size * sizeof(ImDrawVert); From c3d600abed65952f19ae0519212a1255348883bb Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 30 May 2019 16:45:59 +0200 Subject: [PATCH 390/566] Fixed imgui_impl_opengl3 broken in previous few commits. (#2591, #2593, #2594) --- examples/imgui_impl_opengl3.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 152929cc..494fa07a 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -106,9 +106,9 @@ // Desktop GL has glDrawElementsBaseVertex() which GL ES and WebGL don't have. #if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) -#define IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX 1 -#else #define IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX 0 +#else +#define IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX 1 #endif // OpenGL Data @@ -312,9 +312,9 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); #if IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX - glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)pcmd->IdxOffset, (GLint)pcmd->VtxOffset); + glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset); #else - glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)pcmd->IdxOffset); + glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx))); #endif } } From 21ebdcafc957c431d6053e2d3f8680554b7e90b6 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 15:54:55 +0200 Subject: [PATCH 391/566] Internals: Window rectangles: Renaming of all rectangles toward their final form. Should be a no-op. Renamed GetWorkRectMax() to GetContentRegionMaxAbs(). Metrics shows SizeContents. --- imgui.cpp | 57 ++++++++++++++++++++++++----------------------- imgui_internal.h | 10 ++++----- imgui_widgets.cpp | 12 +++++----- 3 files changed, 40 insertions(+), 39 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 33e53453..bf738ff3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2997,7 +2997,7 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) ImGuiWindow* window = GImGui->CurrentWindow; if (wrap_pos_x == 0.0f) - wrap_pos_x = GetWorkRectMax().x; + wrap_pos_x = GetContentRegionMaxAbs().x; else if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space @@ -5517,10 +5517,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); - window->InnerVisibleRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; - window->InnerVisibleRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); - window->InnerVisibleRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); - window->InnerVisibleRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); + window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; + window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + window->InnerRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); + window->InnerRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); // Outer host rectangle for drawing background and borders ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; @@ -5532,12 +5532,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Inner work/clipping rectangle will extend a little bit outside the work region. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. - window->InnerWorkRect.Min.x = ImFloor(0.5f + window->InnerVisibleRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerWorkRect.Min.y = ImFloor(0.5f + window->InnerVisibleRect.Min.y); - window->InnerWorkRect.Max.x = ImFloor(0.5f + window->InnerVisibleRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->InnerWorkRect.Max.y = ImFloor(0.5f + window->InnerVisibleRect.Max.y); - window->InnerWorkRectClipped = window->InnerWorkRect; - window->InnerWorkRectClipped.ClipWithFull(host_rect); + window->WorkRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->WorkRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y); + window->WorkRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); + window->WorkRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y); + window->InnerClipRect = window->WorkRect; + window->InnerClipRect.ClipWithFull(host_rect); // DRAWING @@ -5662,7 +5662,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetCurrentWindow(window); } - PushClipRect(window->InnerWorkRectClipped.Min, window->InnerWorkRectClipped.Max, true); + PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) if (first_begin_of_the_frame) @@ -5905,7 +5905,7 @@ float ImGui::CalcItemWidth() w = window->DC.ItemWidth; if (w < 0.0f) { - float region_max_x = GetWorkRectMax().x; + float region_max_x = GetContentRegionMaxAbs().x; w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); } w = (float)(int)w; @@ -5922,7 +5922,7 @@ ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) ImVec2 region_max; if (size.x < 0.0f || size.y < 0.0f) - region_max = GetWorkRectMax(); + region_max = GetContentRegionMaxAbs(); if (size.x == 0.0f) size.x = default_w; @@ -6513,7 +6513,7 @@ ImVec2 ImGui::GetContentRegionMax() } // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. -ImVec2 ImGui::GetWorkRectMax() +ImVec2 ImGui::GetContentRegionMaxAbs() { ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max; @@ -6525,7 +6525,7 @@ ImVec2 ImGui::GetWorkRectMax() ImVec2 ImGui::GetContentRegionAvail() { ImGuiWindow* window = GImGui->CurrentWindow; - return GetWorkRectMax() - window->DC.CursorPos; + return GetContentRegionMaxAbs() - window->DC.CursorPos; } // In window space (not screen space!) @@ -7843,7 +7843,7 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput // NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated. static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) { - ImRect window_rect(window->InnerVisibleRect.Min - ImVec2(1, 1), window->InnerVisibleRect.Max + ImVec2(1, 1)); + ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] if (window_rect.Contains(item_rect)) return; @@ -8117,7 +8117,7 @@ static void ImGui::NavUpdate() if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0) { ImGuiWindow* window = g.NavWindow; - ImRect window_rect_rel(window->InnerVisibleRect.Min - window->Pos - ImVec2(1,1), window->InnerVisibleRect.Max - window->Pos + ImVec2(1,1)); + ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1)); if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { float pad = window->CalcFontSize() * 0.5f; @@ -8218,14 +8218,14 @@ static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) - SetWindowScrollY(window, window->Scroll.y - window->InnerVisibleRect.GetHeight()); + SetWindowScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) - SetWindowScrollY(window, window->Scroll.y + window->InnerVisibleRect.GetHeight()); + SetWindowScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); } else { const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; - const float page_offset_y = ImMax(0.0f, window->InnerVisibleRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); + const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); float nav_scoring_rect_offset_y = 0.0f; if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) { @@ -8701,7 +8701,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag window->DC.CurrentColumns = columns; // Set state for first column - const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerWorkRect.Max.x - window->Pos.x); + const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->WorkRect.Max.x - window->Pos.x); columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range columns->OffMaxX = ImMax(content_region_width - window->Scroll.x, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; @@ -9749,10 +9749,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; } - enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerVisibleRect, RT_InnerWorkRect, RT_InnerWorkRectClipped, RT_ContentsRegionRect, RT_ContentsFullRect }; + enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerRect, RT_InnerClipRect, RT_WorkRect, RT_Contents, RT_ContentsRegionRect }; static bool show_windows_begin_order = false; static bool show_windows_rects = false; - static int show_windows_rect_type = RT_InnerWorkRect; + static int show_windows_rect_type = RT_WorkRect; static bool show_drawcmd_clip_rects = true; ImGuiIO& io = ImGui::GetIO(); @@ -9769,9 +9769,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) { if (rect_type == RT_OuterRect) { return window->Rect(); } else if (rect_type == RT_OuterRectClipped) { return window->OuterRectClipped; } - else if (rect_type == RT_InnerVisibleRect) { return window->InnerVisibleRect; } - else if (rect_type == RT_InnerWorkRect) { return window->InnerWorkRect; } - else if (rect_type == RT_InnerWorkRectClipped) { return window->InnerWorkRectClipped; } + else if (rect_type == RT_InnerRect) { return window->InnerRect; } + else if (rect_type == RT_InnerClipRect) { return window->InnerClipRect; } + else if (rect_type == RT_WorkRect) { return window->WorkRect; } + else if (rect_type == RT_Contents) { return ImRect(window->Pos, window->Pos + window->SizeContents); } else if (rect_type == RT_ContentsRegionRect) { return window->ContentsRegionRect; } IM_ASSERT(0); return ImRect(); @@ -9979,7 +9980,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerVisibleRect\0" "InnerWorkRect\0" "InnerWorkRectClipped\0" "ContentsRegionRect\0"); + show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerRect\0" "InnerClipRect\0" "WorkRect\0" "Contents\0" "ContentsRegionRect\0"); if (show_windows_rects && g.NavWindow) { ImRect r = Funcs::GetRect(g.NavWindow, show_windows_rect_type); diff --git a/imgui_internal.h b/imgui_internal.h index 6d396460..0af4a5ed 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1297,9 +1297,9 @@ struct IMGUI_API ImGuiWindow ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack ImRect ClipRect; // Current clipping rectangle. = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. ImRect OuterRectClipped; // == WindowRect just after setup in Begin(). == window->Rect() for root window. - ImRect InnerVisibleRect; // Inner visible rectangle - ImRect InnerWorkRect; // == InnerMainRect minus WindowPadding.x - ImRect InnerWorkRectClipped; // == InnerMainRect minus WindowPadding.x, clipped within viewport or parent clip rect. + ImRect InnerRect; // Inner rectangle + ImRect InnerClipRect; // == InnerRect minus WindowPadding.x, clipped within viewport or parent clip rect. + ImRect WorkRect; // == InnerRect minus WindowPadding.x ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. Maximum visible content position ~~ Pos + (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis int LastFrameActive; // Last frame number the window was Active. float ItemWidthDefault; @@ -1501,8 +1501,8 @@ namespace ImGui IMGUI_API void PushMultiItemsWidths(int components, float width_full); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); - IMGUI_API bool IsItemToggledSelection(); // was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) - IMGUI_API ImVec2 GetWorkRectMax(); + IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) + IMGUI_API ImVec2 GetContentRegionMaxAbs(); IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); // Logging/Capture diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e806eec0..08c936fd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -888,14 +888,14 @@ void ImGui::Scrollbar(ImGuiAxis axis) ImRect bb; if (axis == ImGuiAxis_X) { - bb.Min = ImVec2(window->InnerVisibleRect.Min.x, window->InnerVisibleRect.Max.y); - bb.Max = ImVec2(window->InnerVisibleRect.Max.x, outer_rect.Max.y - window->WindowBorderSize); + bb.Min = ImVec2(window->InnerRect.Min.x, window->InnerRect.Max.y); + bb.Max = ImVec2(window->InnerRect.Max.x, outer_rect.Max.y - window->WindowBorderSize); rounding_corners |= ImDrawCornerFlags_BotLeft; } else { - bb.Min = ImVec2(window->InnerVisibleRect.Max.x, window->InnerVisibleRect.Min.y); - bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerVisibleRect.Max.y); + bb.Min = ImVec2(window->InnerRect.Max.x, window->InnerRect.Min.y); + bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerRect.Max.y); rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; } ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->SizeFull[axis] - other_scrollbar_size, window->SizeContents[axis], rounding_corners); @@ -5127,7 +5127,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // We vertically grow up to current line height up the typical widget height. const float text_base_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); - ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(GetWorkRectMax().x, window->DC.CursorPos.y + frame_height)); + ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(GetContentRegionMaxAbs().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding @@ -6281,7 +6281,7 @@ bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) ImGuiID id = window->GetID(str_id); ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); - ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->InnerWorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); + ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); tab_bar->ID = id; return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused); } From 546b728199f1b41d0bd0fa72e4efdbc7c6a524c8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 16:00:34 +0200 Subject: [PATCH 392/566] Internals: Window rectangles: Fixed ContentsRegion lag by moving back after Scrollbar, fixes b50c61c9. Shuffling setup order and added comments. --- imgui.cpp | 62 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bf738ff3..e42f3ae0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4996,6 +4996,8 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) } } +// Draw background and borders +// Draw and handle scrollbars void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size) { ImGuiContext& g = *GImGui; @@ -5503,39 +5505,46 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars. window->SizeFullAtLastBegin = window->SizeFull; - // UPDATE RECTANGLES + // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) + // Update various regions. Variables they depends on should be set above in this function. + // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. - // Update various regions. Variables they depends on are set above in this function. - // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. - // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out. - window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; - window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); - window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); - window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); + // Outer rectangle + // Not affected by window border size. Used by: + // - FindHoveredWindow() (w/ extra padding when border resize is enabled) + // - Begin() initial clipping rect for drawing window background and borders. + // - Begin() clipping whole child + ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; + window->OuterRectClipped = window->Rect(); + window->OuterRectClipped.ClipWith(host_rect); // Inner rectangle - // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame - // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + // Used by: + // - NavScrollToBringItemIntoView() + // - NavUpdatePageUpPageDown() + // - Scrollbar() const ImRect title_bar_rect = window->TitleBarRect(); window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); window->InnerRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); window->InnerRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); - // Outer host rectangle for drawing background and borders - ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; - - // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() - window->OuterRectClipped = window->Rect(); - window->OuterRectClipped.ClipWith(host_rect); - - // Inner work/clipping rectangle will extend a little bit outside the work region. - // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. - // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + // Work rectangle. + // Affected by window padding and border size. Used by: + // - Columns() for right-most edge + // - BeginTabBar() for right-most edge window->WorkRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->WorkRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y); window->WorkRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->WorkRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y); + + // Inner clipping rectangle. + // Will extend a little bit outside the normal work region. + // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. + // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + // Affected by window/frame border size. Used by: + // - Begin() initial clip rect window->InnerClipRect = window->WorkRect; window->InnerClipRect.ClipWithFull(host_rect); @@ -5582,6 +5591,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f); } + // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) + + // [LEGACY] Contents Region + // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out when we have both. + // Used by: + // - Mouse wheel scrolling + // - ... (many things) + window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; + window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); + window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); + // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; From 42c98c5eea852ef134df043f4cc525810c9076ee Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 30 May 2019 18:47:46 +0200 Subject: [PATCH 393/566] ImDrawList: Fix broken channel splitting (broken by d1e8b69) (#2591) --- imgui_draw.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 442c0e18..e4b906ff 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -568,7 +568,10 @@ void ImDrawList::ChannelsMerge() if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) CmdBuffer.pop_back(); - int new_cmd_buffer_count = 0, new_idx_buffer_count = 0; + // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. + int new_cmd_buffer_count = 0; + int new_idx_buffer_count = 0; + int idx_offset = CmdBuffer.back().IdxOffset + CmdBuffer.back().ElemCount; for (int i = 1; i < _ChannelsCount; i++) { ImDrawChannel& ch = _Channels[i]; @@ -576,10 +579,16 @@ void ImDrawList::ChannelsMerge() ch.CmdBuffer.pop_back(); new_cmd_buffer_count += ch.CmdBuffer.Size; new_idx_buffer_count += ch.IdxBuffer.Size; + for (int cmd_n = 0; cmd_n < ch.CmdBuffer.Size; cmd_n++) + { + ch.CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; + idx_offset += ch.CmdBuffer.Data[cmd_n].ElemCount; + } } CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); + // Flatten our N channels at the end of the first one. ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; for (int i = 1; i < _ChannelsCount; i++) From bff7202ff2ba78dbba59950c85b097c665729e9f Mon Sep 17 00:00:00 2001 From: Sebastian Krzyszkowiak Date: Fri, 31 May 2019 01:52:22 +0200 Subject: [PATCH 394/566] Include also when __SWITCH__ is defined (#2595) Fixes compilation with devkitPro for Nintendo Switch --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e4b906ff..5e968450 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -33,7 +33,7 @@ Index of this file: #include // vsnprintf, sscanf, printf #if !defined(alloca) -#if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) +#if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) || defined(__SWITCH__) #include // alloca (glibc uses . Note that Cygwin may have _WIN32 defined, so the order matters here) #elif defined(_WIN32) #include // alloca From 8abf1313aa627b8d4479c7854f649d05b7b0ba12 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 31 May 2019 11:35:42 +0200 Subject: [PATCH 395/566] ImDrawList: Fix broken channel splitting (another issue when the first channel is empty) (#2591) + fixed warnings with newer VS --- imgui_draw.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5e968450..79d26b67 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -47,6 +47,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 #endif @@ -565,13 +566,13 @@ void ImDrawList::ChannelsMerge() return; ChannelsSetCurrent(0); - if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) + if (CmdBuffer.Size != 0 && CmdBuffer.back().ElemCount == 0) CmdBuffer.pop_back(); // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; int new_idx_buffer_count = 0; - int idx_offset = CmdBuffer.back().IdxOffset + CmdBuffer.back().ElemCount; + int idx_offset = (CmdBuffer.Size != 0) ? (CmdBuffer.back().IdxOffset + CmdBuffer.back().ElemCount) : 0; for (int i = 1; i < _ChannelsCount; i++) { ImDrawChannel& ch = _Channels[i]; From f1f4b42d910eaa876231e0845af969e9c7daf311 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 31 May 2019 12:00:00 +0200 Subject: [PATCH 396/566] ImDrawListSplitter: extracted out of ImDrawList. Down the line we may obsolete the ImDrawList functions and encourage users to store the splitter aside, in the meanwhile ImDrawList holds a splitter. (This will allow columns/table to recurse.) --- imgui.h | 54 ++++++++----- imgui_draw.cpp | 215 ++++++++++++++++++++++++++----------------------- 2 files changed, 150 insertions(+), 119 deletions(-) diff --git a/imgui.h b/imgui.h index 0cc13fbd..c9cfcfec 100644 --- a/imgui.h +++ b/imgui.h @@ -20,7 +20,7 @@ Index of this file: // Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // Obsolete functions // Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) -// Draw List API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) +// Draw List API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) */ @@ -91,11 +91,12 @@ Index of this file: // Forward declarations and basic types //----------------------------------------------------------------------------- -struct ImDrawChannel; // Temporary storage for ImDrawList ot output draw commands out of order, used by ImDrawList::ChannelsSplit() +struct ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) struct ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) +struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader @@ -1760,7 +1761,7 @@ struct ImColor }; //----------------------------------------------------------------------------- -// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) +// Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- @@ -1817,12 +1818,27 @@ struct ImDrawVert IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif -// Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. -// You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. +// For use by ImDrawListSplitter. struct ImDrawChannel { - ImVector CmdBuffer; - ImVector IdxBuffer; + ImVector CmdBuffer; + ImVector IdxBuffer; +}; + +// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. +// This is used by the Columns api, so items of each column can be batched together in a same draw call. +struct ImDrawListSplitter +{ + int _Current; // Current channel number (0) + int _Count; // Number of active channels (1+) + ImVector _Channels; // Draw channels (not resized down so Count might be < Channels.Size) + + inline ImDrawListSplitter() { Clear(); } + inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame + IMGUI_API void ClearFreeMemory(); + IMGUI_API void Split(ImDrawList* draw_list, int count); + IMGUI_API void Merge(ImDrawList* draw_lists); + IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx); }; enum ImDrawCornerFlags_ @@ -1847,8 +1863,10 @@ enum ImDrawListFlags_ }; // 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. -// Each ImGui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to access the current window draw list and draw custom primitives. +// 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. +// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to +// access the current window draw list and draw custom primitives. // You can interleave normal ImGui:: calls and adding primitives to the current draw list. // All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), but you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well) // Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. @@ -1870,9 +1888,7 @@ struct ImDrawList ImVector _ClipRectStack; // [Internal] ImVector _TextureIdStack; // [Internal] ImVector _Path; // [Internal] current path building - int _ChannelsCurrent; // [Internal] current channel number (0) - int _ChannelsCount; // [Internal] number of active channels (1+) - ImVector _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) + ImDrawListSplitter _Splitter; // [Internal] for channels api // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); } @@ -1916,18 +1932,18 @@ struct ImDrawList IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); - // Channels - // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) - // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) - IMGUI_API void ChannelsSplit(int channels_count); - IMGUI_API void ChannelsMerge(); - IMGUI_API void ChannelsSetCurrent(int channel_index); - // Advanced IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. + // Advanced: Channels + // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) + inline void ChannelsSplit(int count) { _Splitter.Split(this, count); } + inline void ChannelsMerge() { _Splitter.Merge(this); } + inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } + // Internal helpers // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void Clear(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 79d26b67..f34b78ac 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -8,6 +8,7 @@ Index of this file: // [SECTION] STB libraries implementation // [SECTION] Style functions // [SECTION] ImDrawList +// [SECTION] ImDrawListSplitter // [SECTION] ImDrawData // [SECTION] Helpers ShadeVertsXXX functions // [SECTION] ImFontConfig @@ -372,9 +373,7 @@ void ImDrawList::Clear() _ClipRectStack.resize(0); _TextureIdStack.resize(0); _Path.resize(0); - _ChannelsCurrent = 0; - _ChannelsCount = 1; - // NB: Do not clear channels so our allocations are re-used after the first frame. + _Splitter.Clear(); } void ImDrawList::ClearFreeMemory() @@ -388,15 +387,7 @@ void ImDrawList::ClearFreeMemory() _ClipRectStack.clear(); _TextureIdStack.clear(); _Path.clear(); - _ChannelsCurrent = 0; - _ChannelsCount = 1; - for (int i = 0; i < _Channels.Size; i++) - { - if (i == 0) memset(&_Channels[0], 0, sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again - _Channels[i].CmdBuffer.clear(); - _Channels[i].IdxBuffer.clear(); - } - _Channels.clear(); + _Splitter.ClearFreeMemory(); } ImDrawList* ImDrawList::CloneOutput() const @@ -526,94 +517,6 @@ void ImDrawList::PopTextureID() UpdateTextureID(); } -void ImDrawList::ChannelsSplit(int channels_count) -{ - IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1); - int old_channels_count = _Channels.Size; - if (old_channels_count < channels_count) - _Channels.resize(channels_count); - _ChannelsCount = channels_count; - - // _Channels[] (24/32 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer - // The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. - // When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer - memset(&_Channels[0], 0, sizeof(ImDrawChannel)); - for (int i = 1; i < channels_count; i++) - { - if (i >= old_channels_count) - { - IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); - } - else - { - _Channels[i].CmdBuffer.resize(0); - _Channels[i].IdxBuffer.resize(0); - } - if (_Channels[i].CmdBuffer.Size == 0) - { - ImDrawCmd draw_cmd; - draw_cmd.ClipRect = _ClipRectStack.back(); - draw_cmd.TextureId = _TextureIdStack.back(); - _Channels[i].CmdBuffer.push_back(draw_cmd); - } - } -} - -void ImDrawList::ChannelsMerge() -{ - // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. - if (_ChannelsCount <= 1) - return; - - ChannelsSetCurrent(0); - if (CmdBuffer.Size != 0 && CmdBuffer.back().ElemCount == 0) - CmdBuffer.pop_back(); - - // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. - int new_cmd_buffer_count = 0; - int new_idx_buffer_count = 0; - int idx_offset = (CmdBuffer.Size != 0) ? (CmdBuffer.back().IdxOffset + CmdBuffer.back().ElemCount) : 0; - for (int i = 1; i < _ChannelsCount; i++) - { - ImDrawChannel& ch = _Channels[i]; - if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) - ch.CmdBuffer.pop_back(); - new_cmd_buffer_count += ch.CmdBuffer.Size; - new_idx_buffer_count += ch.IdxBuffer.Size; - for (int cmd_n = 0; cmd_n < ch.CmdBuffer.Size; cmd_n++) - { - ch.CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; - idx_offset += ch.CmdBuffer.Data[cmd_n].ElemCount; - } - } - CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); - IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); - - // Flatten our N channels at the end of the first one. - ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; - _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; - for (int i = 1; i < _ChannelsCount; i++) - { - ImDrawChannel& ch = _Channels[i]; - if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } - if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; } - } - UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. - _ChannelsCount = 1; -} - -void ImDrawList::ChannelsSetCurrent(int idx) -{ - IM_ASSERT(idx < _ChannelsCount); - if (_ChannelsCurrent == idx) return; - memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times - memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer)); - _ChannelsCurrent = idx; - memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer)); - memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer)); - _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size; -} - // NB: this can be called with negative count for removing primitives (as long as the result does not underflow) void ImDrawList::PrimReserve(int idx_count, int vtx_count) { @@ -1287,6 +1190,118 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, c PopTextureID(); } + +//----------------------------------------------------------------------------- +// ImDrawListSplitter +//----------------------------------------------------------------------------- +// FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. +//----------------------------------------------------------------------------- + +void ImDrawListSplitter::ClearFreeMemory() +{ + for (int i = 0; i < _Channels.Size; i++) + { + if (i == _Current) + memset(&_Channels[i], 0, sizeof(_Channels[i])); // Current channel is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i].CmdBuffer.clear(); + _Channels[i].IdxBuffer.clear(); + } + _Current = 0; + _Count = 1; + _Channels.clear(); +} + +void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) +{ + IM_ASSERT(_Current == 0 && _Count == 1); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + _Channels.resize(channels_count); + _Count = channels_count; + + // Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer + // The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy draw_list->_CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list->CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); + } + else + { + _Channels[i].CmdBuffer.resize(0); + _Channels[i].IdxBuffer.resize(0); + } + if (_Channels[i].CmdBuffer.Size == 0) + { + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); + draw_cmd.TextureId = draw_list->_TextureIdStack.back(); + _Channels[i].CmdBuffer.push_back(draw_cmd); + } + } +} + +void ImDrawListSplitter::Merge(ImDrawList* draw_list) +{ + // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_Count <= 1) + return; + + SetCurrentChannel(draw_list, 0); + if (draw_list->CmdBuffer.Size != 0 && draw_list->CmdBuffer.back().ElemCount == 0) + draw_list->CmdBuffer.pop_back(); + + // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. + int new_cmd_buffer_count = 0; + int new_idx_buffer_count = 0; + int idx_offset = (draw_list->CmdBuffer.Size != 0) ? (draw_list->CmdBuffer.back().IdxOffset + draw_list->CmdBuffer.back().ElemCount) : 0; + for (int i = 1; i < _Count; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) + ch.CmdBuffer.pop_back(); + new_cmd_buffer_count += ch.CmdBuffer.Size; + new_idx_buffer_count += ch.IdxBuffer.Size; + for (int cmd_n = 0; cmd_n < ch.CmdBuffer.Size; cmd_n++) + { + ch.CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; + idx_offset += ch.CmdBuffer.Data[cmd_n].ElemCount; + } + } + draw_list->CmdBuffer.resize(draw_list->CmdBuffer.Size + new_cmd_buffer_count); + draw_list->IdxBuffer.resize(draw_list->IdxBuffer.Size + new_idx_buffer_count); + + // Write commands and indices in order (they are fairly small structures, we don't copy vertices only indices) + ImDrawCmd* cmd_write = draw_list->CmdBuffer.Data + draw_list->CmdBuffer.Size - new_cmd_buffer_count; + ImDrawIdx* idx_write = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _Count; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch.IdxBuffer.Size) { memcpy(idx_write, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } + } + draw_list->_IdxWritePtr = idx_write; + draw_list->UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. + _Count = 1; +} + +void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) +{ + IM_ASSERT(idx < _Count); + if (_Current == idx) + return; + // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap() + memcpy(&_Channels.Data[_Current].CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&_Channels.Data[_Current].IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); + _Current = idx; + memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx].CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx].IdxBuffer, sizeof(draw_list->IdxBuffer)); + draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size; +} + //----------------------------------------------------------------------------- // [SECTION] ImDrawData //----------------------------------------------------------------------------- From cef88f6aae52bf0e9e558ea5e30eca95676f439b Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 May 2019 18:50:59 +0200 Subject: [PATCH 397/566] ImDrawListSplitter: Support merging consecutive draw commands straddling two channels. Support zero-init. --- imgui_draw.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f34b78ac..3f6b49a2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1213,7 +1213,7 @@ void ImDrawListSplitter::ClearFreeMemory() void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) { - IM_ASSERT(_Current == 0 && _Count == 1); + IM_ASSERT(_Current == 0 && _Count <= 1); int old_channels_count = _Channels.Size; if (old_channels_count < channels_count) _Channels.resize(channels_count); @@ -1244,6 +1244,11 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) } } +static inline bool CanMergeDrawCommands(ImDrawCmd* a, ImDrawCmd* b) +{ + return memcmp(&a->ClipRect, &b->ClipRect, sizeof(a->ClipRect)) == 0 && a->TextureId == b->TextureId && !a->UserCallback && !b->UserCallback; +} + void ImDrawListSplitter::Merge(ImDrawList* draw_list) { // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. @@ -1257,12 +1262,21 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; int new_idx_buffer_count = 0; - int idx_offset = (draw_list->CmdBuffer.Size != 0) ? (draw_list->CmdBuffer.back().IdxOffset + draw_list->CmdBuffer.back().ElemCount) : 0; + ImDrawCmd* last_cmd = (_Count > 0 && _Channels[0].CmdBuffer.Size > 0) ? &_Channels[0].CmdBuffer.back() : NULL; + int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0; for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) ch.CmdBuffer.pop_back(); + else if (ch.CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch.CmdBuffer[0])) + { + // Merge previous channel last draw command with current channel first draw command if matching. + last_cmd->ElemCount += ch.CmdBuffer[0].ElemCount; + ch.CmdBuffer.erase(ch.CmdBuffer.Data); + } + if (ch.CmdBuffer.Size > 0) + last_cmd = &ch.CmdBuffer.back(); new_cmd_buffer_count += ch.CmdBuffer.Size; new_idx_buffer_count += ch.IdxBuffer.Size; for (int cmd_n = 0; cmd_n < ch.CmdBuffer.Size; cmd_n++) From eb7849b477ff96d8d0cc9f2f4a304b5fc0f3ac1a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 31 May 2019 20:48:52 +0200 Subject: [PATCH 398/566] Nav: Fixed gamepad/keyboard moving of window affecting contents size incorrectly, sometimes leading to scrollbars appearing during the movement. + minor fix with the mostly dead Ctrl+wheel scaling. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 6 +++--- imgui_internal.h | 6 +++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 010fc805..83af7f48 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,8 @@ Other Changes: options. (#2587, broken in 1.69 by #2384). - CollapsingHeader: Better clipping when a close button is enabled and it overlaps the label. (#600) - Scrollbar: Very minor bounding box adjustment to cope with various border size. +- Nav: Fixed gamepad/keyboard moving of window affecting contents size incorrectly, sometimes leading + to scrollbars appearing during the movement. - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. - Style: Made window close button cross slightly smaller. diff --git a/imgui.cpp b/imgui.cpp index e42f3ae0..1be33f96 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3330,7 +3330,7 @@ void ImGui::UpdateMouseWheel() // Zoom / Scale window // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. - if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) + if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling && !window->Collapsed) { const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); const float scale = new_font_scale / window->FontWindowScale; @@ -3338,7 +3338,7 @@ void ImGui::UpdateMouseWheel() if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) { const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; - window->Pos = ImFloor(window->Pos + offset); + SetWindowPos(window, window->Pos + offset, 0); window->Size = ImFloor(window->Size * scale); window->SizeFull = ImFloor(window->SizeFull * scale); } @@ -8398,7 +8398,7 @@ static void ImGui::NavUpdateWindowing() { const float NAV_MOVE_SPEED = 800.0f; const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well - g.NavWindowingTarget->RootWindow->Pos += move_delta * move_speed; + SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always); g.NavDisableMouseHover = true; MarkIniSettingsDirty(g.NavWindowingTarget); } diff --git a/imgui_internal.h b/imgui_internal.h index 0af4a5ed..2ad53b24 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1450,9 +1450,9 @@ namespace ImGui IMGUI_API float GetWindowScrollMaxX(ImGuiWindow* window); IMGUI_API float GetWindowScrollMaxY(ImGuiWindow* window); IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); - IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond); - IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond); - IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond); + IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); + IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); + IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); IMGUI_API void SetCurrentFont(ImFont* font); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } From 6614bab883268778db8490f1282d7cfb8fdac1bf Mon Sep 17 00:00:00 2001 From: DucaRii <24766710+DucaRii@users.noreply.github.com> Date: Tue, 4 Jun 2019 16:37:45 +0200 Subject: [PATCH 399/566] Combo: Fixed rounding not applying with the ImGuiComboFlags_NoArrowButton flag. (#2606, #2607) --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 83af7f48..8a38612e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,7 @@ Other Changes: options. (#2587, broken in 1.69 by #2384). - CollapsingHeader: Better clipping when a close button is enabled and it overlaps the label. (#600) - Scrollbar: Very minor bounding box adjustment to cope with various border size. +- Combo: Fixed rounding not applying with the ImGuiComboFlags_NoArrowButton flag. (#2607) [@DucaRii] - Nav: Fixed gamepad/keyboard moving of window affecting contents size incorrectly, sometimes leading to scrollbars appearing during the movement. - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 08c936fd..24c7b3e3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1411,7 +1411,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const float value_x2 = ImMax(frame_bb.Min.x, frame_bb.Max.x - arrow_size); RenderNavHighlight(frame_bb, id); if (!(flags & ImGuiComboFlags_NoPreview)) - window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(value_x2, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left); + window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(value_x2, frame_bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Left); if (!(flags & ImGuiComboFlags_NoArrowButton)) { window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); From 57d8ab62f4c0c28e24b099c61ebee911b1aa7e7e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Jun 2019 00:25:21 +0200 Subject: [PATCH 400/566] Nav: Fixed rare crash when e.g. releasing Alt-key while focusing a window with a menu at the same frame as clearing the focus. This was in most noticeable in some back-ends with emits key release events when focusing another viewport. (#2609) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8a38612e..09152b43 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,10 @@ Other Changes: - Combo: Fixed rounding not applying with the ImGuiComboFlags_NoArrowButton flag. (#2607) [@DucaRii] - Nav: Fixed gamepad/keyboard moving of window affecting contents size incorrectly, sometimes leading to scrollbars appearing during the movement. +- Nav: Fixed rare crash when e.g. releasing Alt-key while focusing a window with a menu at the same + frame as clearing the focus. This was in most noticeable in back-ends such as Glfw and SDL which + emits key release events when focusing another viewport, leading to Alt+clicking on void on another + viewport triggering the issue. (#2609) - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. - Style: Made window close button cross slightly smaller. diff --git a/imgui.cpp b/imgui.cpp index 1be33f96..99fb8c2e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7933,10 +7933,10 @@ static void ImGui::NavUpdate() g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Process navigation init request (select first/default focus) - if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove)) + // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) + if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow) { // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) - IM_ASSERT(g.NavWindow); if (g.NavInitRequestFromMove) SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel); else From 5cdd788f30d12b1abc5f2464135ea70eed87e77a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 31 May 2019 23:54:15 +0200 Subject: [PATCH 401/566] Comments (#2599). Moved branch Changelog above 1.71 wip one. Added some missing changelog bits. --- docs/CHANGELOG.txt | 105 ++++++++++++++++++++++++--------------------- imgui.cpp | 1 + imgui.h | 8 ++-- imgui_demo.cpp | 8 +++- 4 files changed, 67 insertions(+), 55 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1e05b3b0..12136481 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -28,55 +28,6 @@ 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.71 (In Progress) ------------------------------------------------------------------------ - -Breaking Changes: -- IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). -- Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). - -Other Changes: -- Columns: Fixed Separator from creating an extraneous draw command. (#125) -- Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) -- Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect - but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. -- Fixed InputScalar, InputScalarN, SliderScalarN, DragScalarN with non-visible label from inserting - style.ItemInnerSpacing.x worth of trailing spacing. -- Fixed InputFloatX, SliderFloatX, DragFloatX functions erroneously reporting IsItemEdited() multiple - times when the text input doesn't match the formatted output value (e.g. input "1" shows "1.000"). - It wasn't much of a problem because we typically use the return value instead of IsItemEdited() here. -- Fixed uses of IsItemDeactivated(), IsItemDeactivatedAfterEdit() on multi-components widgets and - after EndGroup(). (#2550, #1875) -- Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) -- ColorEdit: Fixed the color picker popup only displaying inputs as HSV instead of showing multiple - options. (#2587, broken in 1.69 by #2384). -- CollapsingHeader: Better clipping when a close button is enabled and it overlaps the label. (#600) -- Scrollbar: Very minor bounding box adjustment to cope with various border size. -- Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the - collapsing/docking button to the other side of the title bar. -- Style: Made window close button cross slightly smaller. -- ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bits indices. - The renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' to enable - this, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. - This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not - support 32-bits indices. Most examples back-ends have been modified to support the VtxOffset field. -- ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. - This is provided for convenience and consistency with VtxOffset. -- ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) - Combine with RasterizerFlags::MonoHinting for best results. -- ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not - fully cleared. Fixed edge-case overflow when adding character 0xFFFF. (#2568). [@NIKE3500] -- Demo: Added full "Dear ImGui" prefix to the title of "Dear ImGui Demo" and "Dear ImGui Metrics" windows. -- Backends: Add native Mac clipboard copy/paste default implementation in core library to match what we are - dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] -- Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] -- Examples/Backends: DirectX9/10/11/12, Metal, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes - (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. -- Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), - the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode - support. (#2538, #2541) - ----------------------------------------------------------------------- DOCKING BRANCH (In Progress) @@ -93,7 +44,10 @@ DOCKING FEATURES - Added GetWindowDockId(), IsWindowDocked() API. - Added ImGuiWindowFlags_NoDocking window flag to disable the possibility for a window to be docked. Popup, Menu and Child windows always have the ImGuiWindowFlags_NoDocking flag set. - - Added io.ConfigDockingWithShift option to configure docking mode. + - Added io.ConfigDockingNoSplit option. + - Added io.ConfigDockingWithShift option. + - Added io.ConfigDockingTabBarOnSingleWindows option. + - Added io.ConfigDockingTransparentPayload option. - Style: Added ImGuiCol_DockingPreview, ImGuiCol_DockingEmptyBg colors. - Demo: Added "DockSpace" example app showcasing use of explicit dockspace nodes. @@ -129,6 +83,7 @@ Other changes: - Added UpdatePlatformWindows(), RenderPlatformWindows(), DestroyPlatformWindows() for usage for application core. - Added FindViewportByID(), FindViewportByPlatformHandle() for usage by back-ends. - Added ImGuiConfigFlags_ViewportsEnable configuration flag and other viewport options. +- Added io.ConfigViewportsNoAutoMerge, io.ConfigViewportsNoTaskBarIcon, io.ConfigViewportsNoDecoration, io.ConfigViewportsNoDefaultParent options. - Added ImGuiBackendFlags_PlatformHasViewports, ImGuiBackendFlags_RendererHasViewports, ImGuiBackendFlags_HasMouseHoveredViewport backend flags. - Added io.MainViewport, io.Viewports, io.MouseHoveredViewport (MouseHoveredViewport is optional _even_ for multi-viewport support). - Added ImGuiViewport structure, ImGuiViewportFlags flags. @@ -142,6 +97,56 @@ Other changes: to make the examples main.cpp easier to read. +----------------------------------------------------------------------- + VERSION 1.71 (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: +- IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). +- Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). + +Other Changes: +- Columns: Fixed Separator from creating an extraneous draw command. (#125) +- Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) +- Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect + but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. +- Fixed InputScalar, InputScalarN, SliderScalarN, DragScalarN with non-visible label from inserting + style.ItemInnerSpacing.x worth of trailing spacing. +- Fixed InputFloatX, SliderFloatX, DragFloatX functions erroneously reporting IsItemEdited() multiple + times when the text input doesn't match the formatted output value (e.g. input "1" shows "1.000"). + It wasn't much of a problem because we typically use the return value instead of IsItemEdited() here. +- Fixed uses of IsItemDeactivated(), IsItemDeactivatedAfterEdit() on multi-components widgets and + after EndGroup(). (#2550, #1875) +- Fixed crash when appending with BeginMainMenuBar() more than once and no other window are showing. (#2567) +- ColorEdit: Fixed the color picker popup only displaying inputs as HSV instead of showing multiple + options. (#2587, broken in 1.69 by #2384). +- CollapsingHeader: Better clipping when a close button is enabled and it overlaps the label. (#600) +- Scrollbar: Very minor bounding box adjustment to cope with various border size. +- Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the + collapsing/docking button to the other side of the title bar. +- Style: Made window close button cross slightly smaller. +- ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bits indices. + The renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' to enable + this, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. + This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not + support 32-bits indices. Most examples back-ends have been modified to support the VtxOffset field. +- ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. + This is provided for convenience and consistency with VtxOffset. +- ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) + Combine with RasterizerFlags::MonoHinting for best results. +- ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not + fully cleared. Fixed edge-case overflow when adding character 0xFFFF. (#2568). [@NIKE3500] +- Demo: Added full "Dear ImGui" prefix to the title of "Dear ImGui Demo" and "Dear ImGui Metrics" windows. +- Backends: Add native Mac clipboard copy/paste default implementation in core library to match what we are + dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] +- Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] +- Examples/Backends: DirectX9/10/11/12, Metal, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes + (64k+ vertices) with 16-bits indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. +- Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), + the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode + support. (#2538, #2541) + + ----------------------------------------------------------------------- VERSION 1.70 (Released 2019-05-06) ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index ea1347a7..5ba7e30a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5768,6 +5768,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) flags = window->Flags; // Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies) + // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. if (flags & ImGuiWindowFlags_ChildWindow) window->WindowBorderSize = style.ChildBorderSize; else diff --git a/imgui.h b/imgui.h index f46372c0..03b66663 100644 --- a/imgui.h +++ b/imgui.h @@ -597,9 +597,9 @@ namespace ImGui // Docking // [BETA API] Enable with io.ConfigFlags |= ImGuiConfigFlags_DockingEnable. // Note: you DO NOT need to call DockSpace() to use most Docking facilities! - // To dock windows: if io.ConfigDockingWithShift == false: drag window from their title bar. - // To dock windows: if io.ConfigDockingWithShift == true: hold SHIFT anywhere while moving windows. - // Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details. + // - To dock windows: if io.ConfigDockingWithShift == false (default) drag window from their title bar. + // - To dock windows: if io.ConfigDockingWithShift == true: hold SHIFT anywhere while moving windows. + // - Use DockSpace() to create an explicit dock node _within_ an existing window. See Docking demo for details. IMGUI_API void DockSpace(ImGuiID id, const ImVec2& size = ImVec2(0, 0), ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); IMGUI_API ImGuiID DockSpaceOverViewport(ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, const ImGuiWindowClass* window_class = NULL); IMGUI_API void SetNextWindowDockID(ImGuiID dock_id, ImGuiCond cond = 0); // set next window dock id (FIXME-DOCK) @@ -1052,7 +1052,7 @@ enum ImGuiConfigFlags_ ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. // [BETA] Docking - ImGuiConfigFlags_DockingEnable = 1 << 6, // Docking enable flags. Use SHIFT to dock window into another (or without SHIFT if io.ConfigDockingWithShift = false). + ImGuiConfigFlags_DockingEnable = 1 << 6, // Docking enable flags. // [BETA] Viewports // When using viewports it is recommended that your default value for ImGuiCol_WindowBg is opaque (Alpha=1.0) so transition to a viewport won't be noticeable. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 267439dc..11ae1952 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4326,7 +4326,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) //----------------------------------------------------------------------------- // Demonstrate using DockSpace() to create an explicit docking node within an existing window. -// Note that you already dock windows into each others _without_ a DockSpace() by just holding SHIFT when moving a window. +// Note that you already dock windows into each others _without_ a DockSpace() by just moving windows +// from their title bar (or by holding SHIFT if io.ConfigDockingWithShift is set). // DockSpace() is only useful to construct to a central location for your application. void ShowExampleAppDockSpace(bool* p_open) { @@ -4353,6 +4354,11 @@ void ShowExampleAppDockSpace(bool* p_open) if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) window_flags |= ImGuiWindowFlags_NoBackground; + // Important: note that we proceed even if Begin() returns false (aka window is collapsed). + // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, + // all active windows docked into it will lose their parent and become undocked. + // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise + // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", p_open, window_flags); ImGui::PopStyleVar(); From b9874a24233bdc8b7a25c6107a6ae9bffea3477e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Jun 2019 12:05:53 +0200 Subject: [PATCH 402/566] Comments about obsoleted features version. Todo. Clarify tab bar initial offset (useful if we decide to remove the half-windowpadding clip margin). --- docs/TODO.txt | 2 ++ imgui.h | 20 ++++++++++---------- imgui_widgets.cpp | 7 ++++--- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index f32c944d..e6e119f1 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -69,6 +69,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - widgets: checkbox: checkbox with custom glyph inside frame. - widgets: coloredit: keep reporting as active when picker is on? + - widgets: group/scalarn functions: expose more per-component information. e.g. store NextItemData.ComponentIdx set by scalarn function, groups can expose them back somehow. - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) @@ -231,6 +232,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc. - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation). - style: global scale setting. + - style: FramePadding could be different for up vs down (#584) - style: WindowPadding needs to be EVEN as the 0.5 multiplier used on this value probably have a subtle effect on clip rectangle - style: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438, #707, #1223) - style: gradients fill (#1223) ~ 2 bg colors for each fill? tricky with rounded shapes and using textures for corners. diff --git a/imgui.h b/imgui.h index c9cfcfec..b865679e 100644 --- a/imgui.h +++ b/imgui.h @@ -790,7 +790,7 @@ enum ImGuiTreeNodeFlags_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap + , ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap // [renamed in 1.53] #endif }; @@ -801,7 +801,7 @@ enum ImGuiSelectableFlags_ ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too - ImGuiSelectableFlags_Disabled = 1 << 3 // Cannot be selected, display greyed out text + ImGuiSelectableFlags_Disabled = 1 << 3 // Cannot be selected, display grayed out text }; // Flags for ImGui::BeginCombo() @@ -1106,7 +1106,8 @@ enum ImGuiStyleVar_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT, ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding + , ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT // [renamed in 1.60] + , ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding // [renamed in 1.53] #endif }; @@ -1151,7 +1152,7 @@ enum ImGuiColorEditFlags_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex + , ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] #endif }; @@ -1172,7 +1173,7 @@ enum ImGuiMouseCursor_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT + , ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT // [renamed in 1.60] #endif }; @@ -1188,7 +1189,7 @@ enum ImGuiCond_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing + , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing // [renamed in 1.51] #endif }; @@ -1535,7 +1536,6 @@ namespace ImGui { // OBSOLETED in 1.71 (from May 2019) static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } - // OBSOLETED in 1.70 (from May 2019) static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.69 (from Mar 2019) @@ -1570,7 +1570,7 @@ namespace ImGui static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } } -typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETE in 1.63 (from Aug 2018): made the names consistent +typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; #endif @@ -2153,7 +2153,7 @@ struct ImFontAtlas int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETE 1.67+ + typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ #endif }; @@ -2207,7 +2207,7 @@ struct ImFont IMGUI_API void SetFallbackChar(ImWchar c); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - typedef ImFontGlyph Glyph; // OBSOLETE 1.52+ + typedef ImFontGlyph Glyph; // OBSOLETED in 1.52+ #endif }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 24c7b3e3..aedaa0ef 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6460,7 +6460,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) } // Compute width - const float width_avail = tab_bar->BarRect.GetWidth(); + const float initial_offset_x = 0.0f; // g.Style.ItemInnerSpacing.x; + const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - initial_offset_x, 0.0f); float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f; if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown)) { @@ -6480,7 +6481,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) } // Layout all active tabs - float offset_x = 0.0f; + float offset_x = initial_offset_x; + tab_bar->OffsetNextTab = offset_x; // This is used by non-reorderable tab bar where the submission order is always honored. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; @@ -6490,7 +6492,6 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) offset_x += tab->Width + g.Style.ItemInnerSpacing.x; } tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); - tab_bar->OffsetNextTab = 0.0f; // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); From 09bcf9fbc54e751aed79ca908811eef4f2b1d700 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 16:18:30 +0200 Subject: [PATCH 403/566] Window rectangles: Made InnerRect not affected by window border sizes. its few users shouldn't be meaningfully affected. --- imgui.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 99fb8c2e..652651ab 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5519,15 +5519,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->OuterRectClipped.ClipWith(host_rect); // Inner rectangle - // Used by: + // Not affected by window border size. Used by: // - NavScrollToBringItemIntoView() // - NavUpdatePageUpPageDown() // - Scrollbar() const ImRect title_bar_rect = window->TitleBarRect(); - window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; - window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); - window->InnerRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); - window->InnerRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); + window->InnerRect.Min.x = title_bar_rect.Min.x; + window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight(); + window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x; + window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y; // Work rectangle. // Affected by window padding and border size. Used by: From a0994d74c256aaa582149a174385d2257a55728f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Jun 2019 15:35:55 +0200 Subject: [PATCH 404/566] Clarified behavior of SetNextWindowContentSize(). Content size is defined as the size available after removal of WindowPadding on each sides. So SetNextWindowContentSize(ImVec2(100,100)) + auto-resize will always allow submitting a 100x100 item without creating a scrollbar, regarding of WindowPadding.The exact meaning of ContentSize for decorated windows was previously ill-defined. --- docs/CHANGELOG.txt | 4 +++ imgui.cpp | 82 ++++++++++++++++++++++------------------------ imgui.h | 2 +- imgui_internal.h | 5 ++- imgui_widgets.cpp | 2 +- 5 files changed, 47 insertions(+), 48 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 09152b43..c0929a07 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,10 @@ Breaking Changes: - Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). Other Changes: +- Window: clarified behavior of SetNextWindowContentSize(). Content size is defined as the size available + after removal of WindowPadding on each sides. So SetNextWindowContentSize(ImVec2(100,100)) + auto-resize + will always allow submitting a 100x100 item without creating a scrollbar, regarding of WindowPadding. + The exact meaning of ContentSize for decorated windows was previously ill-defined. - Columns: Fixed Separator from creating an extraneous draw command. (#125) - Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect diff --git a/imgui.cpp b/imgui.cpp index 652651ab..09a81fa9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4637,8 +4637,8 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl if (ImLengthSqr(settings->Size) > 0.00001f) size = ImFloor(settings->Size); } - window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size); - window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values + window->Size = window->SizeFull = ImFloor(size); + window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { @@ -4703,19 +4703,22 @@ static ImVec2 CalcSizeContents(ImGuiWindow* window) return window->SizeContents; ImVec2 sz; - sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x)); - sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y)); - return sz + window->WindowPadding; + sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); + sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); + return sz; } static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; + ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight()); + ImVec2 size_pad = window->WindowPadding * 2.0f; + ImVec2 size_desired = size_contents + size_pad + size_decorations; if (window->Flags & ImGuiWindowFlags_Tooltip) { // Tooltip always resize - return size_contents; + return size_desired; } else { @@ -4725,14 +4728,14 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) ImVec2 size_min = style.WindowMinSize; if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) size_min = ImMin(size_min, ImVec2(4.0f, 4.0f)); - ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f)); + ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f)); // When the window cannot fit all contents (either because of constraints, either because screen is too small), // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit); - if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) + if (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) size_auto_fit.y += style.ScrollbarSize; - if (size_auto_fit_after_constraint.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) + if (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) size_auto_fit.x += style.ScrollbarSize; return size_auto_fit; } @@ -4746,12 +4749,12 @@ ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) float ImGui::GetWindowScrollMaxX(ImGuiWindow* window) { - return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x)); + return ImMax(0.0f, window->SizeContents.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); } float ImGui::GetWindowScrollMaxY(ImGuiWindow* window) { - return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y)); + return ImMax(0.0f, window->SizeContents.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); } static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) @@ -4761,7 +4764,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s if (window->ScrollTarget.x < FLT_MAX) { float cr_x = window->ScrollTargetCenterRatio.x; - scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x); + scroll.x = window->ScrollTarget.x - cr_x * window->InnerRect.GetWidth(); } if (window->ScrollTarget.y < FLT_MAX) { @@ -4770,9 +4773,9 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s float target_y = window->ScrollTarget.y; if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) target_y = 0.0f; - if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y - window->WindowPadding.y + g.Style.ItemSpacing.y) - target_y = window->SizeContents.y; - scroll.y = target_y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y); + if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y + window->WindowPadding.y + g.Style.ItemSpacing.y) + target_y = window->SizeContents.y + window->WindowPadding.y * 2.0f; + scroll.y = target_y - cr_y * window->InnerRect.GetHeight(); } scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) @@ -5280,16 +5283,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); } if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize) - { - // Adjust passed "client size" to become a "window size" window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal; - if (window->SizeContentsExplicit.y != 0.0f) - window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight(); - } else if (first_begin_of_the_frame) - { window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); - } if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed) SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus) @@ -5349,9 +5345,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } } + // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style) SetCurrentWindow(window); - // Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies) + // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) + if (flags & ImGuiWindowFlags_ChildWindow) window->WindowBorderSize = style.ChildBorderSize; else @@ -5417,13 +5415,14 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size). if (!window->Collapsed) { - // When reading the current size we need to read it after size constraints have been applied - float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x; - float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y; - window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); - window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + // When reading the current size we need to read it after size constraints have been applied. + // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. + float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->InnerRect.GetWidth() + window->ScrollbarSizes.x; + float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y - window->TitleBarHeight() - window->MenuBarHeight() : window->InnerRect.GetHeight() + window->ScrollbarSizes.y; + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x + window->WindowPadding.x * 2.0f > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); if (window->ScrollbarX && !window->ScrollbarY) - window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar); + window->ScrollbarY = (window->SizeContents.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); } @@ -5502,9 +5501,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) else window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); - // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars. - window->SizeFullAtLastBegin = window->SizeFull; - // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) // Update various regions. Variables they depends on should be set above in this function. // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. @@ -6325,16 +6321,12 @@ ImVec2 ImGui::GetWindowPos() void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x) { - window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. window->Scroll.x = new_scroll_x; - window->DC.CursorMaxPos.x -= window->Scroll.x; } void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) { - window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. window->Scroll.y = new_scroll_y; - window->DC.CursorMaxPos.y -= window->Scroll.y; } void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) @@ -6350,8 +6342,10 @@ void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) // Set const ImVec2 old_pos = window->Pos; window->Pos = ImFloor(pos); - window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor - window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. + ImVec2 offset = window->Pos - old_pos; + window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so SizeContents calculation doesn't get affected. + window->DC.CursorStartPos += offset; } void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond) @@ -6495,11 +6489,13 @@ void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& s g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; } +// Content size = inner scrollable rectangle, padded with WindowPadding. +// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item. void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize; - g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value. + g.NextWindowData.ContentSizeVal = size; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) @@ -6712,7 +6708,7 @@ void ImGui::SetScrollX(float scroll_x) void ImGui::SetScrollY(float scroll_y) { ImGuiWindow* window = GetCurrentWindow(); - window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY + window->ScrollTarget.y = scroll_y; window->ScrollTargetCenterRatio.y = 0.0f; } @@ -7717,7 +7713,7 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov ImGuiDir clip_dir = g.NavMoveDir; if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) { - bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x) - window->Scroll.x; + bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x + window->WindowPadding.x * 2.0f) - window->Scroll.x; if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } @@ -7729,7 +7725,7 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov } if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) { - bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y) - window->Scroll.y; + bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y + window->WindowPadding.y * 2.0f) - window->Scroll.y; if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } @@ -9794,7 +9790,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) else if (rect_type == RT_InnerRect) { return window->InnerRect; } else if (rect_type == RT_InnerClipRect) { return window->InnerClipRect; } else if (rect_type == RT_WorkRect) { return window->WorkRect; } - else if (rect_type == RT_Contents) { return ImRect(window->Pos, window->Pos + window->SizeContents); } + else if (rect_type == RT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->SizeContents); } else if (rect_type == RT_ContentsRegionRect) { return window->ContentsRegionRect; } IM_ASSERT(0); return ImRect(); diff --git a/imgui.h b/imgui.h index b865679e..394c2842 100644 --- a/imgui.h +++ b/imgui.h @@ -271,7 +271,7 @@ namespace ImGui IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints. - IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. diff --git a/imgui_internal.h b/imgui_internal.h index 2ad53b24..c28073ea 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1253,9 +1253,8 @@ struct IMGUI_API ImGuiWindow ImVec2 Pos; // Position (always rounded-up to nearest pixel) ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) ImVec2 SizeFull; // Size when non collapsed - ImVec2 SizeFullAtLastBegin; // Copy of SizeFull at the end of Begin. This is the reference value we'll use on the next frame to decide if we need scrollbars. - ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame. FIXME: Include decoration, window title, border, menu, etc. Ideally should remove them from this value? - ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize(). EXCLUDE decorations. Making this not consistent with the above! + ImVec2 SizeContents; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. + ImVec2 SizeContentsExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). ImVec2 WindowPadding; // Window padding at the time of begin. float WindowRounding; // Window rounding at the time of begin. float WindowBorderSize; // Window border size at the time of begin. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index aedaa0ef..d744d77b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -898,7 +898,7 @@ void ImGui::Scrollbar(ImGuiAxis axis) bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerRect.Max.y); rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; } - ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->SizeFull[axis] - other_scrollbar_size, window->SizeContents[axis], rounding_corners); + ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->InnerRect.Max[axis] - window->InnerRect.Min[axis], window->SizeContents[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners); } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) From f95c77eeeae70383b3e278a33b511e0d63ee16ac Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 May 2019 21:49:22 +0200 Subject: [PATCH 405/566] Window rectangles: Changed WorkRect to cover the whole region including scrolling (toward obsolete ContentsRegionRect) + using full WindowPadding*1 padding. Tweaked InnerClipRect. TreeNode, CollapsingHeader: Fixed highlight frame not covering horizontal area fully when using horizontal scrolling. (#2211, #2579) TabBar: Fixed BeginTabBar() within a window with horizontal scrolling from creating a feedback loop with the horizontal contents size. Columns: Fixed Columns() within a window with horizontal scrolling from not covering the full horizontal area (previously only worked with an explicit contents size). (#125) Demo: Added demo code to test contentsrect/workrect --- docs/CHANGELOG.txt | 6 +++ imgui.cpp | 44 ++++++++++++---------- imgui_demo.cpp | 92 ++++++++++++++++++++++++++++++++++++++++++++-- imgui_internal.h | 16 +++++--- imgui_widgets.cpp | 17 +++++---- 5 files changed, 140 insertions(+), 35 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c0929a07..efbc663e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,12 @@ Other Changes: frame as clearing the focus. This was in most noticeable in back-ends such as Glfw and SDL which emits key release events when focusing another viewport, leading to Alt+clicking on void on another viewport triggering the issue. (#2609) +- TreeNode, CollapsingHeader: Fixed highlight frame not covering horizontal area fully when using + horizontal scrolling. (#2211, #2579) +- TabBar: Fixed BeginTabBar() within a window with horizontal scrolling from creating a feedback + loop with the horizontal contents size. +- Columns: Fixed Columns() within a window with horizontal scrolling from not covering the full + horizontal area (previously only worked with an explicit contents size). (#125) - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. - Style: Made window close button cross slightly smaller. diff --git a/imgui.cpp b/imgui.cpp index 09a81fa9..8038dfc5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4999,8 +4999,6 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) } } -// Draw background and borders -// Draw and handle scrollbars void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size) { ImGuiContext& g = *GImGui; @@ -5511,7 +5509,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // - Begin() initial clipping rect for drawing window background and borders. // - Begin() clipping whole child ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; - window->OuterRectClipped = window->Rect(); + ImRect outer_rect = window->Rect(); + window->OuterRectClipped = outer_rect; window->OuterRectClipped.ClipWith(host_rect); // Inner rectangle @@ -5525,15 +5524,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x; window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y; - // Work rectangle. - // Affected by window padding and border size. Used by: - // - Columns() for right-most edge - // - BeginTabBar() for right-most edge - window->WorkRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->WorkRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y); - window->WorkRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); - window->WorkRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y); - // Inner clipping rectangle. // Will extend a little bit outside the normal work region. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. @@ -5541,7 +5531,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. // Affected by window/frame border size. Used by: // - Begin() initial clip rect - window->InnerClipRect = window->WorkRect; + float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); + window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize)); + window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size); + window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.y * 0.5f), window->WindowBorderSize)); + window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize); window->InnerClipRect.ClipWithFull(host_rect); // DRAWING @@ -5589,12 +5583,25 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) + // Work rectangle. + // Affected by window padding and border size. Used by: + // - Columns() for right-most edge + // - TreeNode(), CollapsingHeader() for right-most edge + // - BeginTabBar() for right-most edge + const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar); + const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar); + const float work_rect_size_x = (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : ImMax(allow_scrollbar_x ? window->SizeContents.x : 0.0f, window->InnerRect.GetWidth() - window->WindowPadding.x * 2.0f)); + const float work_rect_size_y = (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : ImMax(allow_scrollbar_y ? window->SizeContents.y : 0.0f, window->InnerRect.GetHeight() - window->WindowPadding.y * 2.0f)); + window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize)); + window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize)); + window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x; + window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y; + // [LEGACY] Contents Region - // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + // FIXME-OBSOLETE: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out when we have both. // Used by: - // - Mouse wheel scrolling - // - ... (many things) + // - Mouse wheel scrolling + many other things window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); @@ -8719,9 +8726,8 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag window->DC.CurrentColumns = columns; // Set state for first column - const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->WorkRect.Max.x - window->Pos.x); - columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range - columns->OffMaxX = ImMax(content_region_width - window->Scroll.x, columns->OffMinX + 1.0f); + columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; + columns->OffMaxX = ImMax(window->WorkRect.Max.x - window->Pos.x, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostClipRect = window->ClipRect; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b38fadc7..294e6f03 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -17,9 +17,18 @@ // In this demo code, we frequently we use 'static' variables inside functions. A static variable persist across calls, so it is // essentially like a global variable but declared inside the scope of the function. We do this as a way to gather code and data // in the same place, to make the demo source code faster to read, faster to write, and smaller in size. -// It also happens to be a convenient way of storing simple UI related information as long as your function doesn't need to be reentrant -// or used in threads. This might be a pattern you will want to use in your code, but most of the real data you would be editing is -// likely going to be stored outside your functions. +// It also happens to be a convenient way of storing simple UI related information as long as your function doesn't need to be +// reentrant or used in multiple threads. This might be a pattern you will want to use in your code, but most of the real data +// you would be editing is likely going to be stored outside your functions. + +// The Demo code is this file is designed to be easy to copy-and-paste in into your application! +// Because of this: +// - We never omit the ImGui:: namespace when calling functions, even though most of our code is already in the same namespace. +// - We try to declare static variables in the local scope, as close as possible to the code using them. +// - We never use any of the helpers/facilities used internally by dear imgui, unless it has been exposed in the public API (imgui.h). +// - We never use maths operators on ImVec2/ImVec4. For other imgui sources files, they are provided by imgui_internal.h w/ IMGUI_DEFINE_MATH_OPERATORS, +// for your own sources file they are optional and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h. +// Because we don't want to assume anything about your support of maths operators, we don't use them in imgui_demo.cpp. /* @@ -2135,6 +2144,83 @@ static void ShowDemoWindowLayout() ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); ImGui::EndChild(); } + ImGui::Spacing(); + + static bool show_horizontal_contents_size_demo_window = false; + ImGui::Checkbox("Show Horizontal contents size demo window", &show_horizontal_contents_size_demo_window); + + if (show_horizontal_contents_size_demo_window) + { + static bool show_h_scrollbar = true; + static bool show_button = true; + static bool show_tree_nodes = true; + static bool show_columns = true; + static bool show_tab_bar = true; + static bool explicit_content_size = false; + static float contents_size_x = 300.0f; + if (explicit_content_size) + ImGui::SetNextWindowContentSize(ImVec2(contents_size_x, 0.0f)); + ImGui::Begin("Horizontal contents size demo window", &show_horizontal_contents_size_demo_window, show_h_scrollbar ? ImGuiWindowFlags_HorizontalScrollbar : 0); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0)); + HelpMarker("Test of different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\nUse 'Metrics->Tools->Show windows rectangles' to visualize rectangles."); + ImGui::Checkbox("H-scrollbar", &show_h_scrollbar); + ImGui::Checkbox("Button", &show_button); // Will grow contents size (unless explicitly overwritten) + ImGui::Checkbox("Tree nodes", &show_tree_nodes); // Will grow contents size and display highlight over full width + ImGui::Checkbox("Columns", &show_columns); // Will use contents size + ImGui::Checkbox("Tab bar", &show_tab_bar); // Will use contents size + ImGui::Checkbox("Explicit content size", &explicit_content_size); + if (explicit_content_size) + { + ImGui::SameLine(); + ImGui::SetNextItemWidth(100); + ImGui::DragFloat("##csx", &contents_size_x); + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE); + ImGui::Dummy(ImVec2(0, 10)); + } + ImGui::PopStyleVar(2); + ImGui::Separator(); + if (show_button) + { + ImGui::Button("this is a 300-wide button", ImVec2(300, 0)); + } + if (show_tree_nodes) + { + bool open = true; + if (ImGui::TreeNode("this is a tree node")) + { + if (ImGui::TreeNode("another one of those tree node...")) + { + ImGui::Text("Some tree contents"); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::CollapsingHeader("CollapsingHeader", &open); + } + if (show_columns) + { + ImGui::Columns(4); + for (int n = 0; n < 4; n++) + { + ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::NextColumn(); + } + ImGui::Columns(1); + } + if (show_tab_bar && ImGui::BeginTabBar("Hello")) + { + if (ImGui::BeginTabItem("OneOneOne")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("TwoTwoTwo")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("ThreeThreeThree")) { ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("FourFourFour")) { ImGui::EndTabItem(); } + ImGui::EndTabBar(); + } + ImGui::End(); + } + ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index c28073ea..e360f55a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1294,12 +1294,16 @@ struct IMGUI_API ImGuiWindow ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack - ImRect ClipRect; // Current clipping rectangle. = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. - ImRect OuterRectClipped; // == WindowRect just after setup in Begin(). == window->Rect() for root window. - ImRect InnerRect; // Inner rectangle - ImRect InnerClipRect; // == InnerRect minus WindowPadding.x, clipped within viewport or parent clip rect. - ImRect WorkRect; // == InnerRect minus WindowPadding.x - ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. Maximum visible content position ~~ Pos + (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis + + // The best way to understand what those rectangles are is to use the 'Metrics -> Tools -> Show windows rectangles' viewer. + // The main 'OuterRect', omitted as a field, is window->Rect(). + ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. + ImRect InnerRect; // Inner rectangle (omit title bar, menu bar) + ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect. + ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentsRegionRect over time (from 1.71+ onward). + ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). + ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. + int LastFrameActive; // Last frame number the window was Active. float ItemWidthDefault; ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d744d77b..0a3c8684 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5127,12 +5127,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // We vertically grow up to current line height up the typical widget height. const float text_base_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); - ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(GetContentRegionMaxAbs().x, window->DC.CursorPos.y + frame_height)); + ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->WorkRect.Max.x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding - frame_bb.Min.x -= (float)(int)(window->WindowPadding.x * 0.5f) - 1; - frame_bb.Max.x += (float)(int)(window->WindowPadding.x * 0.5f) - 1; + frame_bb.Min.x -= (float)(int)(window->WindowPadding.x * 0.5f - 1.0f); + frame_bb.Max.x += (float)(int)(window->WindowPadding.x * 0.5f - 1.0f); } const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing @@ -6324,15 +6324,15 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->FramePadding = g.Style.FramePadding; // Layout - ItemSize(ImVec2(tab_bar->OffsetMax, tab_bar->BarRect.GetHeight())); + ItemSize(ImVec2(0.0f /*tab_bar->OffsetMax*/, tab_bar->BarRect.GetHeight())); // Don't feed width back window->DC.CursorPos.x = tab_bar->BarRect.Min.x; // Draw separator const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_Tab); const float y = tab_bar->BarRect.Max.y - 1.0f; { - const float separator_min_x = tab_bar->BarRect.Min.x - window->WindowPadding.x; - const float separator_max_x = tab_bar->BarRect.Max.x + window->WindowPadding.x; + const float separator_min_x = tab_bar->BarRect.Min.x - ImFloor(window->WindowPadding.x * 0.5f); + const float separator_max_x = tab_bar->BarRect.Max.x + ImFloor(window->WindowPadding.x * 0.5f); window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f); } return true; @@ -6874,7 +6874,10 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (want_clip_rect) PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x, bb.Max.y), true); - ItemSize(bb, style.FramePadding.y); + ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; + ItemSize(bb.GetSize(), style.FramePadding.y); + window->DC.CursorMaxPos = backup_cursor_max_pos; + if (!ItemAdd(bb, id)) { if (want_clip_rect) From fe32fde376033916acef02db528de929a69c28c3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Jun 2019 16:55:48 +0200 Subject: [PATCH 406/566] Internals: Renamed SizeContents to ContentSize, SizeContentsExplicit to ContentSizeExplicit. Tweaked Metrics->Show Rectangles functionality. --- imgui.cpp | 75 ++++++++++++++++++++++++++--------------------- imgui_internal.h | 6 ++-- imgui_widgets.cpp | 4 +-- 3 files changed, 46 insertions(+), 39 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8038dfc5..c871445f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2550,7 +2550,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) Flags = ImGuiWindowFlags_None; Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); - SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); + ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f); WindowPadding = ImVec2(0.0f, 0.0f); WindowRounding = 0.0f; WindowBorderSize = 0.0f; @@ -4638,7 +4638,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl size = ImFloor(settings->Size); } window->Size = window->SizeFull = ImFloor(size); - window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values + window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { @@ -4694,17 +4694,17 @@ static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) return new_size; } -static ImVec2 CalcSizeContents(ImGuiWindow* window) +static ImVec2 CalcContentSize(ImGuiWindow* window) { if (window->Collapsed) if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) - return window->SizeContents; + return window->ContentSize; if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0) - return window->SizeContents; + return window->ContentSize; ImVec2 sz; - sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); - sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); + sz.x = (float)(int)((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); + sz.y = (float)(int)((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); return sz; } @@ -4743,18 +4743,18 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) { - ImVec2 size_contents = CalcSizeContents(window); + ImVec2 size_contents = CalcContentSize(window); return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents)); } float ImGui::GetWindowScrollMaxX(ImGuiWindow* window) { - return ImMax(0.0f, window->SizeContents.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); + return ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); } float ImGui::GetWindowScrollMaxY(ImGuiWindow* window) { - return ImMax(0.0f, window->SizeContents.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); + return ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); } static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) @@ -4773,8 +4773,8 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s float target_y = window->ScrollTarget.y; if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) target_y = 0.0f; - if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y + window->WindowPadding.y + g.Style.ItemSpacing.y) - target_y = window->SizeContents.y + window->WindowPadding.y * 2.0f; + if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y) + target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f; scroll.y = target_y - cr_y * window->InnerRect.GetHeight(); } scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); @@ -5281,9 +5281,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); } if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize) - window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal; + window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal; else if (first_begin_of_the_frame) - window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); + window->ContentSizeExplicit = ImVec2(0.0f, 0.0f); if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed) SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus) @@ -5318,7 +5318,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS // Update contents size from last frame for auto-fitting (or use explicit size) - window->SizeContents = CalcSizeContents(window); + window->ContentSize = CalcContentSize(window); if (window->HiddenFramesCanSkipItems > 0) window->HiddenFramesCanSkipItems--; if (window->HiddenFramesCannotSkipItems > 0) @@ -5329,7 +5329,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->HiddenFramesCannotSkipItems = 1; // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) - // We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. + // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0) { window->HiddenFramesCannotSkipItems = 1; @@ -5339,7 +5339,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Size.x = window->SizeFull.x = 0.f; if (!window_size_y_set_by_api) window->Size.y = window->SizeFull.y = 0.f; - window->SizeContents = ImVec2(0.f, 0.f); + window->ContentSize = ImVec2(0.f, 0.f); } } @@ -5382,7 +5382,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // SIZE // Calculate auto-fit size, handle automatic resize - const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents); + const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->ContentSize); ImVec2 size_full_modified(FLT_MAX, FLT_MAX); if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) { @@ -5417,10 +5417,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->InnerRect.GetWidth() + window->ScrollbarSizes.x; float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y - window->TitleBarHeight() - window->MenuBarHeight() : window->InnerRect.GetHeight() + window->ScrollbarSizes.y; - window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); - window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x + window->WindowPadding.x * 2.0f > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->ContentSize.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->ContentSize.x + window->WindowPadding.x * 2.0f > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); if (window->ScrollbarX && !window->ScrollbarY) - window->ScrollbarY = (window->SizeContents.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); + window->ScrollbarY = (window->ContentSize.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); } @@ -5590,8 +5590,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // - BeginTabBar() for right-most edge const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar); const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar); - const float work_rect_size_x = (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : ImMax(allow_scrollbar_x ? window->SizeContents.x : 0.0f, window->InnerRect.GetWidth() - window->WindowPadding.x * 2.0f)); - const float work_rect_size_y = (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : ImMax(allow_scrollbar_y ? window->SizeContents.y : 0.0f, window->InnerRect.GetHeight() - window->WindowPadding.y * 2.0f)); + const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->InnerRect.GetWidth() - window->WindowPadding.x * 2.0f)); + const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->InnerRect.GetHeight() - window->WindowPadding.y * 2.0f)); window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize)); window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize)); window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x; @@ -5604,8 +5604,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // - Mouse wheel scrolling + many other things window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); - window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); - window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); + window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); + window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) @@ -6351,7 +6351,7 @@ void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) window->Pos = ImFloor(pos); ImVec2 offset = window->Pos - old_pos; window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor - window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so SizeContents calculation doesn't get affected. + window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. window->DC.CursorStartPos += offset; } @@ -7720,7 +7720,7 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov ImGuiDir clip_dir = g.NavMoveDir; if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) { - bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x + window->WindowPadding.x * 2.0f) - window->Scroll.x; + bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x; if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } @@ -7732,7 +7732,7 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov } if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) { - bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y + window->WindowPadding.y * 2.0f) - window->Scroll.y; + bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y; if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } @@ -9773,7 +9773,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; } - enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerRect, RT_InnerClipRect, RT_WorkRect, RT_Contents, RT_ContentsRegionRect }; + enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerRect, RT_InnerClipRect, RT_WorkRect, RT_Contents, RT_ContentsRegionRect, RT_Count }; static bool show_windows_begin_order = false; static bool show_windows_rects = false; static int show_windows_rect_type = RT_WorkRect; @@ -9796,7 +9796,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) else if (rect_type == RT_InnerRect) { return window->InnerRect; } else if (rect_type == RT_InnerClipRect) { return window->InnerClipRect; } else if (rect_type == RT_WorkRect) { return window->WorkRect; } - else if (rect_type == RT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->SizeContents); } + else if (rect_type == RT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } else if (rect_type == RT_ContentsRegionRect) { return window->ContentsRegionRect; } IM_ASSERT(0); return ImRect(); @@ -9901,7 +9901,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->DrawList, "DrawList"); - ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); + ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y); ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", @@ -10004,11 +10004,18 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerRect\0" "InnerClipRect\0" "WorkRect\0" "Contents\0" "ContentsRegionRect\0"); + const char* rects_names[RT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Contents", "ContentsRegionRect" }; + show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, rects_names, RT_Count); if (show_windows_rects && g.NavWindow) { - ImRect r = Funcs::GetRect(g.NavWindow, show_windows_rect_type); - ImGui::BulletText("'%s': (%.1f,%.1f) (%.1f,%.1f) Size (%.1f,%.1f)", g.NavWindow->Name, r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight()); + ImGui::BulletText("'%s':", g.NavWindow->Name); + ImGui::Indent(); + for (int n = 0; n < RT_Count; n++) + { + ImRect r = Funcs::GetRect(g.NavWindow, n); + ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), rects_names[n]); + } + ImGui::Unindent(); } ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects); ImGui::TreePop(); diff --git a/imgui_internal.h b/imgui_internal.h index e360f55a..87a2598e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1170,7 +1170,7 @@ struct IMGUI_API ImGuiWindowTempData ImVec2 CursorPos; ImVec2 CursorPosPrevLine; ImVec2 CursorStartPos; // Initial position in client area with padding - ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Turned into window->SizeContents at the beginning of next frame + ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Used to calculate window->ContentSize at the beginning of next frame ImVec2 CurrLineSize; ImVec2 PrevLineSize; float CurrLineTextBaseOffset; @@ -1253,8 +1253,8 @@ struct IMGUI_API ImGuiWindow ImVec2 Pos; // Position (always rounded-up to nearest pixel) ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) ImVec2 SizeFull; // Size when non collapsed - ImVec2 SizeContents; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. - ImVec2 SizeContentsExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). + ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. + ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). ImVec2 WindowPadding; // Window padding at the time of begin. float WindowRounding; // Window rounding at the time of begin. float WindowBorderSize; // Window border size at the time of begin. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0a3c8684..351a558e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -847,7 +847,7 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa } // Apply scroll - // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm)); *p_scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); @@ -898,7 +898,7 @@ void ImGui::Scrollbar(ImGuiAxis axis) bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerRect.Max.y); rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; } - ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->InnerRect.Max[axis] - window->InnerRect.Min[axis], window->SizeContents[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners); + ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->InnerRect.Max[axis] - window->InnerRect.Min[axis], window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners); } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) From d6df777ff2c52b5afaac2b9837c2ec1b71b6edc6 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Jun 2019 17:07:43 +0200 Subject: [PATCH 407/566] TextWrapped, PushTextWrapPos(0.0f) within a window with horizontal scrolling from not covering the full horizontal area (previously only worked with an explicit contents size). --- imgui.cpp | 2 +- imgui_demo.cpp | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index c871445f..4c8812bc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2997,7 +2997,7 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) ImGuiWindow* window = GImGui->CurrentWindow; if (wrap_pos_x == 0.0f) - wrap_pos_x = GetContentRegionMaxAbs().x; + wrap_pos_x = window->WorkRect.Max.x; else if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 294e6f03..c8d7b83f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2154,6 +2154,7 @@ static void ShowDemoWindowLayout() static bool show_h_scrollbar = true; static bool show_button = true; static bool show_tree_nodes = true; + static bool show_text_wrapped = false; static bool show_columns = true; static bool show_tab_bar = true; static bool explicit_content_size = false; @@ -2167,6 +2168,7 @@ static void ShowDemoWindowLayout() ImGui::Checkbox("H-scrollbar", &show_h_scrollbar); ImGui::Checkbox("Button", &show_button); // Will grow contents size (unless explicitly overwritten) ImGui::Checkbox("Tree nodes", &show_tree_nodes); // Will grow contents size and display highlight over full width + ImGui::Checkbox("Text wrapped", &show_text_wrapped);// Will grow and use contents size ImGui::Checkbox("Columns", &show_columns); // Will use contents size ImGui::Checkbox("Tab bar", &show_tab_bar); // Will use contents size ImGui::Checkbox("Explicit content size", &explicit_content_size); @@ -2200,6 +2202,10 @@ static void ShowDemoWindowLayout() } ImGui::CollapsingHeader("CollapsingHeader", &open); } + if (show_text_wrapped) + { + ImGui::TextWrapped("This text should automatically wrap on the edge of the work rectangle."); + } if (show_columns) { ImGui::Columns(4); From 06f1d2c10152d91a1af6864a22201d9407fdd58b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Jun 2019 18:51:12 +0200 Subject: [PATCH 408/566] Internals: Storing ScrollMax into a member. Mostly to facilitate debugging. Also locking down window->Scroll slightly lower in the Begin function. --- imgui.cpp | 46 ++++++++++++++++++++++++---------------------- imgui_internal.h | 3 +-- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4c8812bc..3851108a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4747,16 +4747,6 @@ ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents)); } -float ImGui::GetWindowScrollMaxX(ImGuiWindow* window) -{ - return ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); -} - -float ImGui::GetWindowScrollMaxY(ImGuiWindow* window) -{ - return ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); -} - static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) { ImGuiContext& g = *GImGui; @@ -4780,8 +4770,8 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) { - scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window)); - scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window)); + scroll.x = ImMin(scroll.x, window->ScrollMax.x); + scroll.y = ImMin(scroll.y, window->ScrollMax.y); } return scroll; } @@ -5470,10 +5460,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; - // Apply scrolling - window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true); - window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); - // Apply window focus (new and reactivated windows are moved to front) bool want_focus = false; if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) @@ -5538,6 +5524,18 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize); window->InnerClipRect.ClipWithFull(host_rect); + // SCROLLING + + // Lock down maximum scrolling + // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate + // for right/bottom aligned items without creating a scrollbar. + window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); + window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); + + // Apply scrolling + window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true); + window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + // DRAWING // Setup draw list and outer clipping rectangle @@ -5619,7 +5617,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.NavHideHighlightOneFrame = false; - window->DC.NavHasScroll = (GetWindowScrollMaxY(window) > 0.0f); + window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f); window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; window->DC.MenuBarAppending = false; @@ -6687,22 +6685,26 @@ void ImGui::SetCursorScreenPos(const ImVec2& pos) float ImGui::GetScrollX() { - return GImGui->CurrentWindow->Scroll.x; + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Scroll.x; } float ImGui::GetScrollY() { - return GImGui->CurrentWindow->Scroll.y; + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Scroll.y; } float ImGui::GetScrollMaxX() { - return GetWindowScrollMaxX(GImGui->CurrentWindow); + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ScrollMax.x; } float ImGui::GetScrollMaxY() { - return GetWindowScrollMaxY(GImGui->CurrentWindow); + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ScrollMax.y; } void ImGui::SetScrollX(float scroll_x) @@ -9906,7 +9908,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); - ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window)); + ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y); ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); diff --git a/imgui_internal.h b/imgui_internal.h index 87a2598e..8faaa026 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1262,6 +1262,7 @@ struct IMGUI_API ImGuiWindow ImGuiID MoveId; // == window->GetID("#MOVE") ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window) ImVec2 Scroll; + ImVec2 ScrollMax; ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered ImVec2 ScrollbarSizes; // Size taken by scrollbars on each axis @@ -1450,8 +1451,6 @@ namespace ImGui IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); IMGUI_API void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x); IMGUI_API void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); - IMGUI_API float GetWindowScrollMaxX(ImGuiWindow* window); - IMGUI_API float GetWindowScrollMaxY(ImGuiWindow* window); IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); From 4149d22e852a2556865e6ce9cb50a597cc754e14 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Jun 2019 19:25:03 +0200 Subject: [PATCH 409/566] Fixed newly created window (e.g. appearing child window) from having scrollbar active on the first frame. (fix 6e03b27) + reworded code a little. (+1 squashed commits) Fixed auto-resize with AlwaysVerticalScrollbar or AlwaysHorizontalScrollbar flags not taking account of the expect scrollbar sizes. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index efbc663e..1375cb8e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,7 @@ Other Changes: after removal of WindowPadding on each sides. So SetNextWindowContentSize(ImVec2(100,100)) + auto-resize will always allow submitting a 100x100 item without creating a scrollbar, regarding of WindowPadding. The exact meaning of ContentSize for decorated windows was previously ill-defined. +- Window: Fixed auto-resize with AlwaysVerticalScrollbar or AlwaysHorizontalScrollbar flags. - Columns: Fixed Separator from creating an extraneous draw command. (#125) - Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect diff --git a/imgui.cpp b/imgui.cpp index 3851108a..e926bf8e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4733,9 +4733,11 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) // When the window cannot fit all contents (either because of constraints, either because screen is too small), // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit); - if (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) + bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar); + bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar); + if (will_have_scrollbar_x) size_auto_fit.y += style.ScrollbarSize; - if (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) + if (will_have_scrollbar_y) size_auto_fit.x += style.ScrollbarSize; return size_auto_fit; } @@ -5405,12 +5407,15 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { // When reading the current size we need to read it after size constraints have been applied. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. - float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->InnerRect.GetWidth() + window->ScrollbarSizes.x; - float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y - window->TitleBarHeight() - window->MenuBarHeight() : window->InnerRect.GetHeight() + window->ScrollbarSizes.y; - window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->ContentSize.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); - window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->ContentSize.x + window->WindowPadding.x * 2.0f > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - window->TitleBarHeight() - window->MenuBarHeight()); + ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes; + ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0,0) : window->ContentSize + window->WindowPadding * 2.0f; + float size_x_for_scrollbars = (size_full_modified.x != FLT_MAX || window_just_created) ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; + float size_y_for_scrollbars = (size_full_modified.y != FLT_MAX || window_just_created) ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); if (window->ScrollbarX && !window->ScrollbarY) - window->ScrollbarY = (window->ContentSize.y + window->WindowPadding.y * 2.0f > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); + window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); } From 15282261ddfd3bdd651a348b2ca8484ae217da26 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 4 Jun 2019 16:22:47 +0200 Subject: [PATCH 410/566] Internals: Minor no-op tidying up toward solving the WindowPadding / WindowBorderSize / ScrollbarSize overlapping mess. + Demo: Use SetScrollY(). --- imgui.cpp | 20 ++++++++++++-------- imgui_demo.cpp | 29 ++++++++++++++++++++--------- imgui_widgets.cpp | 11 +++++++---- 3 files changed, 39 insertions(+), 21 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e926bf8e..bc51d8aa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5400,6 +5400,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull); window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; + // Decoration size + const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); + // SCROLLBAR STATUS // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size). @@ -5407,7 +5410,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { // When reading the current size we need to read it after size constraints have been applied. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. - ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - window->TitleBarHeight() - window->MenuBarHeight()); + ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height); ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes; ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0,0) : window->ContentSize + window->WindowPadding * 2.0f; float size_x_for_scrollbars = (size_full_modified.x != FLT_MAX || window_just_created) ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; @@ -5499,19 +5502,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // - FindHoveredWindow() (w/ extra padding when border resize is enabled) // - Begin() initial clipping rect for drawing window background and borders. // - Begin() clipping whole child - ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; - ImRect outer_rect = window->Rect(); + const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; + const ImRect outer_rect = window->Rect(); + const ImRect title_bar_rect = window->TitleBarRect(); window->OuterRectClipped = outer_rect; window->OuterRectClipped.ClipWith(host_rect); // Inner rectangle // Not affected by window border size. Used by: + // - InnerClipRect // - NavScrollToBringItemIntoView() // - NavUpdatePageUpPageDown() // - Scrollbar() - const ImRect title_bar_rect = window->TitleBarRect(); - window->InnerRect.Min.x = title_bar_rect.Min.x; - window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight(); + window->InnerRect.Min.x = window->Pos.x; + window->InnerRect.Min.y = window->Pos.y + decoration_up_height; window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x; window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y; @@ -5606,7 +5610,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Used by: // - Mouse wheel scrolling + many other things window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; - window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height; window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); @@ -5615,7 +5619,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; window->DC.GroupOffset.x = 0.0f; window->DC.ColumnsOffset.x = 0.0f; - window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); + window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c8d7b83f..58f1dbec 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2059,14 +2059,21 @@ static void ShowDemoWindowLayout() HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given position."); static bool track = true; - static int track_line = 50, scroll_to_px = 200; + static int track_line = 50; + static float scroll_to_off_px = 0.0f; + static float scroll_to_pos_px = 200.0f; ImGui::Checkbox("Track", &track); ImGui::PushItemWidth(100); - ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line = %d"); - bool scroll_to = ImGui::Button("Scroll To Pos"); - ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "Y = %d px"); + ImGui::SameLine(140); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line = %d"); + + bool scroll_to_off = ImGui::Button("Scroll Offset"); + ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off_y", &scroll_to_off_px, 1.00f, 0, 9999, "+%.0f px"); + + bool scroll_to_pos = ImGui::Button("Scroll To Pos"); + ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos_y", &scroll_to_pos_px, 1.00f, 0, 9999, "Y = %.0f px"); + ImGui::PopItemWidth(); - if (scroll_to) + if (scroll_to_off || scroll_to_pos) track = false; ImGuiStyle& style = ImGui::GetStyle(); @@ -2076,9 +2083,13 @@ static void ShowDemoWindowLayout() if (i > 0) ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); - ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true); - if (scroll_to) - ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f); + + ImGuiWindowFlags child_flags = ImGuiWindowFlags_MenuBar; + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, child_flags); + if (scroll_to_off) + ImGui::SetScrollY(scroll_to_off_px); + if (scroll_to_pos) + ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f); for (int line = 0; line < 100; line++) { if (track && line == track_line) @@ -2094,7 +2105,7 @@ static void ShowDemoWindowLayout() float scroll_y = ImGui::GetScrollY(); float scroll_max_y = ImGui::GetScrollMaxY(); ImGui::EndChild(); - ImGui::Text("%.0f/%0.f", scroll_y, scroll_max_y); + ImGui::Text("%.0f/%.0f", scroll_y, scroll_max_y); ImGui::EndGroup(); } ImGui::TreePop(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 351a558e..becb5fe9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -883,22 +883,25 @@ void ImGui::Scrollbar(ImGuiAxis axis) // Calculate scrollbar bounding box const ImRect outer_rect = window->Rect(); + const ImRect inner_rect = window->InnerRect; + const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; + IM_ASSERT(scrollbar_size > 0.0f); IM_UNUSED(scrollbar_size); const float other_scrollbar_size = window->ScrollbarSizes[axis]; ImDrawCornerFlags rounding_corners = (other_scrollbar_size <= 0.0f) ? ImDrawCornerFlags_BotRight : 0; ImRect bb; if (axis == ImGuiAxis_X) { - bb.Min = ImVec2(window->InnerRect.Min.x, window->InnerRect.Max.y); - bb.Max = ImVec2(window->InnerRect.Max.x, outer_rect.Max.y - window->WindowBorderSize); + bb.Min = ImVec2(inner_rect.Min.x, inner_rect.Max.y); + bb.Max = ImVec2(inner_rect.Max.x, outer_rect.Max.y - window->WindowBorderSize); rounding_corners |= ImDrawCornerFlags_BotLeft; } else { - bb.Min = ImVec2(window->InnerRect.Max.x, window->InnerRect.Min.y); + bb.Min = ImVec2(inner_rect.Max.x, inner_rect.Min.y); bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerRect.Max.y); rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; } - ScrollbarEx(bb, id, axis, &window->Scroll[axis], window->InnerRect.Max[axis] - window->InnerRect.Min[axis], window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners); + ScrollbarEx(bb, id, axis, &window->Scroll[axis], inner_rect.Max[axis] - inner_rect.Min[axis], window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners); } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) From c1a61d25a71823d21943ff33121f75f344346955 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Jun 2019 15:23:01 +0200 Subject: [PATCH 411/566] Scrollbar overlap an extra WindowBorderSize amount on the left to make all distances consistent. Reverted to BorderSize not affecting work/contents rectangles. Scrollbar, Style: Changed default style.ScrollbarSize from 16 to 14. --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 45 +++++++++++++++++++++++++++++---------------- imgui_demo.cpp | 8 ++++++++ imgui_widgets.cpp | 11 ++++++----- 4 files changed, 45 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1375cb8e..11c98068 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,7 +57,8 @@ Other Changes: - ColorEdit: Fixed the color picker popup only displaying inputs as HSV instead of showing multiple options. (#2587, broken in 1.69 by #2384). - CollapsingHeader: Better clipping when a close button is enabled and it overlaps the label. (#600) -- Scrollbar: Very minor bounding box adjustment to cope with various border size. +- Scrollbar: Minor bounding box adjustment to cope with various border size. +- Scrollbar, Style: Changed default style.ScrollbarSize from 16 to 14. - Combo: Fixed rounding not applying with the ImGuiComboFlags_NoArrowButton flag. (#2607) [@DucaRii] - Nav: Fixed gamepad/keyboard moving of window affecting contents size incorrectly, sometimes leading to scrollbars appearing during the movement. diff --git a/imgui.cpp b/imgui.cpp index bc51d8aa..039f93f6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1146,7 +1146,7 @@ ImGuiStyle::ImGuiStyle() TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). - ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. @@ -5375,23 +5375,36 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Calculate auto-fit size, handle automatic resize const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->ContentSize); - ImVec2 size_full_modified(FLT_MAX, FLT_MAX); + bool use_current_size_for_scrollbar_x = window_just_created; + bool use_current_size_for_scrollbar_y = window_just_created; if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) { // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. if (!window_size_x_set_by_api) - window->SizeFull.x = size_full_modified.x = size_auto_fit.x; + { + window->SizeFull.x = size_auto_fit.x; + use_current_size_for_scrollbar_x = true; + } if (!window_size_y_set_by_api) - window->SizeFull.y = size_full_modified.y = size_auto_fit.y; + { + window->SizeFull.y = size_auto_fit.y; + use_current_size_for_scrollbar_y = true; + } } else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) { // Auto-fit may only grow window during the first few frames // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0) - window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + { + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + use_current_size_for_scrollbar_x = true; + } if (!window_size_y_set_by_api && window->AutoFitFramesY > 0) - window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + { + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + use_current_size_for_scrollbar_y = true; + } if (!window->Collapsed) MarkIniSettingsDirty(window); } @@ -5403,18 +5416,19 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Decoration size const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); - // SCROLLBAR STATUS + // SCROLLBAR VISIBILITY - // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size). + // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). if (!window->Collapsed) { // When reading the current size we need to read it after size constraints have been applied. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height); ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes; - ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0,0) : window->ContentSize + window->WindowPadding * 2.0f; - float size_x_for_scrollbars = (size_full_modified.x != FLT_MAX || window_just_created) ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; - float size_y_for_scrollbars = (size_full_modified.y != FLT_MAX || window_just_created) ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; + ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f; + float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; + float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; + //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons? window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); if (window->ScrollbarX && !window->ScrollbarY) @@ -5597,8 +5611,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // - BeginTabBar() for right-most edge const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar); const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar); - const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->InnerRect.GetWidth() - window->WindowPadding.x * 2.0f)); - const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->InnerRect.GetHeight() - window->WindowPadding.y * 2.0f)); + const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x)); + const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y)); window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize)); window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize)); window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x; @@ -5606,13 +5620,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // [LEGACY] Contents Region // FIXME-OBSOLETE: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. - // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out when we have both. // Used by: // - Mouse wheel scrolling + many other things window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height; - window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); - window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); + window->ContentsRegionRect.Max.x = window->ContentsRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x)); + window->ContentsRegionRect.Max.y = window->ContentsRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y)); // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 58f1dbec..6abfbbf2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2168,6 +2168,7 @@ static void ShowDemoWindowLayout() static bool show_text_wrapped = false; static bool show_columns = true; static bool show_tab_bar = true; + static bool show_child = false; static bool explicit_content_size = false; static float contents_size_x = 300.0f; if (explicit_content_size) @@ -2182,7 +2183,9 @@ static void ShowDemoWindowLayout() ImGui::Checkbox("Text wrapped", &show_text_wrapped);// Will grow and use contents size ImGui::Checkbox("Columns", &show_columns); // Will use contents size ImGui::Checkbox("Tab bar", &show_tab_bar); // Will use contents size + ImGui::Checkbox("Child", &show_child); // Will grow and use contents size ImGui::Checkbox("Explicit content size", &explicit_content_size); + ImGui::Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui::GetScrollX(), ImGui::GetScrollMaxX(), ImGui::GetScrollY(), ImGui::GetScrollMaxY()); if (explicit_content_size) { ImGui::SameLine(); @@ -2235,6 +2238,11 @@ static void ShowDemoWindowLayout() if (ImGui::BeginTabItem("FourFourFour")) { ImGui::EndTabItem(); } ImGui::EndTabBar(); } + if (show_child) + { + ImGui::BeginChild("child", ImVec2(0,0), true); + ImGui::EndChild(); + } ImGui::End(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index becb5fe9..39307243 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -884,21 +884,22 @@ void ImGui::Scrollbar(ImGuiAxis axis) // Calculate scrollbar bounding box const ImRect outer_rect = window->Rect(); const ImRect inner_rect = window->InnerRect; + const float border_size = window->WindowBorderSize; const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; - IM_ASSERT(scrollbar_size > 0.0f); IM_UNUSED(scrollbar_size); + IM_ASSERT(scrollbar_size > 0.0f); const float other_scrollbar_size = window->ScrollbarSizes[axis]; ImDrawCornerFlags rounding_corners = (other_scrollbar_size <= 0.0f) ? ImDrawCornerFlags_BotRight : 0; ImRect bb; if (axis == ImGuiAxis_X) { - bb.Min = ImVec2(inner_rect.Min.x, inner_rect.Max.y); - bb.Max = ImVec2(inner_rect.Max.x, outer_rect.Max.y - window->WindowBorderSize); + bb.Min = ImVec2(inner_rect.Min.x, outer_rect.Max.y - border_size - scrollbar_size); + bb.Max = ImVec2(inner_rect.Max.x, outer_rect.Max.y); rounding_corners |= ImDrawCornerFlags_BotLeft; } else { - bb.Min = ImVec2(inner_rect.Max.x, inner_rect.Min.y); - bb.Max = ImVec2(outer_rect.Max.x - window->WindowBorderSize, window->InnerRect.Max.y); + bb.Min = ImVec2(outer_rect.Max.x - border_size - scrollbar_size, inner_rect.Min.y); + bb.Max = ImVec2(outer_rect.Max.x, window->InnerRect.Max.y); rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; } ScrollbarEx(bb, id, axis, &window->Scroll[axis], inner_rect.Max[axis] - inner_rect.Min[axis], window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f, rounding_corners); From 300d8dd6569d1b45e67fbed9b05b4cc077d30690 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Jun 2019 15:32:37 +0200 Subject: [PATCH 412/566] Internals: Moved scrollbar visibility calculation block below the call to UpdateManualResize(). This commit is _intended_ to have no side-effect (next commit will). Also moved ItemWidthDefault calculation below rectangles. --- imgui.cpp | 52 ++++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 039f93f6..183b8c2d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5416,26 +5416,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Decoration size const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); - // SCROLLBAR VISIBILITY - - // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). - if (!window->Collapsed) - { - // When reading the current size we need to read it after size constraints have been applied. - // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. - ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height); - ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes; - ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f; - float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; - float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; - //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons? - window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); - window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); - if (window->ScrollbarX && !window->ScrollbarY) - window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); - window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); - } - // POSITION // Popup latch its initial position, will position itself when it appears next frame @@ -5466,7 +5446,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = FindBestWindowPosForPopup(window); - // Clamp position so it stays visible + // Clamp position/size so it stays visible // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. ImRect viewport_rect(GetViewportRect()); if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) @@ -5501,11 +5481,25 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); window->ResizeBorderHeld = (signed char)border_held; - // Default item width. Make it proportional to window size if window manually resizes - if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) - window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); - else - window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); + // SCROLLBAR VISIBILITY + + // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). + if (!window->Collapsed) + { + // When reading the current size we need to read it after size constraints have been applied. + // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. + ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height); + ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes; + ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f; + float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; + float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; + //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons? + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + if (window->ScrollbarX && !window->ScrollbarY) + window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + } // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) // Update various regions. Variables they depends on should be set above in this function. @@ -5547,6 +5541,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize); window->InnerClipRect.ClipWithFull(host_rect); + // Default item width. Make it proportional to window size if window manually resizes + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); + else + window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); + // SCROLLING // Lock down maximum scrolling From c96f2c40571c32700e0568fb4165badc93a7559c Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Jun 2019 15:33:41 +0200 Subject: [PATCH 413/566] Window: Fixed one case where auto-resize by double-clicking the resize grip would make either scrollbar appear for a single frame after the resize. Moved Scrollbar visibility block. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 16 +++++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 11c98068..2833b29f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,8 @@ Other Changes: will always allow submitting a 100x100 item without creating a scrollbar, regarding of WindowPadding. The exact meaning of ContentSize for decorated windows was previously ill-defined. - Window: Fixed auto-resize with AlwaysVerticalScrollbar or AlwaysHorizontalScrollbar flags. +- Window: Fixed one case where auto-resize by double-clicking the resize grip would make either scrollbar + appear for a single frame after the resize. - Columns: Fixed Separator from creating an extraneous draw command. (#125) - Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect diff --git a/imgui.cpp b/imgui.cpp index 183b8c2d..36ad3b44 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1077,7 +1077,7 @@ static int FindWindowFocusIndex(ImGuiWindow* window); // Misc static void UpdateMouseInputs(); static void UpdateMouseWheel(); -static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); +static bool UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, 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); @@ -4829,15 +4829,18 @@ static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_ } // Handle resize for: Resize Grips, Borders, Gamepad -static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) +// Return true when using auto-fit (double click on resize grip) +static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; + if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) - return; + return false; if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window. - return; + return false; + bool ret_auto_fit = false; const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0; const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f); @@ -4871,6 +4874,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au { // Manual auto-fit when double-clicking size_target = CalcSizeAfterConstraint(window, size_auto_fit); + ret_auto_fit = true; ClearActiveID(); } else if (held) @@ -4945,6 +4949,7 @@ static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->Size = window->SizeFull; + return ret_auto_fit; } static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding) @@ -5478,7 +5483,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4 const float resize_grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); if (!window->Collapsed) - UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); + if (UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0])) + use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true; window->ResizeBorderHeld = (signed char)border_held; // SCROLLBAR VISIBILITY From 597c024904d76ec3ac182a36ecfdff1aa99c21f0 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Jun 2019 00:42:27 +0200 Subject: [PATCH 414/566] Changed syntax for (very rarely used) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT mechanism, instead you only need to '#define ImDrawVert MyDrawVert' to use this feature, avoiding the need to declare the entire structure within an awkward macro. Using the old macro will now error with a message pointing you to the new method. (#38, #103, #1172, #1231, #2489) --- docs/CHANGELOG.txt | 4 ++++ examples/imgui_impl_dx9.cpp | 4 ++-- imconfig.h | 3 +++ imgui.cpp | 2 ++ imgui.h | 20 ++++++++++++-------- 5 files changed, 23 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2833b29f..e291ef3c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,10 @@ HOW TO UPDATE? Breaking Changes: - IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). - Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). +- Changed syntax for (very rarely used) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT mechanism, instead you only + need to '#define ImDrawVert MyDrawVert' to use this feature, avoiding the need to declare the entire + structure within an awkward macro. Using the old macro will now error with a message pointing you + to the new method. (#38, #103, #1172, #1231, #2489) Other Changes: - Window: clarified behavior of SetNextWindowContentSize(). Content size is defined as the size available diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 9dc9d92f..f1a67f69 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -138,8 +138,8 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. // FIXME-OPT: This is a 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; } + // 1) to avoid repacking colors: use '#define IMGUI_USE_BGRA_PACKED_COLOR' + // 2) to avoid repacking vertices: use 'struct ImDrawVertDx9 { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }' + '#define ImDrawVert ImDrawVertDx9' CUSTOMVERTEX* vtx_dst; ImDrawIdx* idx_dst; if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0) diff --git a/imconfig.h b/imconfig.h index 6eaffd74..ba4ff104 100644 --- a/imconfig.h +++ b/imconfig.h @@ -68,6 +68,9 @@ // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int +//---- Override ImDrawVert layout (see comments near ImDrawVert declaration) +//#define ImDrawVert MyDrawVert + //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui diff --git a/imgui.cpp b/imgui.cpp index 36ad3b44..98d8dd03 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,8 @@ CODE When you are not sure about a 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. + - 2019/06/05 (1.71) - changed syntax for (very rarely used) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT mechanism. instead you only need to '#define ImDrawVert MyDrawVert' to use this feature, + avoiding the need to declare the entire structure within an awkward macro. Using the old macro will now error and show a message pointing you to the you method. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. diff --git a/imgui.h b/imgui.h index 394c2842..5fdc1ae3 100644 --- a/imgui.h +++ b/imgui.h @@ -97,7 +97,7 @@ struct ImDrawData; // All draw command lists required to render struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. -struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. You may override layout with a #define. struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader struct ImFontConfig; // Configuration data when adding a font or merging fonts @@ -1803,19 +1803,23 @@ typedef unsigned short ImDrawIdx; #endif // Vertex layout -#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +// (You can override the vertex format layout by using e.g. #define ImDrawVert MyDrawVert in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields +// as needed to simplify integration in your engine. IMPORTANT: dear imgui DOES NOT CLEAR THE STRUCTURE AND DOESN"T CALL ITS CONSTRUCTOR, +// so any field other than pos/uv/col will be uninitialized. If you add extra fields (such as a Z coordinate) you will need to either +// ignore them, either set them up yourself.) +#ifndef ImDrawVert struct ImDrawVert { ImVec2 pos; ImVec2 uv; ImU32 col; }; -#else -// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h -// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. -// The type has to be described within the macro (you can either declare the struct or use a typedef) -// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. -IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// We previously used IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT that was expanded in this file. Instead please use '#define ImDrawVert MyDrawVert' [OBSOLETED in 1.71] +#if defined(IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +#error Please use '#define ImDrawVert MyDrawVert' instead! #endif // For use by ImDrawListSplitter. From 480d57e6a231a2902a2669712ff1c7871e9288d7 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Jun 2019 00:59:07 +0200 Subject: [PATCH 415/566] Revert "Changed syntax for (very rarely used) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT mechanism, instead you only need to '#define ImDrawVert MyDrawVert' to use this feature, avoiding the need to declare the entire structure within an awkward macro. Using the old macro will now error with a message pointing you to the new method. (#38, #103, #1172, #1231, #2489)" This reverts commit 597c024904d76ec3ac182a36ecfdff1aa99c21f0. --- docs/CHANGELOG.txt | 4 ---- examples/imgui_impl_dx9.cpp | 4 ++-- imconfig.h | 3 --- imgui.cpp | 2 -- imgui.h | 20 ++++++++------------ 5 files changed, 10 insertions(+), 23 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e291ef3c..2833b29f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,10 +35,6 @@ HOW TO UPDATE? Breaking Changes: - IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). - Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). -- Changed syntax for (very rarely used) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT mechanism, instead you only - need to '#define ImDrawVert MyDrawVert' to use this feature, avoiding the need to declare the entire - structure within an awkward macro. Using the old macro will now error with a message pointing you - to the new method. (#38, #103, #1172, #1231, #2489) Other Changes: - Window: clarified behavior of SetNextWindowContentSize(). Content size is defined as the size available diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index f1a67f69..9dc9d92f 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -138,8 +138,8 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. // FIXME-OPT: This is a waste of resource, the ideal is to use imconfig.h and - // 1) to avoid repacking colors: use '#define IMGUI_USE_BGRA_PACKED_COLOR' - // 2) to avoid repacking vertices: use 'struct ImDrawVertDx9 { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }' + '#define ImDrawVert ImDrawVertDx9' + // 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; } CUSTOMVERTEX* vtx_dst; ImDrawIdx* idx_dst; if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0) diff --git a/imconfig.h b/imconfig.h index ba4ff104..6eaffd74 100644 --- a/imconfig.h +++ b/imconfig.h @@ -68,9 +68,6 @@ // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int -//---- Override ImDrawVert layout (see comments near ImDrawVert declaration) -//#define ImDrawVert MyDrawVert - //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui diff --git a/imgui.cpp b/imgui.cpp index 98d8dd03..36ad3b44 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,8 +369,6 @@ CODE When you are not sure about a 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. - - 2019/06/05 (1.71) - changed syntax for (very rarely used) IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT mechanism. instead you only need to '#define ImDrawVert MyDrawVert' to use this feature, - avoiding the need to declare the entire structure within an awkward macro. Using the old macro will now error and show a message pointing you to the you method. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. diff --git a/imgui.h b/imgui.h index 5fdc1ae3..581a3ade 100644 --- a/imgui.h +++ b/imgui.h @@ -97,7 +97,7 @@ struct ImDrawData; // All draw command lists required to render struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) struct ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. -struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. You may override layout with a #define. +struct ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader struct ImFontConfig; // Configuration data when adding a font or merging fonts @@ -1803,23 +1803,19 @@ typedef unsigned short ImDrawIdx; #endif // Vertex layout -// (You can override the vertex format layout by using e.g. #define ImDrawVert MyDrawVert in imconfig.h -// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields -// as needed to simplify integration in your engine. IMPORTANT: dear imgui DOES NOT CLEAR THE STRUCTURE AND DOESN"T CALL ITS CONSTRUCTOR, -// so any field other than pos/uv/col will be uninitialized. If you add extra fields (such as a Z coordinate) you will need to either -// ignore them, either set them up yourself.) -#ifndef ImDrawVert +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; ImVec2 uv; ImU32 col; }; -#endif - -// We previously used IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT that was expanded in this file. Instead please use '#define ImDrawVert MyDrawVert' [OBSOLETED in 1.71] -#if defined(IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) -#error Please use '#define ImDrawVert MyDrawVert' instead! +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared a the time you'd want to set your type up. +// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif // For use by ImDrawListSplitter. From fea5f70611bca3987e78c6057302fab04555e56c Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Jun 2019 00:20:29 +0200 Subject: [PATCH 416/566] ImDrawCallback: Allow to override the signature of ImDrawCallback by #define-ing it. This is meant to facilitate custom rendering back-ends passing local render-specific data to the draw callback. --- docs/CHANGELOG.txt | 2 ++ imconfig.h | 6 ++++++ imgui.h | 3 +++ 3 files changed, 11 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2833b29f..791ec1e7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -84,6 +84,8 @@ Other Changes: support 32-bits indices. Most examples back-ends have been modified to support the VtxOffset field. - ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. This is provided for convenience and consistency with VtxOffset. +- ImDrawCallback: Allow to override the signature of ImDrawCallback by #define-ing it. This is meant to + facilitate custom rendering back-ends passing local render-specific data to the draw callback. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) Combine with RasterizerFlags::MonoHinting for best results. - ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not diff --git a/imconfig.h b/imconfig.h index 6eaffd74..84d35fd7 100644 --- a/imconfig.h +++ b/imconfig.h @@ -68,6 +68,12 @@ // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int +//---- Override ImDrawCallback signature (will need to modify renderer back-ends accordingly) +//struct ImDrawList; +//struct ImDrawCmd; +//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); +//#define ImDrawCallback MyImDrawCallback + //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui diff --git a/imgui.h b/imgui.h index 581a3ade..03e94df7 100644 --- a/imgui.h +++ b/imgui.h @@ -1771,7 +1771,10 @@ struct ImColor // A) Change your GPU render state, // B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' +// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering back-end accordingly. +#ifndef ImDrawCallback typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); +#endif // Special Draw callback value to request renderer back-end to reset the graphics/render state. // The renderer back-end needs to handle this special value, otherwise it will crash trying to call a function at this address. From 431aa4e456158f463840f7a9be5e651e94a4d9b6 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Jun 2019 16:13:30 +0200 Subject: [PATCH 417/566] Synced/merged minor cruft from docking branch to minimize drift. AFAIK the only meaningful no-op change is that the call UpdateHoveredWindowAndCaptureFlags() was moved above UpdateMouseMovingNewFrame() to match what docking branch has been doing for a while. --- docs/TODO.txt | 1 + examples/example_apple_opengl2/main.mm | 2 +- examples/example_emscripten/main.cpp | 4 ++-- examples/example_glfw_opengl2/main.cpp | 4 ++-- examples/example_glfw_opengl3/main.cpp | 6 ++---- examples/example_glfw_vulkan/main.cpp | 4 ++-- examples/example_glut_opengl2/main.cpp | 2 +- .../example_sdl_opengl2/example_sdl_opengl2.vcxproj | 2 +- examples/example_sdl_opengl2/main.cpp | 5 +++-- examples/example_sdl_opengl3/main.cpp | 6 +++--- examples/example_sdl_vulkan/main.cpp | 4 ++-- examples/example_win32_directx10/main.cpp | 4 ++-- examples/example_win32_directx11/main.cpp | 4 ++-- examples/example_win32_directx12/main.cpp | 8 ++++---- examples/example_win32_directx9/main.cpp | 4 ++-- examples/imgui_impl_dx10.cpp | 3 ++- examples/imgui_impl_dx11.cpp | 3 ++- examples/imgui_impl_dx12.cpp | 1 + examples/imgui_impl_dx9.cpp | 3 ++- examples/imgui_impl_dx9.h | 2 +- examples/imgui_impl_glfw.cpp | 12 ++++++------ examples/imgui_impl_opengl2.cpp | 3 ++- examples/imgui_impl_opengl3.cpp | 3 ++- examples/imgui_impl_sdl.cpp | 1 - examples/imgui_impl_vulkan.cpp | 3 ++- imgui.cpp | 13 +++++++++---- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 8 +++++--- 28 files changed, 66 insertions(+), 53 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index e6e119f1..a918b9e1 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -9,6 +9,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - doc/test: checklist app to verify binding/integration of imgui (test inputs, rendering, callback, etc.). - doc/tips: tips of the day: website? applet in imgui_club? + - window: preserve/restore relative focus ordering (persistent or not) (#2304) -> also see docking reference to same #. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis). (#690) - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 2c4622f1..d11b908d 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -241,7 +241,7 @@ IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index 574e6e24..5679d08d 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -61,8 +61,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 08463713..57841ffa 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -43,8 +43,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 9888ec5b..dffd46c9 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -86,8 +86,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); @@ -171,14 +171,12 @@ int main(int, char**) // Rendering ImGui::Render(); int display_w, display_h; - glfwMakeContextCurrent(window); glfwGetFramebufferSize(window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - glfwMakeContextCurrent(window); glfwSwapBuffers(window); } diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index e0c062af..2d1c4e00 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -372,8 +372,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index e9fc1068..3e63dad0 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -107,7 +107,7 @@ int main(int argc, char** argv) // Setup Dear ImGui context ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index f6094455..83a6a8a0 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -19,7 +19,7 @@ - {94E991D0-790A-4DAF-B442-AAADE3233C75} + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} example_sdl_opengl2 8.1 diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index ddefd096..7b3e853a 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -31,14 +31,15 @@ int main(int, char**) SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_GLContext gl_context = SDL_GL_CreateContext(window); + SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(1); // Enable vsync // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 08f1bb00..38b9ebd5 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -55,6 +55,7 @@ int main(int, char**) SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_GLContext gl_context = SDL_GL_CreateContext(window); + SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(1); // Enable vsync // Initialize OpenGL loader @@ -77,8 +78,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); @@ -170,7 +171,6 @@ int main(int, char**) // Rendering ImGui::Render(); - SDL_GL_MakeCurrent(window, gl_context); glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 2d49dda4..6ac67b82 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -355,8 +355,8 @@ int main(int, char**) // Setup Dear ImGui context ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 7b4a598e..d05268aa 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -46,8 +46,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 9c338529..9523728d 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -46,8 +46,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 82f1e547..90631e85 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -42,7 +42,7 @@ void CleanupDeviceD3D(); void CreateRenderTarget(); void CleanupRenderTarget(); void WaitForLastSubmittedFrame(); -FrameContext* WaitForNextFrameResources(); +FrameContext* WaitForNextFrameResources(); void ResizeSwapChain(HWND hWnd, int width, int height); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); @@ -70,8 +70,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); @@ -333,9 +333,9 @@ void CleanupDeviceD3D() void CreateRenderTarget() { - ID3D12Resource* pBackBuffer; for (UINT i = 0; i < NUM_BACK_BUFFERS; i++) { + ID3D12Resource* pBackBuffer = NULL; g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer)); g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, g_mainRenderTargetDescriptor[i]); g_mainRenderTargetResource[i] = pBackBuffer; diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 74a19d09..9e8dba95 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -44,8 +44,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 4c3e5bbb..22c4b9d0 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -146,7 +146,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) g_pIB->Unmap(); // Setup orthographic projection matrix into our constant buffer - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). + // 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. { void* mapped_resource; if (g_pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) @@ -486,6 +486,7 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() bool ImGui_ImplDX10_Init(ID3D10Device* device) { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx10"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 685b83fc..3bcb03a2 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -148,7 +148,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ctx->Unmap(g_pIB, 0); // Setup orthographic projection matrix into our constant buffer - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). + // 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. { D3D11_MAPPED_SUBRESOURCE mapped_resource; if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) @@ -493,6 +493,7 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx11"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 9bfa6a87..b40e9282 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -605,6 +605,7 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx12"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 9dc9d92f..2ee76ca6 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -80,7 +80,7 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); // Setup orthographic projection matrix - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). + // 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() { float L = draw_data->DisplayPos.x + 0.5f; @@ -218,6 +218,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx9"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx9.h b/examples/imgui_impl_dx9.h index 3af22d3f..1eaea87d 100644 --- a/examples/imgui_impl_dx9.h +++ b/examples/imgui_impl_dx9.h @@ -19,5 +19,5 @@ IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing ImGui state. -IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 090b012d..bcfeac45 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -43,11 +43,11 @@ #define GLFW_EXPOSE_NATIVE_WIN32 #include // for glfwGetWin32Window #endif -#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING -#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED -#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity -#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale -#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface +#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING +#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED +#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity +#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale +#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface // Data enum GlfwClientApi @@ -56,7 +56,7 @@ enum GlfwClientApi GlfwClientApi_OpenGL, GlfwClientApi_Vulkan }; -static GLFWwindow* g_Window = NULL; +static GLFWwindow* g_Window = NULL; // Main window static GlfwClientApi g_ClientApi = GlfwClientApi_Unknown; static double g_Time = 0.0; static bool g_MouseJustPressed[5] = { false, false, false, false, false }; diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index e1584a16..95720ff3 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -57,6 +57,7 @@ static GLuint g_FontTexture = 0; // Functions bool ImGui_ImplOpenGL2_Init() { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_opengl2"; return true; @@ -98,7 +99,7 @@ static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_wid // glUseProgram(last_program) // 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). DisplayMin is typically (0,0) for single viewport apps. + // 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. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); glMatrixMode(GL_PROJECTION); glPushMatrix(); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 494fa07a..2bf4ea85 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -122,6 +122,7 @@ static unsigned int g_VboHandle = 0, g_ElementsHandle = 0; // Functions bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_opengl3"; #if IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX @@ -177,7 +178,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid #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). DisplayMin is typically (0,0) for single viewport apps. + // 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. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index a9ff5cd8..1922068e 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -43,7 +43,6 @@ #include "imgui_impl_sdl.h" // SDL -// (the multi-viewports feature requires SDL features supported from SDL 2.0.5+) #include #include #if defined(__APPLE__) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 0cd6a77d..b55cb190 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -293,7 +293,7 @@ static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkCommandBu } // Setup scale and translation: - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps. + // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. { float scale[2]; scale[0] = 2.0f / draw_data->DisplaySize.x; @@ -803,6 +803,7 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_vulkan"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/imgui.cpp b/imgui.cpp index 36ad3b44..721fbe11 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3575,9 +3575,12 @@ void ImGui::NewFrame() g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX; + // Find hovered window + // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame) + UpdateHoveredWindowAndCaptureFlags(); + // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) UpdateMouseMovingWindowNewFrame(); - UpdateHoveredWindowAndCaptureFlags(); // Background darkening/whitening if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) @@ -4722,7 +4725,7 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) } else { - // Maximum window size is determined by the display size + // Maximum window size is determined by the viewport size or monitor size const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0; const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0; ImVec2 size_min = style.WindowMinSize; @@ -5081,7 +5084,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl const bool has_close_button = (p_open != NULL); const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse); - // Close & collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) + // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; @@ -5451,7 +5454,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = FindBestWindowPosForPopup(window); - // Clamp position/size so it stays visible + // Clamp position/size so window stays visible within its viewport or monitor + // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. ImRect viewport_rect(GetViewportRect()); if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) @@ -8701,6 +8705,7 @@ void ImGui::PushColumnsBackground() window->DrawList->ChannelsSetCurrent(0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); + IM_UNUSED(cmd_size); IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } diff --git a/imgui_internal.h b/imgui_internal.h index 8faaa026..1760bbb2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1659,10 +1659,10 @@ extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register status flags -#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register status flags +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register status flags #else #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) do { } while (0) -#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) #endif #if defined(__clang__) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 39307243..a5f820b0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -463,7 +463,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool flags |= ImGuiButtonFlags_PressedOnClickRelease; ImGuiWindow* backup_hovered_window = g.HoveredWindow; - if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) + const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window; + if (flatten_hovered_children) g.HoveredWindow = window; #ifdef IMGUI_ENABLE_TEST_ENGINE @@ -491,7 +492,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } } - if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) + if (flatten_hovered_children) g.HoveredWindow = backup_hovered_window; // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. @@ -6454,7 +6455,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. const char* tab_name = tab_bar->GetTabName(tab); - tab->WidthContents = TabItemCalcSize(tab_name, (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true).x; + const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true; + tab->WidthContents = TabItemCalcSize(tab_name, has_close_button).x; width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->WidthContents; From 63310acd5889c7b56ccdbf51d1acc2d98dce4e6f Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Jun 2019 16:16:18 +0200 Subject: [PATCH 418/566] Synced/merged minor cruft from master branch to minimize drift. Only meaningful change AFAIK is removing ImGuiComboFlags_PopupAlignLeft flag from the tab list combo emitted by TabBar. --- docs/TODO.txt | 1 - examples/example_win32_directx12/main.cpp | 10 +++++----- examples/imgui_impl_dx10.cpp | 4 ++-- examples/imgui_impl_dx11.cpp | 4 ++-- examples/imgui_impl_dx12.cpp | 2 +- examples/imgui_impl_dx9.cpp | 5 +++-- examples/imgui_impl_glfw.cpp | 10 +++++----- examples/imgui_impl_opengl2.cpp | 5 +++-- examples/imgui_impl_opengl3.cpp | 4 ++-- examples/imgui_impl_vulkan.cpp | 6 +++--- imgui.cpp | 8 +++++--- imgui_widgets.cpp | 2 +- 12 files changed, 32 insertions(+), 29 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 12f22d36..6d31927a 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -349,7 +349,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) - focus: unable to use SetKeyboardFocusHere() on clipped widgets. (#787) - - examples: move ImGui::NewFrame() out of the backend _NewFrame() ? - viewport: make it possible to have no main/hosting viewport - viewport: We set ImGuiViewportFlags_NoFocusOnAppearing in a way that is required for GLFW/SDL binding, but could be handled better without on a custom e.g. Win32 bindings. It prevents newly dragged-out viewports from taking the focus, which makes ALT+F4 more ambiguous. diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index a904125a..26a16f0f 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -268,10 +268,10 @@ bool CreateDeviceD3D(HWND hWnd) { D3D12_DESCRIPTOR_HEAP_DESC desc = {}; - desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; desc.NumDescriptors = NUM_BACK_BUFFERS; - desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; - desc.NodeMask = 1; + desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; + desc.NodeMask = 1; if (g_pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&g_pd3dRtvDescHeap)) != S_OK) return false; @@ -295,8 +295,8 @@ bool CreateDeviceD3D(HWND hWnd) { D3D12_COMMAND_QUEUE_DESC desc = {}; - desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; + desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; desc.NodeMask = 1; if (g_pd3dDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(&g_pd3dCommandQueue)) != S_OK) return false; diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 38003173..c5fdaeb4 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -152,7 +152,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) g_pIB->Unmap(); // Setup orthographic projection matrix into our constant buffer - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is (0,0) for single viewport apps. + // 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. { void* mapped_resource; if (g_pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) @@ -494,9 +494,9 @@ bool ImGui_ImplDX10_Init(ID3D10Device* device) { // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) io.BackendRendererName = "imgui_impl_dx10"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) // Get factory from device IDXGIDevice* pDXGIDevice = NULL; diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 8b87a895..e43a75af 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -154,7 +154,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ctx->Unmap(g_pIB, 0); // Setup orthographic projection matrix into our constant buffer - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is (0,0) for single viewport apps. + // 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. { D3D11_MAPPED_SUBRESOURCE mapped_resource; if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) @@ -501,9 +501,9 @@ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_co { // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) io.BackendRendererName = "imgui_impl_dx11"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) // Get factory from device IDXGIDevice* pDXGIDevice = NULL; diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 5a50194b..7dfdb9c6 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -611,9 +611,9 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO { // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) // FIXME-VIEWPORT: Actually unfinished.. io.BackendRendererName = "imgui_impl_dx12"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) // FIXME-VIEWPORT: Actually unfinished.. g_pd3dDevice = device; g_RTVFormat = rtv_format; diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index b74bded3..a8635fe0 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -88,7 +88,7 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); // Setup orthographic projection matrix - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is (0,0) for single viewport apps. + // 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() { float L = draw_data->DisplayPos.x + 0.5f; @@ -226,10 +226,11 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { + // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) io.BackendRendererName = "imgui_impl_dx9"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) g_pd3dDevice = device; g_pd3dDevice->AddRef(); diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 75f8f03b..21da2f69 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -233,12 +233,8 @@ void ImGui_ImplGlfw_Shutdown() static void ImGui_ImplGlfw_UpdateMousePosAndButtons() { - ImGuiIO& io = ImGui::GetIO(); - const ImVec2 mouse_pos_backup = io.MousePos; - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - io.MouseHoveredViewport = 0; - // Update buttons + ImGuiIO& io = ImGui::GetIO(); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) { // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. @@ -246,6 +242,10 @@ static void ImGui_ImplGlfw_UpdateMousePosAndButtons() g_MouseJustPressed[i] = false; } + // Update mouse position + const ImVec2 mouse_pos_backup = io.MousePos; + io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + io.MouseHoveredViewport = 0; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); for (int n = 0; n < platform_io.Viewports.Size; n++) { diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index bf6209fa..12526bc3 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -65,8 +65,9 @@ bool ImGui_ImplOpenGL2_Init() { // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) io.BackendRendererName = "imgui_impl_opengl2"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui_ImplOpenGL2_InitPlatformInterface(); return true; @@ -109,7 +110,7 @@ static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_wid // glUseProgram(last_program) // 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). DisplayMin is (0,0) for single viewport apps. + // 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. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); glMatrixMode(GL_PROJECTION); glPushMatrix(); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index ee3974e5..07b2cc67 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -130,11 +130,11 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) io.BackendRendererName = "imgui_impl_opengl3"; #if IMGUI_IMPL_OPENGL_HAS_DRAW_WITH_BASE_VERTEX io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. #endif + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) // Store GLSL version string so we can refer to it later in case we recreate shaders. Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure. #if defined(IMGUI_IMPL_OPENGL_ES2) @@ -189,7 +189,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid #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). DisplayMin is (0,0) for single viewport apps. + // 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. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 59197c30..16d2f4b6 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -307,7 +307,7 @@ static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkCommandBu } // Setup scale and translation: - // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is (0,0) for single viewport apps. + // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. { float scale[2]; scale[0] = 2.0f / draw_data->DisplaySize.x; @@ -821,9 +821,9 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend { // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) io.BackendRendererName = "imgui_impl_vulkan"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) IM_ASSERT(info->Instance != VK_NULL_HANDLE); IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); @@ -868,8 +868,8 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err = vkDeviceWaitIdle(v->Device); check_vk_result(err); - ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(v->Device, v->Allocator); + g_VulkanInitInfo.MinImageCount = min_image_count; } diff --git a/imgui.cpp b/imgui.cpp index fb857ed6..33a3173b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5510,7 +5510,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl window->DC.ItemFlags = item_flags_backup; // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) - // FIXME: Refactor text alignment facilities along with RenderText helpers, this is too much code.. + // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. const char* UNSAVED_DOCUMENT_MARKER = "*"; const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f; const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); @@ -6009,6 +6009,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Save last known viewport position within the window itself (so it can be saved in .ini file and restored) window->ViewportPos = window->Viewport->Pos; + // SCROLLBAR VISIBILITY + // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). if (!window->Collapsed) { @@ -10254,11 +10256,11 @@ static void SettingsHandlerWindow_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandl else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; } } -static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { // Gather data from windows that were active during this session // (if a window wasn't opened in this session we preserve its settings) - ImGuiContext& g = *imgui_ctx; + ImGuiContext& g = *ctx; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d60969e0..778a59fa 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6779,7 +6779,7 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) arrow_col.w *= 0.5f; PushStyleColor(ImGuiCol_Text, arrow_col); PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); - bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_PopupAlignLeft); + bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview); PopStyleColor(2); ImGuiTabItem* tab_to_select = NULL; From 2b997141cf4f7a0e3bf3be88232c1e3bafaa5328 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Jun 2019 16:36:26 +0200 Subject: [PATCH 419/566] Made PushID() behave the same in 32-bit and 64-bit, by not padding the integer into a void*. (Also technically faster.) --- imgui.cpp | 17 +++++++++++++++-- imgui_internal.h | 2 ++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 721fbe11..0be69546 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2624,6 +2624,14 @@ ImGuiID ImGuiWindow::GetID(const void* ptr) return id; } +ImGuiID ImGuiWindow::GetID(int n) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHashData(&n, sizeof(n), seed); + ImGui::KeepAliveID(id); + return id; +} + ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); @@ -2636,6 +2644,12 @@ ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr) return ImHashData(&ptr, sizeof(void*), seed); } +ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n) +{ + ImGuiID seed = IDStack.back(); + return ImHashData(&n, sizeof(n), seed); +} + // This is only used in rare/specific situations to manufacture an ID out of nowhere. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) { @@ -6836,9 +6850,8 @@ void ImGui::PushID(const void* ptr_id) void ImGui::PushID(int int_id) { - const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GImGui->CurrentWindow; - window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id)); + window->IDStack.push_back(window->GetIDNoKeepAlive(int_id)); } // Push a given id value ignoring the ID stack as a seed. diff --git a/imgui_internal.h b/imgui_internal.h index 1760bbb2..ab14d9f3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1330,8 +1330,10 @@ public: ImGuiID GetID(const char* str, const char* str_end = NULL); ImGuiID GetID(const void* ptr); + ImGuiID GetID(int n); ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL); ImGuiID GetIDNoKeepAlive(const void* ptr); + ImGuiID GetIDNoKeepAlive(int n); ImGuiID GetIDFromRectangle(const ImRect& r_abs); // We don't use g.FontSize because the window may be != g.CurrentWidow. From 32ab0a82d6941f89dc95661a8c9481d4c3c482ce Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Jun 2019 17:54:25 +0200 Subject: [PATCH 420/566] imgui-test: Added IMGUI_TEST_ENGINE_LOG macro to emit into test log from core or user land. --- imgui_internal.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ab14d9f3..0482aef2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1660,11 +1660,14 @@ extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); -#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register status flags -#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register status flags +extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...); +#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box +#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional) +#define IMGUI_TEST_ENGINE_LOG(_FMT, ...) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log #else #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB, _ID) do { } while (0) #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID, _LABEL, _FLAGS) do { } while (0) +#define IMGUI_TEST_ENGINE_LOG(_FMT, ...) do { } while (0) #endif #if defined(__clang__) From afa3978ff6969635f95d93e47662879179f49a41 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 20 May 2019 11:45:32 +0200 Subject: [PATCH 421/566] Internals: Added drawlist and color arg to RenderArrow(), RenderBullet(). Reordered args for RenderPixelEllipsis. --- imgui.cpp | 17 ++++++----------- imgui_draw.cpp | 2 +- imgui_internal.h | 12 +++++++++--- imgui_widgets.cpp | 48 ++++++++++++++++++++++++++--------------------- 4 files changed, 43 insertions(+), 36 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0be69546..822d6a40 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2445,13 +2445,11 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) } // 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 -void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale) +void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale) { - ImGuiContext& g = *GImGui; - - const float h = g.FontSize * 1.00f; + const float h = draw_list->_Data->FontSize * 1.00f; float r = h * 0.40f * scale; - ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale); + ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); ImVec2 a, b, c; switch (dir) @@ -2475,15 +2473,12 @@ void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale) IM_ASSERT(0); break; } - - g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text)); + draw_list->AddTriangleFilled(center + a, center + b, center + c, col); } -void ImGui::RenderBullet(ImVec2 pos) +void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); + draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8); } void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3f6b49a2..25671768 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3123,7 +3123,7 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im // FIXME: Rendering an ellipsis "..." is a surprisingly tricky problem for us... we cannot rely on font glyph having it, // and regular dot are typically too wide. If we render a dot/shape ourselves it comes with the risk that it wouldn't match // the boldness or positioning of what the font uses... -void ImGui::RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, int count, ImU32 col) +void ImGui::RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, ImU32 col, int count) { ImFont* font = draw_list->_Data->Font; const float font_scale = draw_list->_Data->FontSize / font->FontSize; diff --git a/imgui_internal.h b/imgui_internal.h index 0482aef2..ed1919cc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1578,18 +1578,24 @@ namespace ImGui IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0); - IMGUI_API void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale = 1.0f); - IMGUI_API void RenderBullet(ImVec2 pos); IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col, float sz); IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL); // 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 RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); IMGUI_API void RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor = ImGuiMouseCursor_Arrow); IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); - IMGUI_API void RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, int count, ImU32 col); + IMGUI_API void RenderPixelEllipsis(ImDrawList* draw_list, ImVec2 pos, ImU32 col, int count); + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + // 2019/06/07: Updating prototypes of some of the internal functions. Leaving those for reference for a short while. + inline void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale=1.0f) { ImGuiWindow* window = GetCurrentWindow(); RenderArrow(window->DrawList, pos, GetColorU32(ImGuiCol_Text), dir, scale); } + inline void RenderBullet(ImVec2 pos) { ImGuiWindow* window = GetCurrentWindow(); RenderBullet(window->DrawList, pos, GetColorU32(ImGuiCol_Text)); } +#endif // Widgets IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a5f820b0..6b2df21c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -366,7 +366,8 @@ void ImGui::BulletTextV(const char* fmt, va_list args) return; // Render - RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col); RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); } @@ -703,10 +704,11 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render - const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); RenderNavHighlight(bb, id); - RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding); - RenderArrow(bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), dir); + RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding); + RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir); return pressed; } @@ -759,11 +761,12 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); // Render - ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 text_col = GetColorU32(ImGuiCol_Text); ImVec2 center = bb.GetCenter(); if (hovered || held) - window->DrawList->AddCircleFilled(center/* + ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, col, 12); - RenderArrow(bb.Min + g.Style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); + window->DrawList->AddCircleFilled(center/*+ ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, bg_col, 12); + RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); // Switch to moving the window after mouse is moved beyond the initial drag threshold if (IsItemActive() && IsMouseDragging()) @@ -1143,8 +1146,9 @@ void ImGui::Bullet() } // Render and stay on same line - RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); - SameLine(0, style.FramePadding.x*2); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col); + SameLine(0, style.FramePadding.x * 2.0f); } //------------------------------------------------------------------------- @@ -1419,8 +1423,10 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(value_x2, frame_bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Left); if (!(flags & ImGuiComboFlags_NoArrowButton)) { - window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); - RenderArrow(ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down); + ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + ImU32 text_col = GetColorU32(ImGuiCol_Text); + window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); + RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down); } RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding); if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) @@ -5225,15 +5231,16 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render - const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y); ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin; if (display_frame) { // Framed type - RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); RenderNavHighlight(frame_bb, id, nav_highlight_flags); - RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); + RenderArrow(window->DrawList, frame_bb.Min + ImVec2(padding.x, text_base_offset_y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton) frame_bb.Max.x -= g.FontSize + style.FramePadding.x; if (g.LogEnabled) @@ -5255,14 +5262,14 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Unframed typed for tree nodes if (hovered || selected) { - RenderFrame(frame_bb.Min, frame_bb.Max, col, false); + RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); RenderNavHighlight(frame_bb, id, nav_highlight_flags); } if (flags & ImGuiTreeNodeFlags_Bullet) - RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); + RenderBullet(window->DrawList, frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y), text_col); else if (!is_leaf) - RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f); + RenderArrow(window->DrawList, frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f); if (g.LogEnabled) LogRenderedText(&text_pos, ">"); RenderText(text_pos, label, label_end, false); @@ -6036,9 +6043,8 @@ bool ImGui::BeginMenu(const char* label, bool enabled) float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); - if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); - RenderArrow(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right); - if (!enabled) PopStyleColor(); + ImU32 text_col = GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled); + RenderArrow(window->DrawList, pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), text_col, ImGuiDir_Right); } const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id); @@ -7094,7 +7100,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, const float ellipsis_x = text_pixel_clip_bb.Min.x + label_size_clipped_x + 1.0f; if (!close_button_visible && ellipsis_x + ellipsis_width <= bb.Max.x) - RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, text_pixel_clip_bb.Min.y), ellipsis_dot_count, GetColorU32(ImGuiCol_Text)); + RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, text_pixel_clip_bb.Min.y), GetColorU32(ImGuiCol_Text), ellipsis_dot_count); } else { From 0770449630630586bb8ec572dcce2fcb9654d70b Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 May 2019 17:24:22 +0200 Subject: [PATCH 422/566] Window: child windows outer decorations (e.g. scrollbar) are rendered as part of their parent window, avoiding the creation of an extraneous draw command. + Metrics: inverted color of clip rect vs vertices bounding box when hovering a draw command, so the color matches the per-vertex preview. --- docs/CHANGELOG.txt | 10 ++++++++-- imgui.cpp | 25 ++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 791ec1e7..93132e15 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,12 @@ HOW TO UPDATE? Breaking Changes: - IO: changed AddInputCharacter(unsigned short c) signature to AddInputCharacter(unsigned int c). - Renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). +- Window: rendering of child windows outer decorations (e.g. bg color, border, scrollbars) is now + performed as part of their parent window, avoiding the creation of an extraneous draw commands. + If you have overlapping child windows with decorations, and relied on their relative z-order to be + mapped to submission their order, this will affect your rendering. The optimization is disabled + if the parent window has no visual output because it appears to be the most common situation leading + to the creation of overlapping child windows. Please reach out if you are affected by this change! Other Changes: - Window: clarified behavior of SetNextWindowContentSize(). Content size is defined as the size available @@ -44,8 +50,6 @@ Other Changes: - Window: Fixed auto-resize with AlwaysVerticalScrollbar or AlwaysHorizontalScrollbar flags. - Window: Fixed one case where auto-resize by double-clicking the resize grip would make either scrollbar appear for a single frame after the resize. -- Columns: Fixed Separator from creating an extraneous draw command. (#125) -- Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Separator: Revert 1.70 "Declare its thickness (1.0f) to the layout" change. It's not incorrect but it breaks existing some layout patterns. Will return back to it when we expose Separator flags. - Fixed InputScalar, InputScalarN, SliderScalarN, DragScalarN with non-visible label from inserting @@ -74,6 +78,8 @@ Other Changes: loop with the horizontal contents size. - Columns: Fixed Columns() within a window with horizontal scrolling from not covering the full horizontal area (previously only worked with an explicit contents size). (#125) +- Columns: Fixed Separator from creating an extraneous draw command. (#125) +- Columns: Fixed Selectable with SpanAllColumns flag from creating an extraneous draw command. (#125) - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. - Style: Made window close button cross slightly smaller. diff --git a/imgui.cpp b/imgui.cpp index 822d6a40..dfdbf716 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,10 @@ CODE When you are not sure about a 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. + - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have + overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering. + This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows. + Please reach out if you are affected. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. @@ -3768,7 +3772,7 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im { int count = window->DC.ChildWindows.Size; if (count > 1) - ImQsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); + ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); for (int i = 0; i < count; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; @@ -5603,10 +5607,25 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding); } + // Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call. + // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. + // We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child. + // We also disabled this when we have dimming overlay behind this specific one child. + // FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected. + bool render_decorations_in_parent = false; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) + if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0) + render_decorations_in_parent = true; + if (render_decorations_in_parent) + window->DrawList = parent_window->DrawList; + const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size); + if (render_decorations_in_parent) + window->DrawList = &window->DrawListInst; + // Draw navigation selection/windowing rectangle border if (g.NavWindowingTargetAnim == window) { @@ -9883,8 +9902,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImRect vtxs_rect; for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); - clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); - vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); + clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,0,255,255)); + vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,255,0,255)); } if (!pcmd_node_open) continue; From d8435c771025dce27c97ca2fdf2736fa303ba0d9 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Jun 2019 15:02:16 +0200 Subject: [PATCH 423/566] ImDrawListSplitter: Fix idx offset when merging (cef88f6) (#2591) --- imgui.h | 2 +- imgui_draw.cpp | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index 03e94df7..b967d5be 100644 --- a/imgui.h +++ b/imgui.h @@ -1840,7 +1840,7 @@ struct ImDrawListSplitter inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame IMGUI_API void ClearFreeMemory(); IMGUI_API void Split(ImDrawList* draw_list, int count); - IMGUI_API void Merge(ImDrawList* draw_lists); + IMGUI_API void Merge(ImDrawList* draw_list); IMGUI_API void SetCurrentChannel(ImDrawList* draw_list, int channel_idx); }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 25671768..cba3e76a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1267,12 +1267,13 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; - if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) + if (ch.CmdBuffer.Size > 0 && ch.CmdBuffer.back().ElemCount == 0) ch.CmdBuffer.pop_back(); - else if (ch.CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch.CmdBuffer[0])) + if (ch.CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch.CmdBuffer[0])) { // Merge previous channel last draw command with current channel first draw command if matching. last_cmd->ElemCount += ch.CmdBuffer[0].ElemCount; + idx_offset += ch.CmdBuffer[0].ElemCount; ch.CmdBuffer.erase(ch.CmdBuffer.Data); } if (ch.CmdBuffer.Size > 0) From a9b5c834b62d72887909169f12119581b84e44dd Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Jun 2019 15:41:04 +0200 Subject: [PATCH 424/566] ImDrawListSplitter: Don't merge draw commands when crossing a VtxOffset boundary + Renamed fields ImDrawChannels to consistently suggest those are internal structures. --- imgui.h | 6 +++--- imgui_draw.cpp | 54 +++++++++++++++++++++++++------------------------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/imgui.h b/imgui.h index b967d5be..f915635d 100644 --- a/imgui.h +++ b/imgui.h @@ -1824,8 +1824,8 @@ IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; // For use by ImDrawListSplitter. struct ImDrawChannel { - ImVector CmdBuffer; - ImVector IdxBuffer; + ImVector _CmdBuffer; + ImVector _IdxBuffer; }; // Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. @@ -1834,7 +1834,7 @@ struct ImDrawListSplitter { int _Current; // Current channel number (0) int _Count; // Number of active channels (1+) - ImVector _Channels; // Draw channels (not resized down so Count might be < Channels.Size) + ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) inline ImDrawListSplitter() { Clear(); } inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index cba3e76a..26edd91a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1203,8 +1203,8 @@ void ImDrawListSplitter::ClearFreeMemory() { if (i == _Current) memset(&_Channels[i], 0, sizeof(_Channels[i])); // Current channel is a copy of CmdBuffer/IdxBuffer, don't destruct again - _Channels[i].CmdBuffer.clear(); - _Channels[i].IdxBuffer.clear(); + _Channels[i]._CmdBuffer.clear(); + _Channels[i]._IdxBuffer.clear(); } _Current = 0; _Count = 1; @@ -1231,22 +1231,22 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) } else { - _Channels[i].CmdBuffer.resize(0); - _Channels[i].IdxBuffer.resize(0); + _Channels[i]._CmdBuffer.resize(0); + _Channels[i]._IdxBuffer.resize(0); } - if (_Channels[i].CmdBuffer.Size == 0) + if (_Channels[i]._CmdBuffer.Size == 0) { ImDrawCmd draw_cmd; draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); draw_cmd.TextureId = draw_list->_TextureIdStack.back(); - _Channels[i].CmdBuffer.push_back(draw_cmd); + _Channels[i]._CmdBuffer.push_back(draw_cmd); } } } static inline bool CanMergeDrawCommands(ImDrawCmd* a, ImDrawCmd* b) { - return memcmp(&a->ClipRect, &b->ClipRect, sizeof(a->ClipRect)) == 0 && a->TextureId == b->TextureId && !a->UserCallback && !b->UserCallback; + return memcmp(&a->ClipRect, &b->ClipRect, sizeof(a->ClipRect)) == 0 && a->TextureId == b->TextureId && a->VtxOffset == b->VtxOffset && !a->UserCallback && !b->UserCallback; } void ImDrawListSplitter::Merge(ImDrawList* draw_list) @@ -1262,28 +1262,28 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; int new_idx_buffer_count = 0; - ImDrawCmd* last_cmd = (_Count > 0 && _Channels[0].CmdBuffer.Size > 0) ? &_Channels[0].CmdBuffer.back() : NULL; + ImDrawCmd* last_cmd = (_Count > 0 && _Channels[0]._CmdBuffer.Size > 0) ? &_Channels[0]._CmdBuffer.back() : NULL; int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0; for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; - if (ch.CmdBuffer.Size > 0 && ch.CmdBuffer.back().ElemCount == 0) - ch.CmdBuffer.pop_back(); - if (ch.CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch.CmdBuffer[0])) + if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0) + ch._CmdBuffer.pop_back(); + if (ch._CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch._CmdBuffer[0])) { // Merge previous channel last draw command with current channel first draw command if matching. - last_cmd->ElemCount += ch.CmdBuffer[0].ElemCount; - idx_offset += ch.CmdBuffer[0].ElemCount; - ch.CmdBuffer.erase(ch.CmdBuffer.Data); + last_cmd->ElemCount += ch._CmdBuffer[0].ElemCount; + idx_offset += ch._CmdBuffer[0].ElemCount; + ch._CmdBuffer.erase(ch._CmdBuffer.Data); } - if (ch.CmdBuffer.Size > 0) - last_cmd = &ch.CmdBuffer.back(); - new_cmd_buffer_count += ch.CmdBuffer.Size; - new_idx_buffer_count += ch.IdxBuffer.Size; - for (int cmd_n = 0; cmd_n < ch.CmdBuffer.Size; cmd_n++) + if (ch._CmdBuffer.Size > 0) + last_cmd = &ch._CmdBuffer.back(); + new_cmd_buffer_count += ch._CmdBuffer.Size; + new_idx_buffer_count += ch._IdxBuffer.Size; + for (int cmd_n = 0; cmd_n < ch._CmdBuffer.Size; cmd_n++) { - ch.CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; - idx_offset += ch.CmdBuffer.Data[cmd_n].ElemCount; + ch._CmdBuffer.Data[cmd_n].IdxOffset = idx_offset; + idx_offset += ch._CmdBuffer.Data[cmd_n].ElemCount; } } draw_list->CmdBuffer.resize(draw_list->CmdBuffer.Size + new_cmd_buffer_count); @@ -1295,8 +1295,8 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; - if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } - if (int sz = ch.IdxBuffer.Size) { memcpy(idx_write, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } + if (int sz = ch._CmdBuffer.Size) { memcpy(cmd_write, ch._CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } } draw_list->_IdxWritePtr = idx_write; draw_list->UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. @@ -1309,11 +1309,11 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) if (_Current == idx) return; // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap() - memcpy(&_Channels.Data[_Current].CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); - memcpy(&_Channels.Data[_Current].IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); + memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); _Current = idx; - memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx].CmdBuffer, sizeof(draw_list->CmdBuffer)); - memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx].IdxBuffer, sizeof(draw_list->IdxBuffer)); + memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx]._CmdBuffer, sizeof(draw_list->CmdBuffer)); + memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx]._IdxBuffer, sizeof(draw_list->IdxBuffer)); draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size; } From a8eb64fc5471e05e17760083b696362b3efb36e2 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Jun 2019 14:02:46 +0200 Subject: [PATCH 425/566] Log/Capture: Fixed BeginTabItem() label not being included in a text log/capture. Extracted tab rendering code into a RenderTextEllipsis() function. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ imgui_internal.h | 1 + imgui_widgets.cpp | 31 ++----------------------------- 4 files changed, 49 insertions(+), 29 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 93132e15..36b62efe 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,7 @@ Other Changes: - Style: Added style.WindowMenuButtonPosition (left/right, defaults to ImGuiDir_Left) to move the collapsing/docking button to the other side of the title bar. - Style: Made window close button cross slightly smaller. +- Log/Capture: Fixed BeginTabItem() label not being included in a text log/capture. - ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bits indices. The renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' to enable this, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. diff --git a/imgui.cpp b/imgui.cpp index dfdbf716..eeafc1c0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2422,6 +2422,51 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons LogRenderedText(&pos_min, text, text_display_end); } + +// Another overly complex function until we reorganize everything into a nice all-in-one helper. +// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define where the ellipsis is, from actual clipping and limit of the ellipsis display. +// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. +void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known) +{ + ImGuiContext& g = *GImGui; + if (text_end_full == NULL) + text_end_full = FindRenderedTextEnd(text); + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f); + + if (text_size.x > pos_max.x - pos_min.x) + { + + const ImFont* font = draw_list->_Data->Font; + const float font_size = draw_list->_Data->FontSize; + const int ellipsis_dot_count = 3; + const float ellipsis_width = (1.0f + 1.0f) * ellipsis_dot_count - 1.0f; + const char* text_end_ellipsis = NULL; + float text_size_clipped_x = font->CalcTextSizeA(font_size, (pos_max.x - pos_min.x) - ellipsis_width + 1.0f, 0.0f, text, text_end_full, &text_end_ellipsis).x; + if (text == text_end_ellipsis && text_end_ellipsis < text_end_full) // Always display at least 1 character if there's no room for character + ellipsis + { + text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full); + text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x; + } + while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) // Trim trailing space + { + text_end_ellipsis--; + text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte + } + RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); + + const float ellipsis_x = pos_min.x + text_size_clipped_x + 1.0f; + if (ellipsis_x + ellipsis_width <= ellipsis_max_x) + RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_dot_count); + } + else + { + RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); + } + + if (g.LogEnabled) + LogRenderedText(&pos_min, text, text_end_full); +} + // Render a rectangle shaped with optional rounding and borders void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { diff --git a/imgui_internal.h b/imgui_internal.h index ed1919cc..247a0748 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1575,6 +1575,7 @@ namespace ImGui IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL); IMGUI_API void 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 = ImVec2(0, 0), const ImRect* clip_rect = NULL); + IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6b2df21c..93ee7f33 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7077,35 +7077,8 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, text_pixel_clip_bb.Max.x -= close_button_sz; } - // Label with ellipsis - // FIXME: This should be extracted into a helper but the use of text_pixel_clip_bb and !close_button_visible makes it tricky to abstract at the moment - const char* label_display_end = FindRenderedTextEnd(label); - if (label_size.x > text_ellipsis_clip_bb.GetWidth()) - { - const int ellipsis_dot_count = 3; - const float ellipsis_width = (1.0f + 1.0f) * ellipsis_dot_count - 1.0f; - const char* label_end = NULL; - float label_size_clipped_x = g.Font->CalcTextSizeA(g.FontSize, text_ellipsis_clip_bb.GetWidth() - ellipsis_width + 1.0f, 0.0f, label, label_display_end, &label_end).x; - if (label_end == label && label_end < label_display_end) // Always display at least 1 character if there's no room for character + ellipsis - { - label_end = label + ImTextCountUtf8BytesFromChar(label, label_display_end); - label_size_clipped_x = g.Font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, label, label_end).x; - } - while (label_end > label && ImCharIsBlankA(label_end[-1])) // Trim trailing space - { - label_end--; - label_size_clipped_x -= g.Font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, label_end, label_end + 1).x; // Ascii blanks are always 1 byte - } - RenderTextClippedEx(draw_list, text_pixel_clip_bb.Min, text_pixel_clip_bb.Max, label, label_end, &label_size, ImVec2(0.0f, 0.0f)); - - const float ellipsis_x = text_pixel_clip_bb.Min.x + label_size_clipped_x + 1.0f; - if (!close_button_visible && ellipsis_x + ellipsis_width <= bb.Max.x) - RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, text_pixel_clip_bb.Min.y), GetColorU32(ImGuiCol_Text), ellipsis_dot_count); - } - else - { - RenderTextClippedEx(draw_list, text_pixel_clip_bb.Min, text_pixel_clip_bb.Max, label, label_display_end, &label_size, ImVec2(0.0f, 0.0f)); - } + float ellipsis_max_x = close_button_visible ? -FLT_MAX : bb.Max.x; + RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size); return close_button_pressed; } From c3a348aa25e59de404e5e641a1755879349e3a03 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Jun 2019 15:52:36 +0200 Subject: [PATCH 426/566] CollapsingHeader: Minor fix to align right side of frames (which is extruded past the Work/Contents rect) with clipping rectangle. --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 93ee7f33..ba3a71e0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5143,7 +5143,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l { // Framed header expand a little outside the default padding frame_bb.Min.x -= (float)(int)(window->WindowPadding.x * 0.5f - 1.0f); - frame_bb.Max.x += (float)(int)(window->WindowPadding.x * 0.5f - 1.0f); + frame_bb.Max.x += (float)(int)(window->WindowPadding.x * 0.5f); } const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing From 459763266299e6d090c6f0f1f44832d650d0c0b9 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Jun 2019 16:11:19 +0200 Subject: [PATCH 427/566] Readme, comments, dear imgui prefixes --- docs/README.md | 15 +++++---- examples/README.txt | 8 ++++- examples/example_allegro5/README.md | 2 +- examples/example_glfw_vulkan/CMakeLists.txt | 7 +++- examples/example_null/main.cpp | 3 +- imconfig.h | 6 ++-- imgui.cpp | 36 ++++++++++----------- imgui.h | 16 ++++----- imgui_demo.cpp | 4 +-- imgui_draw.cpp | 4 +-- imgui_internal.h | 4 +-- misc/cpp/README.txt | 2 +- misc/fonts/README.txt | 4 +-- misc/freetype/README.md | 4 +-- 14 files changed, 64 insertions(+), 51 deletions(-) diff --git a/docs/README.md b/docs/README.md index 1b00d2fb..5987c79a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,7 +20,7 @@ Dear ImGui is designed to enable fast iterations and to empower programmers to c Dear ImGui is particularly suited to integration in games engine (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on consoles platforms where operating system features are non-standard. -See [Software using dear imgui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui), [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) and [Gallery](https://github.com/ocornut/imgui/issues/2265) pages to get an idea of its use cases. +See [Software using dear imgui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui), [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) and [Gallery](https://github.com/ocornut/imgui/issues/2529) pages to get an idea of its use cases. Dear ImGui is self-contained within a few files that you can easily copy and compile into your application/engine: - imgui.cpp @@ -177,7 +177,8 @@ User screenshots:
[Gallery Part 5](https://github.com/ocornut/imgui/issues/1269) (Aug 2017 to Feb 2018)
[Gallery Part 6](https://github.com/ocornut/imgui/issues/1607) (Feb 2018 to June 2018)
[Gallery Part 7](https://github.com/ocornut/imgui/issues/1902) (June 2018 to January 2019) -
[Gallery Part 8](https://github.com/ocornut/imgui/issues/2265) (January 2019 onward) +
[Gallery Part 8](https://github.com/ocornut/imgui/issues/2265) (January 2019 to May 2019) +
[Gallery Part 9](https://github.com/ocornut/imgui/issues/2529) (May 2019 onward) Custom engine [![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) @@ -197,7 +198,7 @@ References The Immediate Mode GUI paradigm may at first appear unusual to some users. This is mainly because "Retained Mode" GUIs have been so widespread and predominant. The following links can give you a better understanding about how Immediate Mode GUIs works. - [Johannes 'johno' Norneby's article](http://www.johno.se/book/imgui.html). - [A presentation by Rickard Gustafsson and Johannes Algelind](http://www.cse.chalmers.se/edu/year/2011/course/TDA361/Advanced%20Computer%20Graphics/IMGUI.pdf). -- [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/). +- [Jari Komppa's tutorial on building an IMGUI library](http://iki.fi/sol/imgui/). - [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861). - [Nicolas Guillemot's CppCon'16 flash-talk about Dear ImGui](https://www.youtube.com/watch?v=LSRJ1jZq90k). - [Thierry Excoffier's Zero Memory Widget](http://perso.univ-lyon1.fr/thierry.excoffier/ZMW/). @@ -241,7 +242,7 @@ See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) and [Software usi The library started its life as "ImGui" due to the fact that I didn't give it a proper name when I released 1.0 and had no particular expectation that it would take off. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations (e.g. Unity uses it own implementation of the IMGUI paradigm). To reduce this ambiguity without affecting existing codebases, I have decided on an alternate, longer name "Dear ImGui" that people can use to refer to this specific library. Please try to refer to this library as "Dear ImGui". -**How can I tell whether to dispatch mouse/keyboard to imgui or to my application?** +**How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?**
**How can I display an image? What is ImTextureID, how does it works?**
**Why are multiple widgets reacting when I interact with a single one? How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack...**
**How can I use my own math types instead of ImVec2/ImVec4?** @@ -250,7 +251,7 @@ The library started its life as "ImGui" due to the fact that I didn't give it a
**How can I load multiple fonts?**
**How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?** ([example](https://github.com/ocornut/imgui/wiki/Loading-Font-Example))
**How can I interact with standard C++ types (such as std::string and std::vector)?** -
**How can I use the drawing facilities without an Dear ImGui window? (using ImDrawList API)** +
**How can I use the drawing facilities without a Dear ImGui window? (using ImDrawList API)**
**How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)**
**I integrated Dear ImGui in my engine and the text or lines are blurry..**
**I integrated Dear ImGui in my engine and some elements are disappearing when I move windows around..** @@ -308,10 +309,10 @@ Ongoing dear imgui development is financially supported by users and private spo - Media Molecule, Mobigame, Aras Pranckevičius, Greggman, DotEmu, Nadeo, Supercell, Runner, Aiden Koss, Kylotonn. **Salty caramel supporters** -- Recognition Robotics, ikrima, Geoffrey Evans, Mercury Labs, Singularity Demo Group, Lionel Landwerlin, Ron Gilbert, Brandon Townsend, Nikhil Deshpande, Cort Stratton, drudru, Harfang 3D, Jeff Roberts, Rainway inc, Ondra Voves, Mesh Consultants, Unit 2 Games. +- Remedy Entertainment, Recognition Robotics, ikrima, Geoffrey Evans, Mercury Labs, Singularity Demo Group, Lionel Landwerlin, Ron Gilbert, Brandon Townsend, Nikhil Deshpande, Cort Stratton, drudru, Harfang 3D, Jeff Roberts, Rainway inc, Ondra Voves, Mesh Consultants, Unit 2 Games, Neil Bickford. **Caramel supporters** -- Jerome Lanquetot, Daniel Collin, Ctrl Alt Ninja, Neil Henning, Neil Blakey-Milner, Aleksei, NeiloGD, Eric, Game Atelier, Vincent Hamm, Colin Riley, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, Josh Faust, Martin Donlon, Codecat, Doug McNabb, Emmanuel Julien, Guillaume Chereau, Jeffrey Slutter, Jeremiah Deckard, r-lyeh, Nekith, Joshua Fisher, Malte Hoffmann, Mustafa Karaalioglu, Merlyn Morgan-Graham, Per Vognsen, Fabian Giesen, Jan Staubach, Matt Hargett, John Shearer, Jesse Chounard, kingcoopa, Jonas Bernemann, Johan Andersson, Michael Labbe, Tomasz Golebiowski, Louis Schnellbach, Jimmy Andrews, Bojan Endrovski, Robin Berg Pettersen, Rachel Crawford, Andrew Johnson, Sean Hunter, Jordan Mellow, Nefarius Software Solutions, Laura Wieme, Robert Nix, Mick Honey, Steven Kah Hien Wong, Bartosz Bielecki, Oscar Penas, A M, Liam Moynihan, Artometa, Mark Lee, Dimitri Diakopoulos, Pete Goodwin, Johnathan Roatch, nyu lea, Oswald Hurlem. +- Jerome Lanquetot, Daniel Collin, Ctrl Alt Ninja, Neil Henning, Neil Blakey-Milner, Aleksei, NeiloGD, Eric, Game Atelier, Vincent Hamm, Colin Riley, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, Josh Faust, Martin Donlon, Codecat, Doug McNabb, Emmanuel Julien, Guillaume Chereau, Jeffrey Slutter, Jeremiah Deckard, r-lyeh, Nekith, Joshua Fisher, Malte Hoffmann, Mustafa Karaalioglu, Merlyn Morgan-Graham, Per Vognsen, Fabian Giesen, Jan Staubach, Matt Hargett, John Shearer, Jesse Chounard, kingcoopa, Jonas Bernemann, Johan Andersson, Michael Labbe, Tomasz Golebiowski, Louis Schnellbach, Jimmy Andrews, Bojan Endrovski, Robin Berg Pettersen, Rachel Crawford, Andrew Johnson, Sean Hunter, Jordan Mellow, Nefarius Software Solutions, Laura Wieme, Robert Nix, Mick Honey, Steven Kah Hien Wong, Bartosz Bielecki, Oscar Penas, A M, Liam Moynihan, Artometa, Mark Lee, Dimitri Diakopoulos, Pete Goodwin, Johnathan Roatch, nyu lea, Oswald Hurlem, Semyon Smelyanskiy, Le Bach, Jeong MyeongSoo, Chris Matthews, Astrofra. And all other past and present supporters; THANK YOU! (Please contact me if you would like to be added or removed from this list) diff --git a/examples/README.txt b/examples/README.txt index 82d39ef1..5cc27482 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -93,7 +93,7 @@ Most the example bindings are split in 2 parts: - Road-map: Dear ImGui 1.80 (WIP currently in the "docking" branch) will allows imgui windows to be seamlessly detached from the main application window. This is achieved using an extra layer to the - platform and renderer bindings, which allows imgui to communicate platform-specific requests. + platform and renderer bindings, which allows Dear ImGui to communicate platform-specific requests. If you decide to use unmodified imgui_impl_xxxx.cpp files, you will automatically benefit from improvements and fixes related to viewports and platform windows without extra work on your side. @@ -211,6 +211,12 @@ example_marmalade/ Marmalade example using IwGx. = main.cpp + imgui_impl_marmalade.cpp +example_null + Null example, compile and link imgui, create context, run headless with no inputs and no graphics output. + = main.cpp + This is used to quickly test compilation of core imgui files in as many setups as possible. + Because this application doesn't create a window nor a graphic context, there's no graphics output. + example_sdl_opengl2/ SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline). = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp diff --git a/examples/example_allegro5/README.md b/examples/example_allegro5/README.md index fb58fdbe..5ef45557 100644 --- a/examples/example_allegro5/README.md +++ b/examples/example_allegro5/README.md @@ -2,7 +2,7 @@ # Configuration Dear ImGui outputs 16-bit vertex indices by default. -Allegro doesn't support them natively, so we have two solutions: convert the indices manually in imgui_impl_allegro5.cpp, or compile imgui with 32-bit indices. +Allegro doesn't support them natively, so we have two solutions: convert the indices manually in imgui_impl_allegro5.cpp, or compile dear imgui with 32-bit indices. You can either modify imconfig.h that comes with Dear ImGui (easier), or set a C++ preprocessor option IMGUI_USER_CONFIG to find to a filename. We are providing `imconfig_allegro5.h` that enables 32-bit indices. Note that the back-end supports _BOTH_ 16-bit and 32-bit indices, but 32-bit indices will be slightly faster as they won't require a manual conversion. diff --git a/examples/example_glfw_vulkan/CMakeLists.txt b/examples/example_glfw_vulkan/CMakeLists.txt index 82d7ab47..68155ec8 100644 --- a/examples/example_glfw_vulkan/CMakeLists.txt +++ b/examples/example_glfw_vulkan/CMakeLists.txt @@ -1,3 +1,8 @@ +# Example usage: +# mkdir build +# cd build +# cmake -g "Visual Studio 14 2015" .. + cmake_minimum_required(VERSION 2.8) project(imgui_example_glfw_vulkan C CXX) @@ -18,7 +23,7 @@ option(GLFW_DOCUMENT_INTERNALS "Include internals in documentation" OFF) add_subdirectory(${GLFW_DIR} binary_dir EXCLUDE_FROM_ALL) include_directories(${GLFW_DIR}/include) -# ImGui +# Dear ImGui set(IMGUI_DIR ../../) include_directories(${IMGUI_DIR} ..) diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index 81af0999..aa2f6dba 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -1,4 +1,5 @@ -// dear imgui: null/dummy example application (compile and link imgui with NO INPUTS, NO OUTPUTS) +// dear imgui: null/dummy example application +// (compile and link imgui, create context, run headless with NO INPUTS, NO GRAPHICS OUTPUT) // This is useful to test building, but you cannot interact with anything here! #include "imgui.h" #include diff --git a/imconfig.h b/imconfig.h index 84d35fd7..30ba7901 100644 --- a/imconfig.h +++ b/imconfig.h @@ -3,10 +3,10 @@ // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. //----------------------------------------------------------------------------- -// A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h) +// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/branch with your modifications to imconfig.h) // B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h" -// If you do so you need to make sure that configuration settings are defined consistently _everywhere_ dear imgui is used, which include -// the imgui*.cpp files but also _any_ of your code that uses imgui. This is because some compile-time options have an affect on data structures. +// If you do so you need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include +// the imgui*.cpp files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. //----------------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index eeafc1c0..1fb76d23 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -51,7 +51,7 @@ DOCUMENTATION - How can I load multiple fonts? - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? - How can I interact with standard C++ types (such as std::string and std::vector)? - - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + - How can I use the drawing facilities without a Dear ImGui window? (using ImDrawList API) - How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad) - I integrated Dear ImGui in my engine and the text or lines are blurry.. - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. @@ -172,7 +172,7 @@ CODE - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. - Add the Dear ImGui source files to your projects or using your preferred build system. It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL). - - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types. + - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" @@ -251,16 +251,16 @@ CODE io.MouseDown[1] = my_mouse_buttons[1]; // Call NewFrame(), after this point you can use ImGui::* functions anytime - // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere) + // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere) ImGui::NewFrame(); // Most of your application code here ImGui::Text("Hello, world!"); - MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); - MyGameRender(); // may use any ImGui functions as well! + MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); + MyGameRender(); // may use any Dear ImGui functions as well! - // Render imgui, swap buffers - // (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code) + // Render dear imgui, swap buffers + // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code) ImGui::EndFrame(); ImGui::Render(); ImDrawData* draw_data = ImGui::GetDrawData(); @@ -282,8 +282,8 @@ CODE for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; - const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui - const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui + const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui + const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; @@ -294,7 +294,7 @@ CODE else { // The texture for the draw call is specified by pcmd->TextureId. - // The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization. + // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization. MyEngineBindTexture((MyTexture*)pcmd->TextureId); // We are using scissoring to clip some objects. All low-level graphics API should supports it. @@ -319,8 +319,8 @@ CODE - The examples/ folders contains many actual implementation of the pseudo-codes above. - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated. - They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs - from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information. + They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the + rest of your application. In every cases you need to pass on the inputs to Dear ImGui. Refer to the FAQ for more information. - Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues! USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS @@ -599,7 +599,7 @@ CODE longer name "Dear ImGui" that people can use to refer to this specific library. Please try to refer to this library as "Dear ImGui". - Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application? + Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application? A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } ) - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application. - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application. @@ -3095,7 +3095,7 @@ const char* ImGui::GetVersion() return IMGUI_VERSION; } -// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself +// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module ImGuiContext* ImGui::GetCurrentContext() { @@ -3474,13 +3474,13 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) g.HoveredWindow = g.HoveredRootWindow = NULL; - // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app) + // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app) if (g.WantCaptureMouseNextFrame != -1) g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0); else g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty()); - // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app) + // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app) if (g.WantCaptureKeyboardNextFrame != -1) g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0); else @@ -3746,7 +3746,7 @@ void ImGui::Shutdown(ImGuiContext* context) } g.IO.Fonts = NULL; - // Cleanup of other data are conditional on actually having initialized ImGui. + // Cleanup of other data are conditional on actually having initialized Dear ImGui. if (!g.Initialized) return; @@ -7368,7 +7368,7 @@ bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) } // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. -// Note that popup visibility status is owned by imgui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here. +// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; diff --git a/imgui.h b/imgui.h index f915635d..4d272015 100644 --- a/imgui.h +++ b/imgui.h @@ -881,7 +881,7 @@ enum ImGuiDragDropFlags_ ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item. ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. - ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) // AcceptDragDropPayload() flags ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. @@ -995,7 +995,7 @@ enum ImGuiConfigFlags_ ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the back-end. ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. - // User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core ImGui) + // User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core Dear ImGui) ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse. }; @@ -1163,12 +1163,12 @@ enum ImGuiMouseCursor_ ImGuiMouseCursor_None = -1, ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. - ImGuiMouseCursor_ResizeAll, // (Unused by imgui functions) + ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions) ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window - ImGuiMouseCursor_Hand, // (Unused by imgui functions. Use for e.g. hyperlinks) + ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) ImGuiMouseCursor_COUNT // Obsolete names (will be removed) @@ -1280,7 +1280,7 @@ struct ImVector struct ImGuiStyle { - float Alpha; // Global alpha applies to everything in ImGui. + float Alpha; // Global alpha applies to everything in Dear ImGui. ImVec2 WindowPadding; // Padding within a window. float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). @@ -1440,7 +1440,7 @@ struct ImGuiIO bool MouseClicked[5]; // Mouse button went from !Down to Down bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? bool MouseReleased[5]; // Mouse button went from Down to !Down - bool MouseDownOwned[5]; // Track if button was clicked inside an imgui window. We don't request mouse capture from the application if click started outside ImGui bounds. + bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window. We don't request mouse capture from the application if click started outside ImGui bounds. bool MouseDownWasDoubleClick[5]; // Track if button down was a double-click float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) float MouseDownDurationPrev[5]; // Previous time the mouse button has been down @@ -1962,7 +1962,7 @@ struct ImDrawList IMGUI_API void UpdateTextureID(); }; -// All draw data to render an ImGui frame +// All draw data to render a Dear ImGui frame // (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, // as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) struct ImDrawData @@ -1981,7 +1981,7 @@ struct ImDrawData ~ImDrawData() { Clear(); } void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext! IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! - IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. + IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6abfbbf2..edef9ebc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2273,7 +2273,7 @@ static void ShowDemoWindowPopups() // The properties of popups windows are: // - They block normal mouse hovering detection outside them. (*) // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. - // - Their visibility state (~bool) is held internally by imgui instead of being held by the programmer as we are used to with regular Begin() calls. + // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as we are used to with regular Begin() calls. // User can manipulate the visibility state by calling OpenPopup(). // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup. // Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time. @@ -2873,7 +2873,7 @@ static void ShowDemoWindowMisc() //----------------------------------------------------------------------------- // [SECTION] About Window / ShowAboutWindow() -// Access from ImGui Demo -> Help -> About +// Access from Dear ImGui Demo -> Help -> About //----------------------------------------------------------------------------- void ImGui::ShowAboutWindow(bool* p_open) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 26edd91a..6e32995a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1434,7 +1434,7 @@ ImFontConfig::ImFontConfig() //----------------------------------------------------------------------------- // A work of art lies ahead! (. = white layer, X = black layer, others are blank) -// The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. +// The white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 108; const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000; @@ -2818,7 +2818,7 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const { if (!text_end) - text_end = text_begin + strlen(text_begin); // ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls. + text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. // Align to be pixel perfect pos.x = (float)(int)pos.x + DisplayOffset.x; diff --git a/imgui_internal.h b/imgui_internal.h index 247a0748..98effed2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -71,7 +71,7 @@ struct ImDrawListSharedData; // Data shared between all ImDrawList instan struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it struct ImGuiColumnData; // Storage data for a single column struct ImGuiColumns; // Storage data for a columns set -struct ImGuiContext; // Main imgui context +struct ImGuiContext; // Main Dear ImGui context struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box @@ -127,7 +127,7 @@ namespace ImStb //----------------------------------------------------------------------------- #ifndef GImGui -extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointer +extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #endif //----------------------------------------------------------------------------- diff --git a/misc/cpp/README.txt b/misc/cpp/README.txt index 9067cac0..8d5982e0 100644 --- a/misc/cpp/README.txt +++ b/misc/cpp/README.txt @@ -5,6 +5,6 @@ imgui_stdlib.h + imgui_stdlib.cpp imgui_scoped.h [Experimental, not currently in main repository] - Additional header file with some RAII-style wrappers for common ImGui functions. + Additional header file with some RAII-style wrappers for common Dear ImGui functions. Try by merging: https://github.com/ocornut/imgui/pull/2197 Discuss at: https://github.com/ocornut/imgui/issues/2096 diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index e658ac67..ae23bb1c 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -279,13 +279,13 @@ ProggyClean.ttf Copyright (c) 2004, 2005 Tristan Grimmer MIT License - recommended loading setting in ImGui: Size = 13.0, DisplayOffset.Y = +1 + recommended loading setting: Size = 13.0, DisplayOffset.Y = +1 http://www.proggyfonts.net/ ProggyTiny.ttf Copyright (c) 2004, 2005 Tristan Grimmer MIT License - recommended loading setting in ImGui: Size = 10.0, DisplayOffset.Y = +1 + recommended loading setting: Size = 10.0, DisplayOffset.Y = +1 http://www.proggyfonts.net/ Karla-Regular.ttf diff --git a/misc/freetype/README.md b/misc/freetype/README.md index b62671ce..87b27364 100644 --- a/misc/freetype/README.md +++ b/misc/freetype/README.md @@ -1,6 +1,6 @@ # imgui_freetype -Build font atlases using FreeType instead of stb_truetype (the default imgui's font rasterizer). +Build font atlases using FreeType instead of stb_truetype (which is the default font rasterizer in Dear ImGui).
by @vuhdo, @mikesart, @ocornut. ### Usage @@ -22,7 +22,7 @@ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); FreeType assumes blending in linear space rather than gamma space. See FreeType note for [FT_Render_Glyph](https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph). For correct results you need to be using sRGB and convert to linear space in the pixel shader output. -The default imgui styles will be impacted by this change (alpha values will need tweaking). +The default Dear ImGui styles will be impacted by this change (alpha values will need tweaking). ### Test code Usage ```cpp From 5ae268c0a3575cb92b16e1751884ae343493e64f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Jun 2019 16:12:00 +0200 Subject: [PATCH 428/566] Internals: Reworked RenderTextEllipsis() to satisfy what we need for table headers. --- imgui.cpp | 19 ++++++++++++++----- imgui_widgets.cpp | 2 +- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1fb76d23..6290ebaf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2424,7 +2424,7 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons // Another overly complex function until we reorganize everything into a nice all-in-one helper. -// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define where the ellipsis is, from actual clipping and limit of the ellipsis display. +// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display. // This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known) { @@ -2435,27 +2435,36 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, if (text_size.x > pos_max.x - pos_min.x) { + // Hello wo... + // | | | + // min max ellipsis_max + // <-> this is generally some padding value + // FIXME-STYLE: RenderPixelEllipsis() style should use actual font data. const ImFont* font = draw_list->_Data->Font; const float font_size = draw_list->_Data->FontSize; const int ellipsis_dot_count = 3; const float ellipsis_width = (1.0f + 1.0f) * ellipsis_dot_count - 1.0f; const char* text_end_ellipsis = NULL; - float text_size_clipped_x = font->CalcTextSizeA(font_size, (pos_max.x - pos_min.x) - ellipsis_width + 1.0f, 0.0f, text, text_end_full, &text_end_ellipsis).x; - if (text == text_end_ellipsis && text_end_ellipsis < text_end_full) // Always display at least 1 character if there's no room for character + ellipsis + + float text_width = ImMax((pos_max.x - ellipsis_width) - pos_min.x, 1.0f); + float text_size_clipped_x = font->CalcTextSizeA(font_size, text_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; + if (text == text_end_ellipsis && text_end_ellipsis < text_end_full) { + // Always display at least 1 character if there's no room for character + ellipsis text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full); text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x; } - while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) // Trim trailing space + while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) { + // Trim trailing space before ellipsis text_end_ellipsis--; text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte } RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); const float ellipsis_x = pos_min.x + text_size_clipped_x + 1.0f; - if (ellipsis_x + ellipsis_width <= ellipsis_max_x) + if (ellipsis_x + ellipsis_width - 1.0f <= ellipsis_max_x) RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_dot_count); } else diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ba3a71e0..11d348c9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7077,7 +7077,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, text_pixel_clip_bb.Max.x -= close_button_sz; } - float ellipsis_max_x = close_button_visible ? -FLT_MAX : bb.Max.x; + float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f; RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size); return close_button_pressed; From 2da1c66d151aec08aee06be4c5948b3cd256a617 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 12 Jun 2019 16:15:08 +0200 Subject: [PATCH 429/566] Version 1.71 + comments --- docs/CHANGELOG.txt | 7 ++++--- examples/README.txt | 4 ++-- examples/example_glut_opengl2/main.cpp | 2 +- examples/imgui_impl_glut.cpp | 2 +- examples/imgui_impl_glut.h | 2 +- imconfig.h | 5 +++-- imgui.cpp | 2 +- imgui.h | 9 +++++---- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 13 files changed, 23 insertions(+), 20 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 36b62efe..d4f5badf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -28,8 +28,9 @@ 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.71 (In Progress) + VERSION 1.71 (Released 2019-06-12) ----------------------------------------------------------------------- Breaking Changes: @@ -93,8 +94,8 @@ Other Changes: This is provided for convenience and consistency with VtxOffset. - ImDrawCallback: Allow to override the signature of ImDrawCallback by #define-ing it. This is meant to facilitate custom rendering back-ends passing local render-specific data to the draw callback. -- ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. (#2545) - Combine with RasterizerFlags::MonoHinting for best results. +- ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. Combine + with RasterizerFlags::MonoHinting for best results. (#2545) [@HolyBlackCat] - ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not fully cleared. Fixed edge-case overflow when adding character 0xFFFF. (#2568). [@NIKE3500] - Demo: Added full "Dear ImGui" prefix to the title of "Dear ImGui Demo" and "Dear ImGui Metrics" windows. diff --git a/examples/README.txt b/examples/README.txt index 5cc27482..4f6dd61a 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.71 WIP + dear imgui, v1.71 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) @@ -104,7 +104,7 @@ List of Platforms Bindings in this repository: imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl back-ends) imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org imgui_impl_win32.cpp ; Win32 native API (Windows) - imgui_impl_glut.cpp ; GLUT/FreeGLUT (not recommended unless really miss the 90's) + imgui_impl_glut.cpp ; GLUT/FreeGLUT (absolutely not recommended in 2019) List of Renderer Bindings in this repository: diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 3e63dad0..764ea092 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -3,7 +3,7 @@ // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! -// !!! Prefer using GLFW Or SDL instead! +// !!! Nowadays, prefer using GLFW or SDL instead! #include "imgui.h" #include "../imgui_impl_glut.h" diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index 78b3c54a..6b800bf1 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -3,7 +3,7 @@ // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! -// !!! Prefer using GLFW or SDL instead! +// !!! Nowadays, prefer using GLFW or SDL instead! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I diff --git a/examples/imgui_impl_glut.h b/examples/imgui_impl_glut.h index c6fcfd07..506c3867 100644 --- a/examples/imgui_impl_glut.h +++ b/examples/imgui_impl_glut.h @@ -3,7 +3,7 @@ // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2019, you are being abused. Please show some resistance. !!! -// !!! Prefer using GLFW or SDL instead! +// !!! Nowadays, prefer using GLFW or SDL instead! // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I diff --git a/imconfig.h b/imconfig.h index 30ba7901..4d7adf5d 100644 --- a/imconfig.h +++ b/imconfig.h @@ -17,7 +17,8 @@ //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts -//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows. +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows +// Using dear imgui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. //#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllimport ) @@ -25,7 +26,7 @@ //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty) -//---- It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp. +// It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp. //#define IMGUI_DISABLE_DEMO_WINDOWS //---- Don't implement some functions to reduce linkage requirements. diff --git a/imgui.cpp b/imgui.cpp index 6290ebaf..72ea25e7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 WIP +// dear imgui, v1.71 // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index 4d272015..d5de1102 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.71 WIP +// dear imgui, v1.71 // (headers) // See imgui.cpp file for documentation. @@ -46,12 +46,13 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.71 WIP" -#define IMGUI_VERSION_NUM 17003 +#define IMGUI_VERSION "1.71" +#define IMGUI_VERSION_NUM 17100 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) // IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h) +// Using dear imgui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. #ifndef IMGUI_API #define IMGUI_API #endif @@ -1534,7 +1535,7 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { - // OBSOLETED in 1.71 (from May 2019) + // OBSOLETED in 1.71 (from June 2019) static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.70 (from May 2019) static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index edef9ebc..df875b23 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 WIP +// dear imgui, v1.71 // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 6e32995a..8d0c31de 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 WIP +// dear imgui, v1.71 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 98effed2..f82225e3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.71 WIP +// dear imgui, v1.71 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 11d348c9..698809b0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 WIP +// dear imgui, v1.71 // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index ae23bb1c..270cb32e 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.71 WIP +dear imgui, v1.71 (Font Readme) --------------------------------------- From 07d3083279834605131baf3bbdda18a4104647c8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 13 Jun 2019 10:19:14 +0200 Subject: [PATCH 430/566] Docking: Fixed rendering of outer decoration happening on non-visible docked window (#2623, #2109). Revealed by 0770449. We are actually better than before now, as previously those would get unnecessarily get rendered into a hidden draw list. --- imgui.cpp | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d59e1ae7..3918a576 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6181,24 +6181,29 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding); } + const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible; + // Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call. // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. // We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child. // We also disabled this when we have dimming overlay behind this specific one child. // FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected. - bool render_decorations_in_parent = false; - if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) - if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0) - render_decorations_in_parent = true; - if (render_decorations_in_parent) - window->DrawList = parent_window->DrawList; - - const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; - const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode))); - RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size); + if (is_undocked_or_docked_visible) + { + bool render_decorations_in_parent = false; + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) + if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0) + render_decorations_in_parent = true; + if (render_decorations_in_parent) + window->DrawList = parent_window->DrawList; - if (render_decorations_in_parent) - window->DrawList = &window->DrawListInst; + const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; + const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode))); + RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size); + + if (render_decorations_in_parent) + window->DrawList = &window->DrawListInst; + } // Draw navigation selection/windowing rectangle border if (g.NavWindowingTargetAnim == window) From 5286ecb8a796dd5236136d9983b9e3772b916609 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 14 Jun 2019 11:58:45 +0200 Subject: [PATCH 431/566] Version 1.72 WIP --- docs/CHANGELOG.txt | 5 +++++ examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 9 files changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d4f5badf..77bc65fa 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -29,6 +29,11 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.72 (In Progress) +----------------------------------------------------------------------- + + ----------------------------------------------------------------------- VERSION 1.71 (Released 2019-06-12) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 4f6dd61a..116ef6b5 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.71 + dear imgui, v1.72 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 72ea25e7..9d918e89 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 +// dear imgui, v1.72 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index d5de1102..fe12fec2 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.71 +// dear imgui, v1.71 WIP // (headers) // See imgui.cpp file for documentation. @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.71" -#define IMGUI_VERSION_NUM 17100 +#define IMGUI_VERSION "1.72 WIP" +#define IMGUI_VERSION_NUM 17101 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index df875b23..30dd5acb 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 +// dear imgui, v1.72 WIP // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8d0c31de..9f49abaf 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 +// dear imgui, v1.72 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index f82225e3..60787bcb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.71 +// dear imgui, v1.72 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 698809b0..03882993 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.71 +// dear imgui, v1.72 WIP // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index 270cb32e..010a7207 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.71 +dear imgui, v1.72 WIP (Font Readme) --------------------------------------- From af3080b81b4f931d4bf8c906f85a7444e035a328 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 14 Jun 2019 11:57:33 +0200 Subject: [PATCH 432/566] Removed redirecting functions/enums that were obsoleted in version 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. --- docs/CHANGELOG.txt | 8 ++++++++ imgui.cpp | 10 +++++++--- imgui.h | 16 ---------------- 3 files changed, 15 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 77bc65fa..0060217b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -33,6 +33,14 @@ HOW TO UPDATE? VERSION 1.72 (In Progress) ----------------------------------------------------------------------- +Breaking Changes: +- Removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): + - ImGuiCol_Column*, ImGuiSetCond_* enums. + - IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow() functions. + - IMGUI_ONCE_UPON_A_FRAME macro. + If you were still using the old names, read "API Breaking Changes" section of imgui.cpp to find out + the new names and equivalent. + ----------------------------------------------------------------------- VERSION 1.71 (Released 2019-06-12) diff --git a/imgui.cpp b/imgui.cpp index 9d918e89..a56500a3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,7 @@ CODE When you are not sure about a 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. + - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names. - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering. This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows. @@ -450,6 +451,9 @@ CODE - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting. + IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly) + IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior] - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead! - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete). @@ -460,10 +464,10 @@ CODE - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. - - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame. + - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. - - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete). - - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete). + - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete). + - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete). - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. diff --git a/imgui.h b/imgui.h index fe12fec2..769d2786 100644 --- a/imgui.h +++ b/imgui.h @@ -1068,7 +1068,6 @@ enum ImGuiCol_ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiCol_ModalWindowDarkening = ImGuiCol_ModalWindowDimBg // [renamed in 1.63] , ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg // [renamed in 1.53] - , ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive // [renamed in 1.51] //ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered, // [unused since 1.60+] the close button now uses regular button colors. //ImGuiCol_ComboBg, // [unused since 1.53+] ComboBg has been merged with PopupBg, so a redirect isn't accurate. #endif @@ -1187,11 +1186,6 @@ enum ImGuiCond_ ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) - - // Obsolete names (will be removed) -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing // [renamed in 1.51] -#endif }; //----------------------------------------------------------------------------- @@ -1565,11 +1559,6 @@ namespace ImGui static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); } - // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) - static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } - static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // This was misleading and partly broken. You probably want to use the ImGui::GetIO().WantCaptureMouse flag instead. - static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } - static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } } typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; @@ -1588,11 +1577,6 @@ struct ImGuiOnceUponAFrame operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; -// Helper: Macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf) // OBSOLETED in 1.51, will remove! -#endif - // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" struct ImGuiTextFilter { From 2645a2516f032332b68a66e20b3d2d8adc2490d0 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 14 Jun 2019 12:06:15 +0200 Subject: [PATCH 433/566] ImDrawList::ChannelsSplit(), ImDrawListSlitter: Fixed an issue with merging draw commands between channels 0 and 1. (#2624) Introduced by cef88f6aae52bf0e9e558ea5e30eca95676f439b. --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0060217b..cac9990d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,9 @@ Breaking Changes: If you were still using the old names, read "API Breaking Changes" section of imgui.cpp to find out the new names and equivalent. +Other Changes: +- ImDrawList::ChannelsSplit(), ImDrawListSlitter: Fixed an issue with merging draw commands between channel 0 and 1. (#2624) + ----------------------------------------------------------------------- VERSION 1.71 (Released 2019-06-12) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 9f49abaf..53fd4171 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1262,7 +1262,7 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; int new_idx_buffer_count = 0; - ImDrawCmd* last_cmd = (_Count > 0 && _Channels[0]._CmdBuffer.Size > 0) ? &_Channels[0]._CmdBuffer.back() : NULL; + ImDrawCmd* last_cmd = (_Count > 0 && draw_list->CmdBuffer.Size > 0) ? &draw_list->CmdBuffer.back() : NULL; int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0; for (int i = 1; i < _Count; i++) { From b82e99c0327456fdb14b7db1314314a8084696c9 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 17 Jun 2019 11:06:36 +0200 Subject: [PATCH 434/566] ImDrawList: Fixed CloneOutput() helper crashing. Also removed unnecessary risk from ImDrawList::Clear(), draw lists are being clear before use each frame anyway. (#1860) --- docs/CHANGELOG.txt | 3 ++- imgui_draw.cpp | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cac9990d..6ee2083a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,7 +42,8 @@ Breaking Changes: the new names and equivalent. Other Changes: -- ImDrawList::ChannelsSplit(), ImDrawListSlitter: Fixed an issue with merging draw commands between channel 0 and 1. (#2624) +- ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] +- ImDrawListSlitter, ImDrawList::ChannelsSplit(), : Fixed an issue with merging draw commands between channel 0 and 1. (#2624) ----------------------------------------------------------------------- diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 53fd4171..478819cc 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -365,7 +365,7 @@ void ImDrawList::Clear() CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); - Flags = _Data->InitialFlags; + Flags = _Data ? _Data->InitialFlags : ImDrawListFlags_None; _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; @@ -392,7 +392,7 @@ void ImDrawList::ClearFreeMemory() ImDrawList* ImDrawList::CloneOutput() const { - ImDrawList* dst = IM_NEW(ImDrawList(NULL)); + ImDrawList* dst = IM_NEW(ImDrawList(_Data)); dst->CmdBuffer = CmdBuffer; dst->IdxBuffer = IdxBuffer; dst->VtxBuffer = VtxBuffer; From ca43436cd395e52191d557800503852bd343c2ea Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 17 Jun 2019 11:19:34 +0200 Subject: [PATCH 435/566] Fix monitor dpi info not being copied to main viewport when multi-viewports are not enabled. (#2621, #1676) + Tweaks, short path in FindPlatformMonitorForRect(). --- imgui.cpp | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0e3ced31..b6b2a32c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10558,17 +10558,20 @@ static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 m return best_candidate; } +// Update viewports and monitor infos +// Note that this is runing even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. static void ImGui::UpdateViewportsNewFrame() { ImGuiContext& g = *GImGui; IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) - for (int n = 0; n < g.Viewports.Size; n++) + if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) { - ImGuiViewportP* viewport = g.Viewports[n]; - const bool platform_funcs_available = viewport->PlatformWindowCreated; - if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + for (int n = 0; n < g.Viewports.Size; n++) + { + ImGuiViewportP* viewport = g.Viewports[n]; + const bool platform_funcs_available = viewport->PlatformWindowCreated; if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) { bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); @@ -10577,6 +10580,7 @@ static void ImGui::UpdateViewportsNewFrame() else viewport->Flags &= ~ImGuiViewportFlags_Minimized; } + } } // Create/update main viewport with current platform position and size @@ -10593,10 +10597,10 @@ static void ImGui::UpdateViewportsNewFrame() g.MouseViewport = NULL; for (int n = 0; n < g.Viewports.Size; n++) { - // Erase unused viewports ImGuiViewportP* viewport = g.Viewports[n]; viewport->Idx = n; + // Erase unused viewports if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2) { // Clear references to this viewport in windows (window->ViewportId becomes the master data) @@ -10631,10 +10635,11 @@ static void ImGui::UpdateViewportsNewFrame() if (viewport->PlatformRequestResize) viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); } - - UpdateViewportPlatformMonitor(viewport); } + // Update/copy monitor info + UpdateViewportPlatformMonitor(viewport); + // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. viewport->Alpha = 1.0f; @@ -11102,11 +11107,15 @@ static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos) // Search for the monitor with the largest intersection area with the given rectangle // We generally try to avoid searching loops but the monitor count should be very small here -// FIXME-OPT: We could test the last monitor used for that viewport first.. +// FIXME-OPT: We could test the last monitor used for that viewport first, and early static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) { ImGuiContext& g = *GImGui; + const int monitor_count = g.PlatformIO.Monitors.Size; + if (monitor_count <= 1) + return monitor_count - 1; + // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position. // This is necessary for tooltips which always resize down to zero at first. const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); From e9b92d1cef0cea3e3d5520e03333efd8325e32c3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 17 Jun 2019 11:32:00 +0200 Subject: [PATCH 436/566] Disable -Wpragmas warning in GCC to avoid relying on version checks, as unusual/forks/mods don't appear to always have same warning<>version. (#2618) + Fix version number in imgui.h --- imgui.cpp | 6 +++--- imgui.h | 9 +++++---- imgui_demo.cpp | 5 ++--- imgui_draw.cpp | 5 ++--- imgui_internal.h | 5 ++--- imgui_widgets.cpp | 5 ++--- misc/freetype/imgui_freetype.cpp | 1 + 7 files changed, 17 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a56500a3..8eb37670 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1020,6 +1020,8 @@ CODE #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. #endif #elif defined(__GNUC__) +// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association. +#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 "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' @@ -1027,9 +1029,7 @@ CODE #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false -#if __GNUC__ >= 8 -#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead -#endif +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. diff --git a/imgui.h b/imgui.h index 769d2786..8131ac36 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.71 WIP +// dear imgui, v1.72 WIP // (headers) // See imgui.cpp file for documentation. @@ -83,9 +83,10 @@ Index of this file: #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif -#elif defined(__GNUC__) && __GNUC__ >= 8 +#elif defined(__GNUC__) #pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wclass-memaccess" +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif //----------------------------------------------------------------------------- @@ -2201,7 +2202,7 @@ struct ImFont #if defined(__clang__) #pragma clang diagnostic pop -#elif defined(__GNUC__) && __GNUC__ >= 8 +#elif defined(__GNUC__) #pragma GCC diagnostic pop #endif diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 30dd5acb..e4b89499 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -89,13 +89,12 @@ Index of this file: #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // #endif #elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value -#if (__GNUC__ >= 6) -#pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. -#endif +#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. #endif // Play it nice with Windows users. Notepad in 2017 still doesn't display text data with Unix-style \n. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 478819cc..288d95ae 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -72,13 +72,12 @@ Index of this file: #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. #endif #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 "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #pragma GCC diagnostic ignored "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer -#if __GNUC__ >= 8 -#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead -#endif +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif //------------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index 60787bcb..81f9bf9a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -56,9 +56,8 @@ Index of this file: #endif #elif defined(__GNUC__) #pragma GCC diagnostic push -#if __GNUC__ >= 8 -#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead -#endif +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif //----------------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 03882993..3490586b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -63,10 +63,9 @@ Index of this file: #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. #endif #elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked -#if __GNUC__ >= 8 -#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead -#endif +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif //------------------------------------------------------------------------- diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index a184d78b..d0d2580d 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -36,6 +36,7 @@ #endif #if 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 #endif From ae2c9f71014727b8f80f74adfc18e701fe173403 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Jun 2019 21:43:05 +0200 Subject: [PATCH 437/566] Internals: Columns: Poke into WorkRect and use them in the GetContentRegionMax() functions. This should be a no-op, but preparing us to transition toward using WorkRect instead of ContentRegionRect. Removed one use of ContentsRegionRect. --- imgui.cpp | 35 ++++++++++++++++++++++++----------- imgui_internal.h | 3 ++- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8eb37670..11bd76ea 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2249,8 +2249,8 @@ static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) ImGuiWindow* window = ImGui::GetCurrentWindow(); window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. - if (window->DC.CurrentColumns) - window->DC.CurrentColumns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly + if (ImGuiColumns* columns = window->DC.CurrentColumns) + columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 @@ -3423,7 +3423,7 @@ void ImGui::UpdateMouseWheel() const bool scroll_allowed = !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs); if (scroll_allowed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f) && !g.IO.KeyCtrl) { - ImVec2 max_step = (window->ContentsRegionRect.GetSize() + window->WindowPadding * 2.0f) * 0.67f; + ImVec2 max_step = window->InnerRect.GetSize() * 0.67f; // Vertical Mouse Wheel Scrolling (hold Shift to scroll horizontally) if (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) @@ -5872,7 +5872,7 @@ void ImGui::End() ImGuiWindow* window = g.CurrentWindow; - if (window->DC.CurrentColumns != NULL) + if (window->DC.CurrentColumns) EndColumns(); PopClipRect(); // Inner window clip rectangle @@ -6649,7 +6649,7 @@ ImVec2 ImGui::GetContentRegionMax() ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max - window->Pos; if (window->DC.CurrentColumns) - mx.x = GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x; + mx.x = window->WorkRect.Max.x - window->Pos.x; return mx; } @@ -6659,7 +6659,7 @@ ImVec2 ImGui::GetContentRegionMaxAbs() ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.CurrentColumns) - mx.x = window->Pos.x + GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x; + mx.x = window->WorkRect.Max.x; return mx; } @@ -6672,19 +6672,19 @@ ImVec2 ImGui::GetContentRegionAvail() // In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentsRegionRect.Min - window->Pos; } ImVec2 ImGui::GetWindowContentRegionMax() { - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentsRegionRect.Max - window->Pos; } float ImGui::GetWindowContentRegionWidth() { - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentsRegionRect.GetWidth(); } @@ -8655,7 +8655,13 @@ void ImGui::NextColumn() window->DC.CurrLineTextBaseOffset = 0.0f; PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? - PushItemWidth(GetColumnWidth() * 0.65f); // FIXME-COLUMNS: Move on columns setup + + // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; } int ImGui::GetColumnIndex() @@ -8851,6 +8857,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostClipRect = window->ClipRect; + columns->HostWorkRect = window->WorkRect; columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -8888,7 +8895,12 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag window->DrawList->ChannelsSetCurrent(1); PushColumnClipRect(0); } - PushItemWidth(GetColumnWidth() * 0.65f); + + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; } void ImGui::EndColumns() @@ -8960,6 +8972,7 @@ void ImGui::EndColumns() } columns->IsBeingResized = is_being_resized; + window->WorkRect = columns->HostWorkRect; window->DC.CurrentColumns = NULL; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); diff --git a/imgui_internal.h b/imgui_internal.h index 81f9bf9a..599f360f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -703,6 +703,7 @@ struct ImGuiColumns float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns() + ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns() ImVector Columns; ImGuiColumns() { Clear(); } @@ -1298,7 +1299,7 @@ struct IMGUI_API ImGuiWindow // The best way to understand what those rectangles are is to use the 'Metrics -> Tools -> Show windows rectangles' viewer. // The main 'OuterRect', omitted as a field, is window->Rect(). ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. - ImRect InnerRect; // Inner rectangle (omit title bar, menu bar) + ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar) ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect. ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentsRegionRect over time (from 1.71+ onward). ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). From 0e37eaff8ae78ca1508e3a7da7217aac30cb349e Mon Sep 17 00:00:00 2001 From: Pavel Rojtberg Date: Mon, 17 Jun 2019 15:17:24 +0200 Subject: [PATCH 438/566] Updated Ogre bindings (#2619) And support python --- docs/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/README.md b/docs/README.md index 5987c79a..241eaadd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -127,7 +127,7 @@ Languages: (third-party bindings) - Odin: [odin-dear_imgui](https://github.com/ThisDrunkDane/odin-dear_imgui) - Pascal: [imgui-pas](https://github.com/dpethes/imgui-pas) - PureBasic: [pb-cimgui](https://github.com/hippyau/pb-cimgui) -- Python: [pyimgui](https://github.com/swistakm/pyimgui) or [bimpy](https://github.com/podgorskiy/bimpy) +- Python: [pyimgui](https://github.com/swistakm/pyimgui) or [bimpy](https://github.com/podgorskiy/bimpy) or [ogre-imgui](https://github.com/OGRECave/ogre-imgui) - Ruby: [ruby-imgui](https://github.com/vaiorabbit/ruby-imgui) - Rust: [imgui-rs](https://github.com/Gekkio/imgui-rs) or [imgui-rust](https://github.com/nsf/imgui-rust) - Swift [swift-imgui](https://github.com/mnmly/Swift-imgui) @@ -142,7 +142,7 @@ Frameworks: - Flexium: [FlexGUI](https://github.com/DXsmiley/FlexGUI) - GML/GameMakerStudio2: [ImGuiGML](https://marketplace.yoyogames.com/assets/6221/imguigml) - Irrlicht: [IrrIMGUI](https://github.com/ZahlGraf/IrrIMGUI) -- Ogre: [ogreimgui](https://bitbucket.org/LMCrashy/ogreimgui/src) +- Ogre: [ogre-imgui](https://github.com/OGRECave/ogre-imgui) - OpenFrameworks: [ofxImGui](https://github.com/jvcleave/ofxImGui) - OpenSceneGraph/OSG: [gist](https://gist.github.com/fulezi/d2442ca7626bf270226014501357042c) - ORX: [ImGuiOrx](https://github.com/thegwydd/ImGuiOrx), [#1843](https://github.com/ocornut/imgui/pull/1843) From 342751c89e461530c4a0d3136c87cb80e10bd38e Mon Sep 17 00:00:00 2001 From: Vincent Hamm Date: Tue, 18 Jun 2019 01:55:33 -0700 Subject: [PATCH 439/566] Fiedx OpenGL ES 3.0 include for iOS and tvOS (#2631) --- examples/imgui_impl_opengl3.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 2bf4ea85..9585215c 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -77,7 +77,7 @@ // Auto-detect GL version #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) -#if (defined(__APPLE__) && TARGET_OS_IOS) || (defined(__ANDROID__)) +#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" #elif defined(__EMSCRIPTEN__) #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" @@ -87,7 +87,11 @@ #if defined(IMGUI_IMPL_OPENGL_ES2) #include #elif defined(IMGUI_IMPL_OPENGL_ES3) +#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) +#include // Use GL ES 3 +#else #include // Use GL ES 3 +#endif #else // About Desktop OpenGL function loaders: // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. From 70fe409338b00940d8c811494a0e993875fbc4f8 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 17 Jun 2019 17:03:54 +0200 Subject: [PATCH 440/566] Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). --- docs/CHANGELOG.txt | 1 + imgui.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ee2083a..d19dc530 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,7 @@ Breaking Changes: the new names and equivalent. Other Changes: +- Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawListSlitter, ImDrawList::ChannelsSplit(), : Fixed an issue with merging draw commands between channel 0 and 1. (#2624) diff --git a/imgui.cpp b/imgui.cpp index 11bd76ea..53289533 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5618,7 +5618,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize)); window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size); - window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.y * 0.5f), window->WindowBorderSize)); + window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize)); window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize); window->InnerClipRect.ClipWithFull(host_rect); From cc4d76cc239fbb3f2da8b1e00200a72470ef1ded Mon Sep 17 00:00:00 2001 From: Vincent Hamm Date: Sun, 16 Jun 2019 16:11:32 -0700 Subject: [PATCH 441/566] Implement SDL/dx11 sample --- .../example_sdl_directx11.vcxproj | 171 ++++++++++++++ .../example_sdl_directx11.vcxproj.filters | 57 +++++ examples/example_sdl_directx11/main.cpp | 220 ++++++++++++++++++ examples/imgui_impl_sdl.cpp | 8 + examples/imgui_impl_sdl.h | 1 + 5 files changed, 457 insertions(+) create mode 100644 examples/example_sdl_directx11/example_sdl_directx11.vcxproj create mode 100644 examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters create mode 100644 examples/example_sdl_directx11/main.cpp diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj new file mode 100644 index 00000000..ce1c5749 --- /dev/null +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -0,0 +1,171 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {9E1987E3-1F19-45CA-B9C9-D31E791836D8} + example_win32_directx11 + 8.1 + example_sdl_directx11 + + + + Application + true + Unicode + v140 + + + Application + true + Unicode + v140 + + + Application + false + true + Unicode + v140 + + + Application + false + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + + Level4 + Disabled + ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + + + true + SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x86 + Console + + + + + Level4 + Disabled + ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + + + true + SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x64 + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + false + + + true + true + true + SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x86 + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + false + + + true + true + true + SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x64 + Console + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters new file mode 100644 index 00000000..b2345067 --- /dev/null +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters @@ -0,0 +1,57 @@ + + + + + {0587d7a3-f2ce-4d56-b84f-a0005d3bfce6} + + + {08e36723-ce4f-4cff-9662-c40801cf1acf} + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + + + imgui + + + sources + + + imgui + + + imgui + + + sources + + + imgui + + + sources + + + + + + sources + + + \ No newline at end of file diff --git a/examples/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp new file mode 100644 index 00000000..bf470d78 --- /dev/null +++ b/examples/example_sdl_directx11/main.cpp @@ -0,0 +1,220 @@ +// dear imgui: standalone example application for SDL2 + OpenGL +// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) + +#include "imgui.h" +#include "imgui_impl_sdl.h" +#include "imgui_impl_dx11.h" +#include +#include +#include +#include + +// Data +static ID3D11Device* g_pd3dDevice = NULL; +static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; +static IDXGISwapChain* g_pSwapChain = NULL; +static ID3D11RenderTargetView* g_mainRenderTargetView = NULL; + +// Forward declarations of helper functions +bool CreateDeviceD3D(HWND hWnd); +void CleanupDeviceD3D(); +void CreateRenderTarget(); +void CleanupRenderTarget(); + +int main(int, char**) +{ + // Setup SDL + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) + { + printf("Error: %s\n", SDL_GetError()); + return -1; + } + + // Create window with graphics context + SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + + SDL_SysWMinfo wmInfo; + SDL_VERSION(&wmInfo.version); + SDL_GetWindowWMInfo(window, &wmInfo); + + HWND hwnd = (HWND)wmInfo.info.win.window; + + // Initialize Direct3D + if (!CreateDeviceD3D(hwnd)) + { + CleanupDeviceD3D(); + return 1; + } + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + + // Setup Platform/Renderer bindings + ImGui_ImplSDL2_InitForD3D(window); + ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Read 'misc/fonts/README.txt' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != NULL); + + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; + while (!done) + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL2_ProcessEvent(&event); + if (event.type == SDL_QUIT) + done = true; + if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) + done = true; + } + + // Start the Dear ImGui frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplSDL2_NewFrame(window); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL); + g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + g_pSwapChain->Present(1, 0); // Present with vsync + //g_pSwapChain->Present(0, 0); // Present without vsync + } + + // Cleanup + ImGui_ImplDX11_Shutdown(); + ImGui_ImplSDL2_Shutdown(); + ImGui::DestroyContext(); + + CleanupDeviceD3D(); + SDL_DestroyWindow(window); + SDL_Quit(); + + return 0; +} + +// Helper functions +bool CreateDeviceD3D(HWND hWnd) +{ + // Setup swap chain + DXGI_SWAP_CHAIN_DESC sd; + ZeroMemory(&sd, sizeof(sd)); + sd.BufferCount = 2; + sd.BufferDesc.Width = 0; + sd.BufferDesc.Height = 0; + sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd.BufferDesc.RefreshRate.Numerator = 60; + sd.BufferDesc.RefreshRate.Denominator = 1; + sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.OutputWindow = hWnd; + sd.SampleDesc.Count = 1; + sd.SampleDesc.Quality = 0; + sd.Windowed = TRUE; + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + UINT createDeviceFlags = 0; + //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + D3D_FEATURE_LEVEL featureLevel; + const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; + if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) + return false; + + CreateRenderTarget(); + return true; +} + +void CleanupDeviceD3D() +{ + CleanupRenderTarget(); + if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } + if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } +} + +void CreateRenderTarget() +{ + ID3D11Texture2D* pBackBuffer; + g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); + pBackBuffer->Release(); +} + +void CleanupRenderTarget() +{ + if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } +} diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 1922068e..0cf937a4 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -190,6 +190,14 @@ bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) return ImGui_ImplSDL2_Init(window); } +bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) +{ +#if !defined(_WIN32) + IM_ASSERT(0 && "Unsupported"); +#endif + return ImGui_ImplSDL2_Init(window); +} + void ImGui_ImplSDL2_Shutdown() { g_Window = NULL; diff --git a/examples/imgui_impl_sdl.h b/examples/imgui_impl_sdl.h index 39cc98e5..376e622c 100644 --- a/examples/imgui_impl_sdl.h +++ b/examples/imgui_impl_sdl.h @@ -21,6 +21,7 @@ typedef union SDL_Event SDL_Event; IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); From 516c3dee802d67c87487572a2d44d8e2d285efd6 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Jun 2019 11:28:26 +0200 Subject: [PATCH 442/566] Examples: SDL+DX11: Changelog, readme, batch files, fixed vcxproj, minor stylistic fixes + minor sync of other main.cpp files. (#2632) --- docs/CHANGELOG.txt | 6 +- examples/README.txt | 7 +++ examples/example_glfw_metal/main.mm | 1 + examples/example_glfw_opengl2/main.cpp | 1 + examples/example_glfw_opengl3/main.cpp | 1 + examples/example_glfw_vulkan/main.cpp | 1 + examples/example_glut_opengl2/main.cpp | 2 + examples/example_marmalade/main.cpp | 1 + .../example_sdl_directx11/build_win32.bat | 8 +++ .../example_sdl_directx11.vcxproj | 58 +++++++++++-------- examples/example_sdl_directx11/main.cpp | 19 +++--- examples/example_sdl_opengl2/main.cpp | 2 + examples/example_sdl_opengl3/main.cpp | 2 + examples/example_sdl_vulkan/main.cpp | 4 +- examples/example_win32_directx11/main.cpp | 1 + 15 files changed, 78 insertions(+), 36 deletions(-) create mode 100644 examples/example_sdl_directx11/build_win32.bat diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d19dc530..f575242f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,7 +44,11 @@ Breaking Changes: Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] -- ImDrawListSlitter, ImDrawList::ChannelsSplit(), : Fixed an issue with merging draw commands between channel 0 and 1. (#2624) +- ImDrawListSlitter, ImDrawList::ChannelsSplit(), : Fixed an issue with merging draw commands between + channel 0 and 1. (#2624) +- Backends: SDL2: Added dummy ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. + (#2482, #2632) [@josiahmanson] +- Examples: Added SDL2+DirectX11 example application. (#2632, #2612, #2482) [@vincenthamm] ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 116ef6b5..5028583b 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -201,6 +201,7 @@ example_glfw_vulkan/ GLFW (Win32, Mac, Linux) + Vulkan example. = main.cpp + imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp This is quite long and tedious, because: Vulkan. + For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. example_glut_opengl2/ GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2. @@ -217,6 +218,11 @@ example_null This is used to quickly test compilation of core imgui files in as many setups as possible. Because this application doesn't create a window nor a graphic context, there's no graphics output. +example_sdl_directx11/ + SDL2 + DirectX11 example, Windows only. + = main.cpp + imgui_impl_sdl.cpp + imgui_impl_dx11.cpp + This to demonstrate usage of DirectX with SDL. + example_sdl_opengl2/ SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline). = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp @@ -240,6 +246,7 @@ example_sdl_vulkan/ SDL2 (Win32, Mac, Linux, etc.) + Vulkan example. = main.cpp + imgui_impl_sdl.cpp + imgui_impl_vulkan.cpp This is quite long and tedious, because: Vulkan. + For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. example_win32_directx9/ DirectX9 example, Windows only. diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index 3b162afb..3a25a9de 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -74,6 +74,7 @@ int main(int, char**) MTLRenderPassDescriptor *renderPassDescriptor = [MTLRenderPassDescriptor new]; + // Our state bool show_demo_window = true; bool show_another_window = false; float clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f}; diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 57841ffa..0a7aa3c3 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -69,6 +69,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index dffd46c9..76174a1f 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -112,6 +112,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 2d1c4e00..fc3c1efb 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -440,6 +440,7 @@ int main(int, char**) ImGui_ImplVulkan_DestroyFontUploadObjects(); } + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 764ea092..75e48ca2 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -18,6 +18,7 @@ #pragma warning (disable: 4505) // unreferenced local function has been removed #endif +// Our state static bool show_demo_window = true; static bool show_another_window = false; static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); @@ -105,6 +106,7 @@ int main(int argc, char** argv) glutDisplayFunc(glut_display_func); // Setup Dear ImGui context + IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls diff --git a/examples/example_marmalade/main.cpp b/examples/example_marmalade/main.cpp index e844a4c9..27a4acd9 100644 --- a/examples/example_marmalade/main.cpp +++ b/examples/example_marmalade/main.cpp @@ -44,6 +44,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); diff --git a/examples/example_sdl_directx11/build_win32.bat b/examples/example_sdl_directx11/build_win32.bat new file mode 100644 index 00000000..8fc702bb --- /dev/null +++ b/examples/example_sdl_directx11/build_win32.bat @@ -0,0 +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_sdl_directx11 +set INCLUDES=/I.. /I..\.. /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" +set SOURCES=main.cpp ..\imgui_impl_sdl.cpp ..\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 +mkdir %OUT_DIR% +cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj index ce1c5749..e28a5d25 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -20,7 +20,7 @@ {9E1987E3-1F19-45CA-B9C9-D31E791836D8} - example_win32_directx11 + example_sdl_directx11 8.1 example_sdl_directx11 @@ -28,28 +28,28 @@ Application true - Unicode - v140 + MultiByte + v110 Application true - Unicode - v140 + MultiByte + v110 Application false true - Unicode - v140 + MultiByte + v110 Application false true - Unicode - v140 + MultiByte + v110 @@ -70,43 +70,49 @@ $(ProjectDir)$(Configuration)\ $(ProjectDir)$(Configuration)\ + $(IncludePath) $(ProjectDir)$(Configuration)\ $(ProjectDir)$(Configuration)\ + $(IncludePath) $(ProjectDir)$(Configuration)\ $(ProjectDir)$(Configuration)\ + $(IncludePath) $(ProjectDir)$(Configuration)\ $(ProjectDir)$(Configuration)\ + $(IncludePath) Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true + %SDL2_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x86 Console + msvcrt.lib Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true + %SDL2_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x64 Console + msvcrt.lib @@ -115,16 +121,18 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false true true true + %SDL2_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x86 Console + + @@ -133,25 +141,20 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories);$(SDL2_DIR)\include + ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false true true true + %SDL2_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;imm32.lib;%(AdditionalDependencies) - $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories);$(SDL2_DIR)\lib\x64 Console + + - - - - - - - @@ -161,6 +164,13 @@ + + + + + + + diff --git a/examples/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp index bf470d78..ae523fe9 100644 --- a/examples/example_sdl_directx11/main.cpp +++ b/examples/example_sdl_directx11/main.cpp @@ -1,4 +1,4 @@ -// dear imgui: standalone example application for SDL2 + OpenGL +// dear imgui: standalone example application for SDL2 + DirectX 11 // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) @@ -22,6 +22,7 @@ void CleanupDeviceD3D(); void CreateRenderTarget(); void CleanupRenderTarget(); +// Main code int main(int, char**) { // Setup SDL @@ -31,14 +32,12 @@ int main(int, char**) return -1; } - // Create window with graphics context + // Setup window SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); - - SDL_SysWMinfo wmInfo; - SDL_VERSION(&wmInfo.version); - SDL_GetWindowWMInfo(window, &wmInfo); - + SDL_SysWMinfo wmInfo; + SDL_VERSION(&wmInfo.version); + SDL_GetWindowWMInfo(window, &wmInfo); HWND hwnd = (HWND)wmInfo.info.win.window; // Initialize Direct3D @@ -52,10 +51,8 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - //io.ConfigViewportsNoAutoMerge = true; - //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); @@ -80,6 +77,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); @@ -168,6 +166,7 @@ int main(int, char**) } // Helper functions + bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index 7b3e853a..1222c250 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -13,6 +13,7 @@ #include #include +// Main code int main(int, char**) { // Setup SDL @@ -64,6 +65,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 38b9ebd5..ae1ef5b3 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -22,6 +22,7 @@ #include IMGUI_IMPL_OPENGL_LOADER_CUSTOM #endif +// Main code int main(int, char**) { // Setup SDL @@ -104,6 +105,7 @@ int main(int, char**) //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 6ac67b82..12c262e9 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -322,7 +322,7 @@ int main(int, char**) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); - return 1; + return -1; } // Setup window @@ -353,6 +353,7 @@ int main(int, char**) SetupVulkanWindow(wd, surface, w, h); // Setup Dear ImGui context + IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls @@ -423,6 +424,7 @@ int main(int, char**) ImGui_ImplVulkan_DestroyFontUploadObjects(); } + // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 9523728d..0a8f09b2 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -146,6 +146,7 @@ int main(int, char**) //g_pSwapChain->Present(0, 0); // Present without vsync } + // Cleanup ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); From dd41df3e98e85030bd478d0c68404667072ec5f1 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Jun 2019 12:50:34 +0200 Subject: [PATCH 443/566] Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). --- docs/CHANGELOG.txt | 2 ++ imgui_draw.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f575242f..d1e0b820 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Breaking Changes: Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). +- Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because + of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawListSlitter, ImDrawList::ChannelsSplit(), : Fixed an issue with merging draw commands between channel 0 and 1. (#2624) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 288d95ae..e54a5fdc 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2692,7 +2692,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c } // We ignore blank width at the end of the line (they can be skipped) - if (line_width + word_width >= wrap_width) + if (line_width + word_width > wrap_width) { // Words that cannot possibly fit within an entire line will be cut anywhere. if (word_width < wrap_width) From 2cbc0f128735e7c7e5fa6474698acbad47b11643 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Jun 2019 23:13:12 +0200 Subject: [PATCH 444/566] Restore SLN which in Docking branch includes more projects. --- examples/imgui_examples.sln | 60 +++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index d4c05ebc..d68f69ec 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -9,10 +9,22 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_directx10", " EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_directx11", "example_win32_directx11\example_win32_directx11.vcxproj", "{9F316E83-5AE5-4939-A723-305A94F48005}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_directx12", "example_win32_directx12\example_win32_directx12.vcxproj", "{B4CF9797-519D-4AFE-A8F4-5141A6B521D3}" +EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_glfw_opengl2", "example_glfw_opengl2\example_glfw_opengl2.vcxproj", "{9CDA7840-B7A5-496D-A527-E95571496D18}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_glfw_opengl3", "example_glfw_opengl3\example_glfw_opengl3.vcxproj", "{4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_glfw_vulkan", "example_glfw_vulkan\example_glfw_vulkan.vcxproj", "{57E2DF5A-6FC8-45BB-99DD-91A18C646E80}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl_opengl2", "example_sdl_opengl2\example_sdl_opengl2.vcxproj", "{2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl_opengl3", "example_sdl_opengl3\example_sdl_opengl3.vcxproj", "{BBAEB705-1669-40F3-8567-04CF6A991F4C}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl_vulkan", "example_sdl_vulkan\example_sdl_vulkan.vcxproj", "{BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl_directx11", "example_sdl_directx11\example_sdl_directx11.vcxproj", "{9E1987E3-1F19-45CA-B9C9-D31E791836D8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -45,6 +57,14 @@ Global {9F316E83-5AE5-4939-A723-305A94F48005}.Release|Win32.Build.0 = Release|Win32 {9F316E83-5AE5-4939-A723-305A94F48005}.Release|x64.ActiveCfg = Release|x64 {9F316E83-5AE5-4939-A723-305A94F48005}.Release|x64.Build.0 = Release|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|Win32.ActiveCfg = Debug|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|Win32.Build.0 = Debug|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|x64.ActiveCfg = Debug|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|x64.Build.0 = Debug|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|Win32.ActiveCfg = Release|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|Win32.Build.0 = Release|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|x64.ActiveCfg = Release|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|x64.Build.0 = Release|x64 {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.ActiveCfg = Debug|Win32 {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.Build.0 = Debug|Win32 {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|x64.ActiveCfg = Debug|x64 @@ -61,6 +81,46 @@ Global {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|Win32.Build.0 = Release|Win32 {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|x64.ActiveCfg = Release|x64 {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|x64.Build.0 = Release|x64 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Debug|Win32.ActiveCfg = Debug|Win32 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Debug|Win32.Build.0 = Debug|Win32 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Debug|x64.ActiveCfg = Debug|x64 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Debug|x64.Build.0 = Debug|x64 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Release|Win32.ActiveCfg = Release|Win32 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Release|Win32.Build.0 = Release|Win32 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Release|x64.ActiveCfg = Release|x64 + {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Release|x64.Build.0 = Release|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|Win32.ActiveCfg = Debug|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|Win32.Build.0 = Debug|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|x64.ActiveCfg = Debug|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|x64.Build.0 = Debug|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|Win32.ActiveCfg = Release|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|Win32.Build.0 = Release|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|x64.ActiveCfg = Release|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|x64.Build.0 = Release|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|Win32.ActiveCfg = Debug|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|Win32.Build.0 = Debug|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|x64.ActiveCfg = Debug|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|x64.Build.0 = Debug|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|Win32.ActiveCfg = Release|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|Win32.Build.0 = Release|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|x64.ActiveCfg = Release|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|x64.Build.0 = Release|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|Win32.ActiveCfg = Debug|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|Win32.Build.0 = Debug|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|x64.ActiveCfg = Debug|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|x64.Build.0 = Debug|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|Win32.ActiveCfg = Release|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|Win32.Build.0 = Release|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|x64.ActiveCfg = Release|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|x64.Build.0 = Release|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|Win32.ActiveCfg = Debug|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|Win32.Build.0 = Debug|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|x64.ActiveCfg = Debug|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|x64.Build.0 = Debug|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|Win32.ActiveCfg = Release|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|Win32.Build.0 = Release|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|x64.ActiveCfg = Release|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 3e8eebfbec4092b69009d7b0ca51eeace114a0a1 Mon Sep 17 00:00:00 2001 From: Vincent Hamm Date: Mon, 17 Jun 2019 21:03:00 -0700 Subject: [PATCH 445/566] Viewport: Added PlatformHandleRaw. Update SDL+DX11 example. (#1542, #2635) --- examples/imgui_impl_dx11.cpp | 8 +++++++- examples/imgui_impl_sdl.cpp | 10 ++++++++++ imgui.h | 3 ++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index e43a75af..b0aad0e1 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -564,7 +564,13 @@ static void ImGui_ImplDX11_CreateWindow(ImGuiViewport* viewport) ImGuiViewportDataDx11* data = IM_NEW(ImGuiViewportDataDx11)(); viewport->RendererUserData = data; - HWND hwnd = (HWND)viewport->PlatformHandle; + // When using SDL, PlatformHandleRaw will be the HWND (because PlatformHandle would be the SDL_Window) + // If not using SDL, PlatformHandleRaw will be null and PlatformHandle will contain the HWND + HWND hwnd = (HWND)viewport->PlatformHandleRaw; + if (hwnd == 0) + { + hwnd = (HWND)viewport->PlatformHandle; + } IM_ASSERT(hwnd != 0); // Create swap chain diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 27aa2017..e115e27f 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -456,6 +456,16 @@ static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport) if (use_opengl && backup_context) SDL_GL_MakeCurrent(data->Window, backup_context); viewport->PlatformHandle = (void*)data->Window; + +#if defined(_WIN32) + // save the window handle for render that needs it (directX) + SDL_SysWMinfo info; + SDL_VERSION(&info.version); + if (SDL_GetWindowWMInfo(data->Window, &info)) + { + viewport->PlatformHandleRaw = info.info.win.window; + } +#endif } static void ImGui_ImplSDL2_DestroyWindow(ImGuiViewport* viewport) diff --git a/imgui.h b/imgui.h index 75272220..be07f2fe 100644 --- a/imgui.h +++ b/imgui.h @@ -2399,11 +2399,12 @@ struct ImGuiViewport void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, frame-buffers etc.) void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context) void* PlatformHandle; // void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle such as HWND, GlfwWindow*, SDL_Window*) + void* PlatformHandleRaw; // void* to hold the platfor-native windows handle (e.g. the HWND) when using an abstraction layer like SDL (where PlatformHandle would be a SDL_Window*) bool PlatformRequestClose; // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4) bool PlatformRequestMove; // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position) bool PlatformRequestResize; // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size) - ImGuiViewport() { ID = 0; Flags = 0; DpiScale = 0.0f; DrawData = NULL; ParentViewportId = 0; RendererUserData = PlatformUserData = PlatformHandle = NULL; PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; } + ImGuiViewport() { ID = 0; Flags = 0; DpiScale = 0.0f; DrawData = NULL; ParentViewportId = 0; RendererUserData = PlatformUserData = PlatformHandle = PlatformHandleRaw = NULL; PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; } ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); } }; From adbbd17cb66f5a1635d209b55d8599fcad369e5f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Jun 2019 23:35:48 +0200 Subject: [PATCH 446/566] Addendum to #2635. Add support for multi-viewports in SDL+DX!! example. making all Win32-centric back-ends handle PlatformHandleRaw. Using the field to use/store the HWND for internal purpose in SDL/GLFW back-ends. (#1542) --- examples/example_sdl_directx11/main.cpp | 21 ++++++++++- examples/imgui_impl_dx10.cpp | 4 ++- examples/imgui_impl_dx11.cpp | 10 ++---- examples/imgui_impl_dx12.cpp | 7 ++-- examples/imgui_impl_dx12.h | 3 +- examples/imgui_impl_dx9.cpp | 8 +++-- examples/imgui_impl_glfw.cpp | 23 ++++++++----- examples/imgui_impl_sdl.cpp | 46 ++++++++++++------------- examples/imgui_impl_vulkan.cpp | 2 +- examples/imgui_impl_win32.cpp | 4 +-- imgui.h | 4 +-- 11 files changed, 79 insertions(+), 53 deletions(-) diff --git a/examples/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp index ae523fe9..3c7ee18e 100644 --- a/examples/example_sdl_directx11/main.cpp +++ b/examples/example_sdl_directx11/main.cpp @@ -51,13 +51,25 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking + io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows + //io.ConfigViewportsNoAutoMerge = true; + //io.ConfigViewportsNoTaskBarIcon = true; // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); + // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. + ImGuiStyle& style = ImGui::GetStyle(); + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + style.WindowRounding = 0.0f; + style.Colors[ImGuiCol_WindowBg].w = 1.0f; + } + // Setup Platform/Renderer bindings ImGui_ImplSDL2_InitForD3D(window); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); @@ -149,6 +161,13 @@ int main(int, char**) g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + // Update and Render additional Platform Windows + if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) + { + ImGui::UpdatePlatformWindows(); + ImGui::RenderPlatformWindowsDefault(); + } + g_pSwapChain->Present(1, 0); // Present with vsync //g_pSwapChain->Present(0, 0); // Present without vsync } diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index c5fdaeb4..cf1c1c44 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -553,7 +553,9 @@ static void ImGui_ImplDX10_CreateWindow(ImGuiViewport* viewport) ImGuiViewportDataDx10* data = IM_NEW(ImGuiViewportDataDx10)(); viewport->RendererUserData = data; - HWND hwnd = (HWND)viewport->PlatformHandle; + // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*). + // Some back-ends will leave PlatformHandleRaw NULL, in which case we assume PlatformHandle will contain the HWND. + HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle; IM_ASSERT(hwnd != 0); // Create swap chain diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index b0aad0e1..02236296 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -564,13 +564,9 @@ static void ImGui_ImplDX11_CreateWindow(ImGuiViewport* viewport) ImGuiViewportDataDx11* data = IM_NEW(ImGuiViewportDataDx11)(); viewport->RendererUserData = data; - // When using SDL, PlatformHandleRaw will be the HWND (because PlatformHandle would be the SDL_Window) - // If not using SDL, PlatformHandleRaw will be null and PlatformHandle will contain the HWND - HWND hwnd = (HWND)viewport->PlatformHandleRaw; - if (hwnd == 0) - { - hwnd = (HWND)viewport->PlatformHandle; - } + // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*). + // Some back-end will leave PlatformHandleRaw NULL, in which case we assume PlatformHandle will contain the HWND. + HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle; IM_ASSERT(hwnd != 0); // Create swap chain diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 7dfdb9c6..04b27113 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -4,7 +4,8 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. -// Issues: +// Missing features, issues: +// [ ] Renderer: Missing multi-viewport support. // [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See github.com/ocornut/imgui/pull/301 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. @@ -680,7 +681,9 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) /* // FIXME-PLATFORM - HWND hwnd = (HWND)viewport->PlatformHandle; + // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*). + // Some back-ends will leave PlatformHandleRaw NULL, in which case we assume PlatformHandle will contain the HWND. + HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle; IM_ASSERT(hwnd != 0); // Create swap chain diff --git a/examples/imgui_impl_dx12.h b/examples/imgui_impl_dx12.h index 8ae75e53..cf34c144 100644 --- a/examples/imgui_impl_dx12.h +++ b/examples/imgui_impl_dx12.h @@ -4,7 +4,8 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. -// Issues: +// Missing features, issues: +// [ ] Renderer: Missing multi-viewport support. // [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See github.com/ocornut/imgui/pull/301 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index a8635fe0..2c22885e 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -319,8 +319,10 @@ static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport) ImGuiViewportDataDx9* data = IM_NEW(ImGuiViewportDataDx9)(); viewport->RendererUserData = data; - HWND hWnd = (HWND)viewport->PlatformHandle; - IM_ASSERT(hWnd != 0); + // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*). + // Some back-ends will leave PlatformHandleRaw NULL, in which case we assume PlatformHandle will contain the HWND. + HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle; + IM_ASSERT(hwnd != 0); ZeroMemory(&data->d3dpp, sizeof(D3DPRESENT_PARAMETERS)); data->d3dpp.Windowed = TRUE; @@ -328,7 +330,7 @@ static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport) data->d3dpp.BackBufferWidth = (UINT)viewport->Size.x; data->d3dpp.BackBufferHeight = (UINT)viewport->Size.y; data->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; - data->d3dpp.hDeviceWindow = hWnd; + data->d3dpp.hDeviceWindow = hwnd; data->d3dpp.EnableAutoDepthStencil = FALSE; data->d3dpp.AutoDepthStencilFormat = D3DFMT_D16; data->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 21da2f69..c4b60217 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -202,6 +202,9 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Our mouse update function expect PlatformHandle to be filled for the main viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->PlatformHandle = (void*)g_Window; +#ifdef _WIN32 + main_viewport->PlatformHandleRaw = glfwGetWin32Window(g_Window); +#endif if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui_ImplGlfw_InitPlatformInterface(); @@ -444,6 +447,9 @@ static void ImGui_ImplGlfw_CreateWindow(ImGuiViewport* viewport) data->Window = glfwCreateWindow((int)viewport->Size.x, (int)viewport->Size.y, "No Title Yet", NULL, share_window); data->WindowOwned = true; viewport->PlatformHandle = (void*)data->Window; +#ifdef _WIN32 + viewport->PlatformHandleRaw = glfwGetWin32Window(data->Window); +#endif glfwSetWindowPos(data->Window, (int)viewport->Pos.x, (int)viewport->Pos.y); // Install callbacks for secondary viewports @@ -468,7 +474,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) if (data->WindowOwned) { #if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) - HWND hwnd = glfwGetWin32Window(data->Window); + HWND hwnd = (HWND)viewport->PlatformHandleRaw; ::RemovePropA(hwnd, "IMGUI_VIEWPORT"); #endif glfwDestroyWindow(data->Window); @@ -504,7 +510,7 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) #if defined(_WIN32) // GLFW hack: Hide icon from task bar - HWND hwnd = glfwGetWin32Window(data->Window); + HWND hwnd = (HWND)viewport->PlatformHandleRaw; if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); @@ -633,13 +639,12 @@ static void ImGui_ImplGlfw_SwapBuffers(ImGuiViewport* viewport, void*) static void ImGui_ImplWin32_SetImeInputPos(ImGuiViewport* viewport, ImVec2 pos) { COMPOSITIONFORM cf = { CFS_FORCE_POSITION, { (LONG)(pos.x - viewport->Pos.x), (LONG)(pos.y - viewport->Pos.y) }, { 0, 0, 0, 0 } }; - if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData) - if (HWND hwnd = glfwGetWin32Window(data->Window)) - if (HIMC himc = ::ImmGetContext(hwnd)) - { - ::ImmSetCompositionWindow(himc, &cf); - ::ImmReleaseContext(hwnd, himc); - } + if (HWND hwnd = (HWND)viewport->PlatformHandleRaw) + if (HIMC himc = ::ImmGetContext(hwnd)) + { + ::ImmSetCompositionWindow(himc, &cf); + ::ImmReleaseContext(hwnd, himc); + } } #else #define HAS_WIN32_IME 0 diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index e115e27f..3ee2b82e 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -200,6 +200,12 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, void* sdl_gl_context) // Our mouse update function expect PlatformHandle to be filled for the main viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->PlatformHandle = (void*)window; +#if defined(_WIN32) + SDL_SysWMinfo info; + SDL_VERSION(&info.version); + if (SDL_GetWindowWMInfo(window, &info)) + main_viewport->PlatformHandleRaw = info.info.win.window; +#endif // We need SDL_CaptureMouse(), SDL_GetGlobalMouseState() from SDL 2.0.4+ to support multiple viewports. // We left the call to ImGui_ImplSDL2_InitPlatformInterface() outside of #ifdef to avoid unused-function warnings. @@ -455,16 +461,13 @@ static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport) } if (use_opengl && backup_context) SDL_GL_MakeCurrent(data->Window, backup_context); - viewport->PlatformHandle = (void*)data->Window; + viewport->PlatformHandle = (void*)data->Window; #if defined(_WIN32) - // save the window handle for render that needs it (directX) SDL_SysWMinfo info; SDL_VERSION(&info.version); if (SDL_GetWindowWMInfo(data->Window, &info)) - { viewport->PlatformHandleRaw = info.info.win.window; - } #endif } @@ -487,28 +490,23 @@ static void ImGui_ImplSDL2_ShowWindow(ImGuiViewport* viewport) { ImGuiViewportDataSDL2* data = (ImGuiViewportDataSDL2*)viewport->PlatformUserData; #if defined(_WIN32) - SDL_SysWMinfo info; - SDL_VERSION(&info.version); - if (SDL_GetWindowWMInfo(data->Window, &info)) - { - HWND hwnd = info.info.win.window; + HWND hwnd = (HWND)viewport->PlatformHandleRaw; - // SDL hack: Hide icon from task bar - // Note: SDL 2.0.6+ has a SDL_WINDOW_SKIP_TASKBAR flag which is supported under Windows but the way it create the window breaks our seamless transition. - if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) - { - LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); - ex_style &= ~WS_EX_APPWINDOW; - ex_style |= WS_EX_TOOLWINDOW; - ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); - } + // SDL hack: Hide icon from task bar + // Note: SDL 2.0.6+ has a SDL_WINDOW_SKIP_TASKBAR flag which is supported under Windows but the way it create the window breaks our seamless transition. + if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) + { + LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); + ex_style &= ~WS_EX_APPWINDOW; + ex_style |= WS_EX_TOOLWINDOW; + ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); + } - // SDL hack: SDL always activate/focus windows :/ - if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) - { - ::ShowWindow(hwnd, SW_SHOWNA); - return; - } + // SDL hack: SDL always activate/focus windows :/ + if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) + { + ::ShowWindow(hwnd, SW_SHOWNA); + return; } #endif diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 16d2f4b6..74d111ea 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -3,8 +3,8 @@ // Implemented features: // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bits indices. +// [x] Platform: Multi-viewport / platform windows. With issues (flickering when creating a new viewport). // Missing features: -// [ ] Platform: Multi-viewport / platform windows. // [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index e1ae9730..d1a42a2f 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -73,7 +73,7 @@ bool ImGui_ImplWin32_Init(void* hwnd) // Our mouse update function expect PlatformHandle to be filled for the main viewport g_hWnd = (HWND)hwnd; ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - main_viewport->PlatformHandle = (void*)g_hWnd; + main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)g_hWnd; if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) ImGui_ImplWin32_InitPlatformInterface(); @@ -547,7 +547,7 @@ static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport) parent_window, NULL, ::GetModuleHandle(NULL), NULL); // Parent window, Menu, Instance, Param data->HwndOwned = true; viewport->PlatformRequestResize = false; - viewport->PlatformHandle = data->Hwnd; + viewport->PlatformHandle = viewport->PlatformHandleRaw = data->Hwnd; } static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport) diff --git a/imgui.h b/imgui.h index be07f2fe..b4539b46 100644 --- a/imgui.h +++ b/imgui.h @@ -2398,8 +2398,8 @@ struct ImGuiViewport void* RendererUserData; // void* to hold custom data structure for the renderer (e.g. swap chain, frame-buffers etc.) void* PlatformUserData; // void* to hold custom data structure for the OS / platform (e.g. windowing info, render context) - void* PlatformHandle; // void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle such as HWND, GlfwWindow*, SDL_Window*) - void* PlatformHandleRaw; // void* to hold the platfor-native windows handle (e.g. the HWND) when using an abstraction layer like SDL (where PlatformHandle would be a SDL_Window*) + void* PlatformHandle; // void* for FindViewportByPlatformHandle(). (e.g. suggested to use natural platform handle such as HWND, GLFWWindow*, SDL_Window*) + void* PlatformHandleRaw; // void* to hold low-level, platform-native window handle (e.g. the HWND) when using an abstraction layer like GLFW or SDL (where PlatformHandle would be a SDL_Window*) bool PlatformRequestClose; // Platform window requested closure (e.g. window was moved by the OS / host window manager, e.g. pressing ALT-F4) bool PlatformRequestMove; // Platform window requested move (e.g. window was moved by the OS / host window manager, authoritative position will be OS window position) bool PlatformRequestResize; // Platform window requested resize (e.g. window was resized by the OS / host window manager, authoritative size will be OS window size) From f563e1a50451fb1a61fd34a3d8c02b95dc983a94 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 19 Jun 2019 18:14:24 +0200 Subject: [PATCH 447/566] Internals: Renamed GetFrontMostPopupModal() to GetTopMostPopupModal() to be consistent. Renamed other locals to follow that terminology. --- imgui.cpp | 36 ++++++++++++++++++------------------ imgui.h | 6 +++--- imgui_internal.h | 4 ++-- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 53289533..0df747f8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3298,7 +3298,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; } - else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL) + else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { // Clicking on void disable focus FocusWindow(NULL); @@ -3310,9 +3310,9 @@ void ImGui::UpdateMouseMovingWindowEndFrame() // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger) if (g.IO.MouseClicked[1]) { - // Find the top-most window between HoveredWindow and the front most Modal Window. + // Find the top-most window between HoveredWindow and the top-most Modal Window. // This is where we can trim the popup stack. - ImGuiWindow* modal = GetFrontMostPopupModal(); + ImGuiWindow* modal = GetTopMostPopupModal(); bool hovered_window_above_modal = false; if (modal == NULL) hovered_window_above_modal = true; @@ -3458,7 +3458,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() FindHoveredWindow(); // Modal windows prevents cursor from hovering behind them. - ImGuiWindow* modal_window = GetFrontMostPopupModal(); + ImGuiWindow* modal_window = GetTopMostPopupModal(); if (modal_window) if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) g.HoveredRootWindow = g.HoveredWindow = NULL; @@ -3654,7 +3654,7 @@ void ImGui::NewFrame() UpdateMouseMovingWindowNewFrame(); // Background darkening/whitening - if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) + if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f); else g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f); @@ -4062,18 +4062,18 @@ void ImGui::Render() if (!g.BackgroundDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList); - ImGuiWindow* windows_to_render_front_most[2]; - windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; - windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL; + ImGuiWindow* windows_to_render_top_most[2]; + windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; + windows_to_render_top_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL; for (int n = 0; n != g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; - if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1]) + if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1]) AddRootWindowToDrawData(window); } - for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++) - if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window - AddRootWindowToDrawData(windows_to_render_front_most[n]); + for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++) + if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window + AddRootWindowToDrawData(windows_to_render_top_most[n]); g.DrawDataBuilder.FlattenIntoSingleLayer(); // Draw software mouse cursor if requested @@ -5648,7 +5648,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) PushClipRect(host_rect.Min, host_rect.Max, false); // Draw modal window background (darkens what is behind them, all viewports) - const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0; + const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0; const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow); if (dim_bg_for_modal || dim_bg_for_window_list) { @@ -5893,7 +5893,7 @@ void ImGui::BringWindowToFocusFront(ImGuiWindow* window) ImGuiContext& g = *GImGui; if (g.WindowsFocusOrder.back() == window) return; - for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the front most window + for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window if (g.WindowsFocusOrder[i] == window) { memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*)); @@ -5908,7 +5908,7 @@ void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) ImGuiWindow* current_front_window = g.Windows.back(); if (current_front_window == window || current_front_window->RootWindow == window) return; - for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window + for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window if (g.Windows[i] == window) { memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*)); @@ -7178,7 +7178,7 @@ bool ImGui::IsPopupOpen(const char* str_id) return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); } -ImGuiWindow* ImGui::GetFrontMostPopupModal() +ImGuiWindow* ImGui::GetTopMostPopupModal() { ImGuiContext& g = *GImGui; for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) @@ -8435,7 +8435,7 @@ static void ImGui::NavUpdateWindowing() ImGuiWindow* apply_focus_window = NULL; bool apply_toggle_layer = false; - ImGuiWindow* modal_window = GetFrontMostPopupModal(); + ImGuiWindow* modal_window = GetTopMostPopupModal(); if (modal_window != NULL) { g.NavWindowingTarget = NULL; @@ -8477,7 +8477,7 @@ static void ImGui::NavUpdateWindowing() g.NavWindowingHighlightAlpha = 1.0f; } - // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most) + // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) if (!IsNavInputDown(ImGuiNavInput_Menu)) { g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. diff --git a/imgui.h b/imgui.h index 8131ac36..32b267e2 100644 --- a/imgui.h +++ b/imgui.h @@ -275,17 +275,17 @@ namespace ImGui IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints. IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() - IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). - IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state - IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus. // Content region // - Those functions are bound to be redesigned soon (they are confusing, incomplete and return values in local window coordinates which increases confusion) diff --git a/imgui_internal.h b/imgui_internal.h index 599f360f..67ee3b4d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -919,7 +919,7 @@ struct ImGuiContext ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard. ImRect NavScoringRectScreen; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring. int NavScoringCount; // Metrics for debugging - ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed front-most. + ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed top-most. ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f ImGuiWindow* NavWindowingList; float NavWindowingTimer; @@ -1520,7 +1520,7 @@ namespace ImGui IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id within current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true); - IMGUI_API ImGuiWindow* GetFrontMostPopupModal(); + IMGUI_API ImGuiWindow* GetTopMostPopupModal(); IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default); From 41e2d4b5ae156462fc1c74c3c0d7fd1525da3b62 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 20 Jun 2019 16:09:31 +0200 Subject: [PATCH 448/566] ImDrawListSplitter: Fixed memory leak when using low-level split api (was not affecting ImDrawList api, also this type was added in 1.71 and not advertised as a public-facing feature). --- docs/CHANGELOG.txt | 4 +++- imgui.h | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d1e0b820..6d747304 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,8 +46,10 @@ Other Changes: - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] -- ImDrawListSlitter, ImDrawList::ChannelsSplit(), : Fixed an issue with merging draw commands between +- ImDrawList::ChannelsSplit(), ImDrawListSplitter: Fixed an issue with merging draw commands between channel 0 and 1. (#2624) +- ImDrawListSplitter: Fixed memory leak when using low-level split api (was not affecting ImDrawList api, + also this type was added in 1.71 and not advertised as a public-facing feature). - Backends: SDL2: Added dummy ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. (#2482, #2632) [@josiahmanson] - Examples: Added SDL2+DirectX11 example application. (#2632, #2612, #2482) [@vincenthamm] diff --git a/imgui.h b/imgui.h index 32b267e2..101f4249 100644 --- a/imgui.h +++ b/imgui.h @@ -1822,7 +1822,8 @@ struct ImDrawListSplitter int _Count; // Number of active channels (1+) ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) - inline ImDrawListSplitter() { Clear(); } + inline ImDrawListSplitter() { Clear(); } + inline ~ImDrawListSplitter() { ClearFreeMemory(); } inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame IMGUI_API void ClearFreeMemory(); IMGUI_API void Split(ImDrawList* draw_list, int count); From eb3e271c24c25f668be02bbf25aeb46a46b9fc08 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 21 Jun 2019 19:38:33 +0200 Subject: [PATCH 449/566] Demo: Using ImVec2(-FLT_MIN,0.0f) instead of ImVec2(-1.0f,0.0f) where it makes sense. (#2449) --- imgui_demo.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e4b89499..80c57771 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -968,7 +968,7 @@ static void ShowDemoWindowWidgets() ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly); ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput); ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine); - ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), flags); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); ImGui::TreePop(); } @@ -1024,7 +1024,7 @@ static void ShowDemoWindowWidgets() static ImVector my_str; if (my_str.empty()) my_str.push_back(0); - Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16)); + Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16)); ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity()); ImGui::TreePop(); } @@ -1085,7 +1085,8 @@ static void ShowDemoWindowWidgets() if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } } - // Typically we would use ImVec2(-1.0f,0.0f) to use all available width, or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width, + // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f)); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::Text("Progress Bar"); @@ -1727,7 +1728,7 @@ static void ShowDemoWindowLayout() { char buf[32]; sprintf(buf, "%03d", i); - ImGui::Button(buf, ImVec2(-1.0f, 0.0f)); + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); ImGui::NextColumn(); } ImGui::EndChild(); @@ -2519,7 +2520,7 @@ static void ShowDemoWindowColumns() char label[32]; sprintf(label, "Item %d", n); if (ImGui::Selectable(label)) {} - //if (ImGui::Button(label, ImVec2(-1,0))) {} + //if (ImGui::Button(label, ImVec2(-FLT_MIN,0.0f))) {} ImGui::NextColumn(); } ImGui::Columns(1); @@ -2570,7 +2571,7 @@ static void ShowDemoWindowColumns() ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); ImGui::Text("Long text that is likely to clip"); - ImGui::Button("Button", ImVec2(-1.0f, 0.0f)); + ImGui::Button("Button", ImVec2(-FLT_MIN, 0.0f)); ImGui::NextColumn(); } ImGui::Columns(1); From 50d421fa19c992301c9e401ef59b6b7de58c446a Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 26 Jun 2019 09:52:25 +0200 Subject: [PATCH 450/566] Docking: Fixed GetBackgroundDrawList(), GetForegroundDrawList() overwriting ImDrawList flags after clear, leading to the AllowVtxOffset flag not being cleared. (#2638) --- imgui.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 2173564b..54e96ae2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3285,7 +3285,6 @@ static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist draw_list->Clear(); draw_list->PushTextureID(g.IO.Fonts->TexID); draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false); - draw_list->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); viewport->LastFrameDrawLists[drawlist_no] = g.FrameCount; } return draw_list; From 4b95e7c2f3d5793bf73c7e8b4c130696010d2f19 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 26 Jun 2019 12:15:32 +0200 Subject: [PATCH 451/566] Doc: Tweak and extra mention of AddCustomRectFontGlyph + made the example register two rectangles. --- imgui.cpp | 2 ++ misc/fonts/README.txt | 22 ++++++++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0df747f8..79c2de90 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -844,6 +844,8 @@ CODE main font. Then you can refer to icons within your strings. You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment. (Read the 'misc/fonts/README.txt' file for more details about icons font loading.) + With some extra effort, you may use colorful icon by registering custom rectangle space inside the font atlas, + and copying your own graphics data into it. See misc/fonts/README.txt about using the AddCustomRectFontGlyph API. Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index 010a7207..cf953cf6 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -212,9 +212,11 @@ texture, and blit/copy any graphics data of your choice into those rectangles. Pseudo-code: - // Add font, then register one custom 13x13 rectangle mapped to glyph 'a' of this font + // Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font ImFont* font = io.Fonts->AddFontDefault(); - int rect_id = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1); + int rect_ids[2]; + rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1); + rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1); // Build atlas io.Fonts->Build(); @@ -224,14 +226,18 @@ Pseudo-code: int tex_width, tex_height; io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); - // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here) - if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) + for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) { - for (int y = 0; y < rect->Height; y++) + int rect_id = rects_ids[rect_n]; + if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) { - ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X); - for (int x = rect->Width; x > 0; x--) - *p++ = IM_COL32(255, 0, 0, 255); + // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!) + for (int y = 0; y < rect->Height; y++) + { + ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X); + for (int x = rect->Width; x > 0; x--) + *p++ = IM_COL32(255, 0, 0, 255); + } } } From 1dd322c6fb700242b156f898862ec098fa88b633 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 27 Jun 2019 12:20:18 +0200 Subject: [PATCH 452/566] Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6d747304..bff027d3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). +- Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawList::ChannelsSplit(), ImDrawListSplitter: Fixed an issue with merging draw commands between channel 0 and 1. (#2624) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e54a5fdc..7b20f2b1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -260,7 +260,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); - colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 0.60f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f); @@ -316,7 +316,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f); colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); - colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); + colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 0.62f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f); From 82711251b66a30b63a815ec6f9519c2cb6914cce Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 27 Jun 2019 18:03:19 +0200 Subject: [PATCH 453/566] Internals: ImGuiListClipper using absolute coordinate (instead of relative one). Minor no-op tweaks + ImDrawListSplitter assert --- imgui.cpp | 31 ++++++++++++++++++++----------- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 79c2de90..6096f510 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2239,7 +2239,8 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) //----------------------------------------------------------------------------- // [SECTION] ImGuiListClipper -// This is currently not as flexible/powerful as it should be, needs some rework (see TODO) +// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed +// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO) //----------------------------------------------------------------------------- static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) @@ -2247,12 +2248,14 @@ static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. // The clipper should probably have a 4th step to display the last item in a regular manner. - ImGui::SetCursorPosY(pos_y); - ImGuiWindow* window = ImGui::GetCurrentWindow(); - window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. - window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + window->DC.CursorPos.y = pos_y; + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. + window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. if (ImGuiColumns* columns = window->DC.CurrentColumns) - columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly + columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 @@ -2260,7 +2263,10 @@ static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. void ImGuiListClipper::Begin(int count, float items_height) { - StartPosY = ImGui::GetCursorPosY(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + StartPosY = window->DC.CursorPos.y; ItemsHeight = items_height; ItemsCount = count; StepNo = 0; @@ -2287,7 +2293,10 @@ void ImGuiListClipper::End() bool ImGuiListClipper::Step() { - if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (ItemsCount == 0 || window->SkipItems) { ItemsCount = -1; return false; @@ -2296,16 +2305,16 @@ bool ImGuiListClipper::Step() { DisplayStart = 0; DisplayEnd = 1; - StartPosY = ImGui::GetCursorPosY(); + StartPosY = window->DC.CursorPos.y; StepNo = 1; return true; } if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. { if (ItemsCount == 1) { ItemsCount = -1; return false; } - float items_height = ImGui::GetCursorPosY() - StartPosY; + float items_height = window->DC.CursorPos.y - StartPosY; IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically - Begin(ItemsCount-1, items_height); + Begin(ItemsCount - 1, items_height); DisplayStart++; DisplayEnd++; StepNo = 3; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 80c57771..afd2b894 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4022,7 +4022,7 @@ static void ShowExampleAppLongText(bool* p_open) static ImGuiTextBuffer log; static int lines = 0; ImGui::Text("Printing unusually long amount of text."); - ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped (slow)\0"); + ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped\0Multiple calls to Text(), not clipped (slow)\0"); ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); if (ImGui::Button("Clear")) { log.clear(); lines = 0; } ImGui::SameLine(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7b20f2b1..51ff2cd9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1304,7 +1304,7 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) { - IM_ASSERT(idx < _Count); + IM_ASSERT(idx >= 0 && idx < _Count); if (_Current == idx) return; // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap() From 401e05147cedbe50dd150b46f1a323e622929a9a Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 29 Jun 2019 18:55:06 +0200 Subject: [PATCH 454/566] Internals: Moved CalcListClipping close to ImGuiListClipper code (no-op) --- imgui.cpp | 82 +++++++++++++++++++++++++++---------------------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6096f510..10538602 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2243,6 +2243,47 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO) //----------------------------------------------------------------------------- +// Helper to calculate coarse clipping of large list of evenly sized items. +// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. +// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX +void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (g.LogEnabled) + { + // If logging is active, do not perform any clipping + *out_items_display_start = 0; + *out_items_display_end = items_count; + return; + } + if (window->SkipItems) + { + *out_items_display_start = *out_items_display_end = 0; + return; + } + + // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect + ImRect unclipped_rect = window->ClipRect; + if (g.NavMoveRequest) + unclipped_rect.Add(g.NavScoringRectScreen); + + const ImVec2 pos = window->DC.CursorPos; + int start = (int)((unclipped_rect.Min.y - pos.y) / items_height); + int end = (int)((unclipped_rect.Max.y - pos.y) / items_height); + + // When performing a navigation request, ensure we have one item extra in the direction we are moving to + if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up) + start--; + if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down) + end++; + + start = ImClamp(start, 0, items_count); + end = ImClamp(end + 1, start, items_count); + *out_items_display_start = start; + *out_items_display_end = end; +} + static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) { // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. @@ -4130,47 +4171,6 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex return text_size; } -// Helper to calculate coarse clipping of large list of evenly sized items. -// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. -// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX -void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - if (g.LogEnabled) - { - // If logging is active, do not perform any clipping - *out_items_display_start = 0; - *out_items_display_end = items_count; - return; - } - if (window->SkipItems) - { - *out_items_display_start = *out_items_display_end = 0; - return; - } - - // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect - ImRect unclipped_rect = window->ClipRect; - if (g.NavMoveRequest) - unclipped_rect.Add(g.NavScoringRectScreen); - - const ImVec2 pos = window->DC.CursorPos; - int start = (int)((unclipped_rect.Min.y - pos.y) / items_height); - int end = (int)((unclipped_rect.Max.y - pos.y) / items_height); - - // When performing a navigation request, ensure we have one item extra in the direction we are moving to - if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up) - start--; - if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down) - end++; - - start = ImClamp(start, 0, items_count); - end = ImClamp(end + 1, start, items_count); - *out_items_display_start = start; - *out_items_display_end = end; -} - // Find window given position, search front-to-back // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is From a89f05a10e80fc25f64dc32f0feff164bb1ede27 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 27 Jun 2019 16:35:56 +0200 Subject: [PATCH 455/566] Child windows inherit Hidden frames setting from parent more accurately, so HiddenFramesCannotSkipItems is honored by child windows. --- imgui.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 10538602..5f402f74 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5832,9 +5832,11 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) window->HiddenFramesCanSkipItems = 1; - // Completely hide along with parent or if parent is collapsed - if (parent_window && (parent_window->Collapsed || parent_window->Hidden)) + // Hide along with parent or if parent is collapsed + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) window->HiddenFramesCanSkipItems = 1; + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) + window->HiddenFramesCannotSkipItems = 1; } // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) From 2a3517a39983c4b7a2d4c1596b803e20d2137fc2 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 30 Jun 2019 12:03:09 +0200 Subject: [PATCH 456/566] Internals: Checkbox: Added undocumented mixed/indeterminate/tristate support via ImGuiItemFlags_MixedValue. (#2644) --- docs/TODO.txt | 2 +- imgui_internal.h | 1 + imgui_widgets.cpp | 11 +++++++++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index a918b9e1..cdd92383 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -65,7 +65,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - widgets: start exposing PushItemFlag() and ImGuiItemFlags - widgets: alignment options in style (e.g. center Selectable, Right-Align within Button, etc.) #1260 - widgets: activate by identifier (trigger button, focus given id) - - widgets: a way to represent "mixed" values, so e.g. all values replaced with **, including check-boxes, colors, etc. with support for multi-components widgets (e.g. SliderFloat3, make only "Y" mixed) + - widgets: a way to represent "mixed" values, so e.g. all values replaced with *, including check-boxes, colors, etc. with support for multi-components widgets (e.g. SliderFloat3, make only "Y" mixed) (#2644) - widgets: selectable: generic BeginSelectable()/EndSelectable() mechanism. - widgets: selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - widgets: checkbox: checkbox with custom glyph inside frame. diff --git a/imgui_internal.h b/imgui_internal.h index 67ee3b4d..3b96116e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -384,6 +384,7 @@ enum ImGuiItemFlags_ ImGuiItemFlags_NoNav = 1 << 3, // false ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window + ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) ImGuiItemFlags_Default_ = 0 }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3490586b..a5959c23 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1001,10 +1001,17 @@ bool ImGui::Checkbox(const char* label, bool* v) const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); RenderNavHighlight(total_bb, id); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); - if (*v) + ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); + if (window->DC.ItemFlags & ImGuiItemFlags_MixedValue) + { + // Undocumented tristate/mixed/indeterminate checkbox (#2644) + ImVec2 pad(ImMax(1.0f, (float)(int)(square_sz / 3.6f)), ImMax(1.0f, (float)(int)(square_sz / 3.6f))); + window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); + } + else if (*v) { const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f)); - RenderCheckMark(check_bb.Min + ImVec2(pad, pad), GetColorU32(ImGuiCol_CheckMark), square_sz - pad*2.0f); + RenderCheckMark(check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad*2.0f); } if (g.LogEnabled) From caf119a982dab93ab45a312be4f2d243f034b097 Mon Sep 17 00:00:00 2001 From: kevreco Date: Tue, 30 Jan 2018 21:51:28 +0100 Subject: [PATCH 457/566] Added 'SetScrollHereX' and 'SetScrollFromPosX' (#1580) --- imgui.cpp | 26 +++++++++++++++++++++++++- imgui.h | 2 ++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 5f402f74..1f877961 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4841,7 +4841,12 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s if (window->ScrollTarget.x < FLT_MAX) { float cr_x = window->ScrollTargetCenterRatio.x; - scroll.x = window->ScrollTarget.x - cr_x * window->InnerRect.GetWidth(); + float target_x = window->ScrollTarget.x; + if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x) + target_x = 0.0f; + else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + GImGui->Style.ItemSpacing.x) + target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f; + scroll.x = target_x - cr_x * window->InnerRect.GetWidth(); } if (window->ScrollTarget.y < FLT_MAX) { @@ -6861,6 +6866,25 @@ void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) window->ScrollTargetCenterRatio.y = center_y_ratio; } +void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); + window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); + window->ScrollTargetCenterRatio.x = center_x_ratio; +} + +// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. +void ImGui::SetScrollHereX(float center_x_ratio) +{ + ImGuiWindow* window = GetCurrentWindow(); + float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space + float last_item_width = window->DC.LastItemRect.GetWidth(); + target_x += (last_item_width * center_x_ratio) + (GImGui->Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. + SetScrollFromPosX(target_x, center_x_ratio); +} + // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. void ImGui::SetScrollHereY(float center_y_ratio) { diff --git a/imgui.h b/imgui.h index 101f4249..7b34c7c5 100644 --- a/imgui.h +++ b/imgui.h @@ -302,7 +302,9 @@ namespace ImGui IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] + IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. + IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. // Parameters stacks (shared) From da29d77253072ad16128e9c9104bf8ad71299822 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 1 Jul 2019 12:15:36 +0200 Subject: [PATCH 458/566] Added SetScrollXHere, SetScrollFromPosX: Changelog, demo, comments (#1580). --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 1 + imgui.cpp | 16 +++++----- imgui_demo.cpp | 73 ++++++++++++++++++++++++++++++++++------------ 4 files changed, 65 insertions(+), 26 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bff027d3..f1861aac 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). +- Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawList::ChannelsSplit(), ImDrawListSplitter: Fixed an issue with merging draw commands between diff --git a/docs/TODO.txt b/docs/TODO.txt index cdd92383..d5291373 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -30,6 +30,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - window/child: the first draw command of a child window could be moved into the current draw command of the parent window (unless child+tooltip?). - window/child: border could be emitted in parent as well. + - window/child: allow SetNextWindowContentSize() to work on child windows. - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - window/tab: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). - scrolling: while holding down a scrollbar, try to keep the same contents visible (at least while not moving mouse) diff --git a/imgui.cpp b/imgui.cpp index 1f877961..5d37d08c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6857,22 +6857,22 @@ void ImGui::SetScrollY(float scroll_y) window->ScrollTargetCenterRatio.y = 0.0f; } -void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) +void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); - window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); - window->ScrollTargetCenterRatio.y = center_y_ratio; + IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); + window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); + window->ScrollTargetCenterRatio.x = center_x_ratio; } -void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) +void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); - window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); - window->ScrollTargetCenterRatio.x = center_x_ratio; + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); + window->ScrollTargetCenterRatio.y = center_y_ratio; } // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index afd2b894..8d9337a5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1744,7 +1744,7 @@ static void ShowDemoWindowLayout() // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from the POV of the parent window) // See "Widgets" -> "Querying Status (Active/Focused/Hovered etc.)" section for more details about this. { - ImGui::SetCursorPosX(50); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10); ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); ImGui::BeginChild("blah", ImVec2(200, 100), true, ImGuiWindowFlags_None); for (int n = 0; n < 50; n++) @@ -1957,7 +1957,7 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Groups")) { - HelpMarker("Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it."); + HelpMarker("BeginGroup() basically locks the horizontal position for new line. EndGroup() bundles the whole group so that you can use \"item\" functions such as IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group."); ImGui::BeginGroup(); { ImGui::BeginGroup(); @@ -2056,21 +2056,22 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Scrolling")) { - HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given position."); + // Vertical scroll functions + HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position."); static bool track = true; - static int track_line = 50; + static int track_item = 50; static float scroll_to_off_px = 0.0f; static float scroll_to_pos_px = 200.0f; ImGui::Checkbox("Track", &track); ImGui::PushItemWidth(100); - ImGui::SameLine(140); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line = %d"); + ImGui::SameLine(140); track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); bool scroll_to_off = ImGui::Button("Scroll Offset"); - ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off_y", &scroll_to_off_px, 1.00f, 0, 9999, "+%.0f px"); + ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, 9999, "+%.0f px"); bool scroll_to_pos = ImGui::Button("Scroll To Pos"); - ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos_y", &scroll_to_pos_px, 1.00f, 0, 9999, "Y = %.0f px"); + ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, 0, 9999, "X/Y = %.0f px"); ImGui::PopItemWidth(); if (scroll_to_off || scroll_to_pos) @@ -2078,28 +2079,31 @@ static void ShowDemoWindowLayout() ImGuiStyle& style = ImGui::GetStyle(); float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; + if (child_w < 20.0f) + child_w = 20.0f; + ImGui::PushID("##VerticalScrolling"); for (int i = 0; i < 5; i++) { if (i > 0) ImGui::SameLine(); ImGui::BeginGroup(); - ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); + const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" }; + ImGui::TextUnformatted(names[i]); - ImGuiWindowFlags child_flags = ImGuiWindowFlags_MenuBar; - ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, child_flags); + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, ImGuiWindowFlags_None); if (scroll_to_off) ImGui::SetScrollY(scroll_to_off_px); if (scroll_to_pos) ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f); - for (int line = 0; line < 100; line++) + for (int item = 0; item < 100; item++) { - if (track && line == track_line) + if (track && item == track_item) { - ImGui::TextColored(ImVec4(1,1,0,1), "Line %d", line); + ImGui::TextColored(ImVec4(1,1,0,1), "Item %d", item); ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom } else { - ImGui::Text("Line %d", line); + ImGui::Text("Item %d", item); } } float scroll_y = ImGui::GetScrollY(); @@ -2108,11 +2112,44 @@ static void ShowDemoWindowLayout() ImGui::Text("%.0f/%.0f", scroll_y, scroll_max_y); ImGui::EndGroup(); } - ImGui::TreePop(); - } + ImGui::PopID(); - if (ImGui::TreeNode("Horizontal Scrolling")) - { + // Horizontal scroll functions + ImGui::Spacing(); + HelpMarker("Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\nUsing the \"Scroll To Pos\" button above will make the discontinuity at edges visible: scrolling to the top/bottom/left/right-most item will add an additional WindowPadding to reflect on reaching the edge of the list.\n\nBecause the clipping rectangle of most window hides half worth of WindowPadding on the left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the equivalent SetScrollFromPosY(+1) wouldn't."); + ImGui::PushID("##HorizontalScrolling"); + for (int i = 0; i < 5; i++) + { + float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f; + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(-100, child_height), true, ImGuiWindowFlags_HorizontalScrollbar); + if (scroll_to_off) + ImGui::SetScrollX(scroll_to_off_px); + if (scroll_to_pos) + ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f); + for (int item = 0; item < 100; item++) + { + if (track && item == track_item) + { + ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item); + ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right + } + else + { + ImGui::Text("Item %d", item); + } + ImGui::SameLine(); + } + float scroll_x = ImGui::GetScrollX(); + float scroll_max_x = ImGui::GetScrollMaxX(); + ImGui::EndChild(); + ImGui::SameLine(); + const char* names[] = { "Left", "25%", "Center", "75%", "Right" }; + ImGui::Text("%s\n%.0f/%.0f", names[i], scroll_x, scroll_max_x); + ImGui::Spacing(); + } + ImGui::PopID(); + + // Miscellaneous Horizontal Scrolling Demo HelpMarker("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\nYou may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); static int lines = 7; ImGui::SliderInt("Lines", &lines, 1, 15); From 58c9f8a19450650088e92858f6df25a4a4237f97 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 1 Jul 2019 18:48:21 +0200 Subject: [PATCH 459/566] Misc: Added IMGUI_DISABLE_METRICS_WINDOW imconfig.h setting to explicitly compile out ShowMetricsWindow(). + Internals: Minor renaming. --- docs/CHANGELOG.txt | 1 + imconfig.h | 1 + imgui.cpp | 39 +++++++++++++++++++++++---------------- 3 files changed, 25 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f1861aac..3eaed626 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,7 @@ Other Changes: of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. +- Misc: Added IMGUI_DISABLE_METRICS_WINDOW imconfig.h setting to explicitly compile out ShowMetricsWindow(). - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawList::ChannelsSplit(), ImDrawListSplitter: Fixed an issue with merging draw commands between channel 0 and 1. (#2624) diff --git a/imconfig.h b/imconfig.h index 4d7adf5d..5d9caecd 100644 --- a/imconfig.h +++ b/imconfig.h @@ -28,6 +28,7 @@ //---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty) // It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp. //#define IMGUI_DISABLE_DEMO_WINDOWS +//#define IMGUI_DISABLE_METRICS_WINDOW //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. diff --git a/imgui.cpp b/imgui.cpp index 5d37d08c..f5602651 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9935,6 +9935,7 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} // [SECTION] METRICS/DEBUG WINDOW //----------------------------------------------------------------------------- +#ifndef IMGUI_DISABLE_METRICS_WINDOW void ImGui::ShowMetricsWindow(bool* p_open) { if (!ImGui::Begin("Dear ImGui Metrics", p_open)) @@ -9943,10 +9944,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; } - enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerRect, RT_InnerClipRect, RT_WorkRect, RT_Contents, RT_ContentsRegionRect, RT_Count }; + enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Contents, WRT_ContentsRegionRect, WRT_Count }; // Windows Rect Type + const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Contents", "ContentsRegionRect" }; + static bool show_windows_begin_order = false; static bool show_windows_rects = false; - static int show_windows_rect_type = RT_WorkRect; + static int show_windows_rect_type = WRT_WorkRect; static bool show_drawcmd_clip_rects = true; ImGuiIO& io = ImGui::GetIO(); @@ -9959,15 +9962,15 @@ void ImGui::ShowMetricsWindow(bool* p_open) struct Funcs { - static ImRect GetRect(ImGuiWindow* window, int rect_type) + static ImRect GetWindowRect(ImGuiWindow* window, int rect_type) { - if (rect_type == RT_OuterRect) { return window->Rect(); } - else if (rect_type == RT_OuterRectClipped) { return window->OuterRectClipped; } - else if (rect_type == RT_InnerRect) { return window->InnerRect; } - else if (rect_type == RT_InnerClipRect) { return window->InnerClipRect; } - else if (rect_type == RT_WorkRect) { return window->WorkRect; } - else if (rect_type == RT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } - else if (rect_type == RT_ContentsRegionRect) { return window->ContentsRegionRect; } + if (rect_type == WRT_OuterRect) { return window->Rect(); } + else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; } + else if (rect_type == WRT_InnerRect) { return window->InnerRect; } + else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; } + else if (rect_type == WRT_WorkRect) { return window->WorkRect; } + else if (rect_type == WRT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } + else if (rect_type == WRT_ContentsRegionRect) { return window->ContentsRegionRect; } IM_ASSERT(0); return ImRect(); } @@ -10174,16 +10177,15 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - const char* rects_names[RT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Contents", "ContentsRegionRect" }; - show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, rects_names, RT_Count); + show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count); if (show_windows_rects && g.NavWindow) { ImGui::BulletText("'%s':", g.NavWindow->Name); ImGui::Indent(); - for (int n = 0; n < RT_Count; n++) + for (int rect_n = 0; rect_n < WRT_Count; rect_n++) { - ImRect r = Funcs::GetRect(g.NavWindow, n); - ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), rects_names[n]); + ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n); + ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]); } ImGui::Unindent(); } @@ -10201,7 +10203,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImDrawList* draw_list = GetForegroundDrawList(window); if (show_windows_rects) { - ImRect r = Funcs::GetRect(window, show_windows_rect_type); + ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow)) @@ -10216,6 +10218,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) } ImGui::End(); } +#else +void ImGui::ShowMetricsWindow(bool*) +{ +} +#endif //----------------------------------------------------------------------------- From e16564e67a2e88d4cbe3afa6594650712790fba3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 1 Jul 2019 20:57:15 +0200 Subject: [PATCH 460/566] Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. --- docs/CHANGELOG.txt | 1 + imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3eaed626..d8e96b4c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,7 @@ Breaking Changes: Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). +- Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8d9337a5..a8d72f2e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2079,8 +2079,8 @@ static void ShowDemoWindowLayout() ImGuiStyle& style = ImGui::GetStyle(); float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; - if (child_w < 20.0f) - child_w = 20.0f; + if (child_w < 1.0f) + child_w = 1.0f; ImGui::PushID("##VerticalScrolling"); for (int i = 0; i < 5; i++) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a5959c23..8af935c5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -895,13 +895,13 @@ void ImGui::Scrollbar(ImGuiAxis axis) ImRect bb; if (axis == ImGuiAxis_X) { - bb.Min = ImVec2(inner_rect.Min.x, outer_rect.Max.y - border_size - scrollbar_size); + bb.Min = ImVec2(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size)); bb.Max = ImVec2(inner_rect.Max.x, outer_rect.Max.y); rounding_corners |= ImDrawCornerFlags_BotLeft; } else { - bb.Min = ImVec2(outer_rect.Max.x - border_size - scrollbar_size, inner_rect.Min.y); + bb.Min = ImVec2(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y); bb.Max = ImVec2(outer_rect.Max.x, window->InnerRect.Max.y); rounding_corners |= ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0; } From 54c49b5fb1371626f92853a2658cfe2d51d2e41d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 2 Jul 2019 18:28:53 +0200 Subject: [PATCH 461/566] Window: Mouse wheel scrolling while hovering a child window is automatically forwarded to parent window if ScrollMax is zero on the scrolling axis. Also still case if ImGuiWindowFlags_NoScrollWithMouse is set (not new), but previously the forwarding would be disabled if ImGuiWindowFlags_NoScrollbar was set on the child window, which is not the case any more (amend #1502, #1380). --- docs/CHANGELOG.txt | 5 +++++ imgui.cpp | 49 +++++++++++++++++++++++++--------------------- 2 files changed, 32 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d8e96b4c..331e9005 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,11 @@ Breaking Changes: Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). +- Window: Mouse wheel scrolling while hovering a child window is automatically forwarded to parent window + if ScrollMax is zero on the scrolling axis. + Also still case if ImGuiWindowFlags_NoScrollWithMouse is set (not new), but previously the forwarding + would be disabled if ImGuiWindowFlags_NoScrollbar was set on the child window, which is not the case + any more. Forwarding can still be disabled by setting ImGuiWindowFlags_NoInputs. (amend #1502, #1380). - Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). diff --git a/imgui.cpp b/imgui.cpp index f5602651..4d7ff311 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3449,12 +3449,12 @@ void ImGui::UpdateMouseWheel() return; if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f) return; - ImGuiWindow* window = g.HoveredWindow; // Zoom / Scale window // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. - if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling && !window->Collapsed) + if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling && !g.HoveredWindow->Collapsed) { + ImGuiWindow* window = g.HoveredWindow; const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); const float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; @@ -3469,31 +3469,36 @@ void ImGui::UpdateMouseWheel() } // Mouse wheel scrolling - // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set). - while ((window->Flags & ImGuiWindowFlags_ChildWindow) && (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs) && window->ParentWindow) - window = window->ParentWindow; - const bool scroll_allowed = !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs); - if (scroll_allowed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f) && !g.IO.KeyCtrl) - { - ImVec2 max_step = window->InnerRect.GetSize() * 0.67f; + // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent + // FIXME: Lock scrolling window while not moving (see #2604) - // Vertical Mouse Wheel Scrolling (hold Shift to scroll horizontally) - if (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) - { - float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step.y)); - SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * scroll_step); - } - else if (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) + // Vertical Mouse Wheel scrolling + const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; + if (wheel_y != 0.0f && !g.IO.KeyCtrl) + { + ImGuiWindow* window = g.HoveredWindow; + while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) + window = window->ParentWindow; + if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) { - float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x)); - SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheel * scroll_step); + float max_step = window->InnerRect.GetHeight() * 0.67f; + float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step)); + SetWindowScrollY(window, window->Scroll.y - wheel_y * scroll_step); } + } - // Horizontal Mouse Wheel Scrolling (for hardware that supports it) - if (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) + // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held + const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; + if (wheel_x != 0.0f && !g.IO.KeyCtrl) + { + ImGuiWindow* window = g.HoveredWindow; + while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) + window = window->ParentWindow; + if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) { - float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x)); - SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_step); + float max_step = window->InnerRect.GetWidth() * 0.67f; + float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step)); + SetWindowScrollX(window, window->Scroll.x - wheel_x * scroll_step); } } } From d23f1b1409fbb565b974599c2f3bb0d83b830a0b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 10 Jul 2019 11:36:43 +0200 Subject: [PATCH 462/566] fonts/binary_to_compress: display error message when failing to open file + misc comments. --- docs/CHANGELOG.txt | 1 + imgui.h | 20 ++++++++++---------- misc/fonts/binary_to_compressed_c.cpp | 7 +++++-- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 331e9005..2d507bfe 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,7 @@ Other Changes: channel 0 and 1. (#2624) - ImDrawListSplitter: Fixed memory leak when using low-level split api (was not affecting ImDrawList api, also this type was added in 1.71 and not advertised as a public-facing feature). +- Fonts: binary_to_compressed_c.cpp: Display an error message if failing to open/read the input font file. - Backends: SDL2: Added dummy ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. (#2482, #2632) [@josiahmanson] - Examples: Added SDL2+DirectX11 example application. (#2632, #2612, #2482) [@vincenthamm] diff --git a/imgui.h b/imgui.h index 7b34c7c5..ec4e1357 100644 --- a/imgui.h +++ b/imgui.h @@ -126,30 +126,30 @@ typedef void* ImTextureID; // User data to identify a texture (this is typedef unsigned int ImGuiID; // Unique ID used by widgets (typically hashed from a stack of string) typedef unsigned short ImWchar; // A single U16 character for keyboard input/display. We encode them as multi bytes UTF-8 when used in strings. typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling -typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for Set*() +typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A key identifier (ImGui-side enum) typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling -typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect*() etc. +typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect(), AddRectFilled() etc. typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags -typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit*(), ColorPicker*() +typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: for Columns(), BeginColumns() typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() -typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for *DragDrop*() +typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. -typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText*() +typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() -typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode*(),CollapsingHeader() -typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin*() +typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() +typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); @@ -870,7 +870,7 @@ enum ImGuiHoveredFlags_ ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. - ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window + ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is obstructed or overlapped by another window ImGuiHoveredFlags_AllowWhenDisabled = 1 << 7, // Return true even if the item is disabled ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows @@ -901,7 +901,7 @@ enum ImGuiDragDropFlags_ // A primary data type enum ImGuiDataType_ { - ImGuiDataType_S8, // char + ImGuiDataType_S8, // signed char / char (with sensible compilers) ImGuiDataType_U8, // unsigned char ImGuiDataType_S16, // short ImGuiDataType_U16, // unsigned short @@ -1344,7 +1344,7 @@ struct ImGuiIO float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. void* UserData; // = NULL // Store your own data for retrieval by callbacks. - ImFontAtlas*Fonts; // // Load, rasterize and pack one or more fonts into a single texture. + ImFontAtlas*Fonts; // // Font atlas: load, rasterize and pack one or more fonts into a single texture. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. diff --git a/misc/fonts/binary_to_compressed_c.cpp b/misc/fonts/binary_to_compressed_c.cpp index 3fde3d95..4d3522d4 100644 --- a/misc/fonts/binary_to_compressed_c.cpp +++ b/misc/fonts/binary_to_compressed_c.cpp @@ -48,12 +48,15 @@ int main(int argc, char** argv) else if (strcmp(argv[argn], "-nocompress") == 0) { use_compression = false; argn++; } else { - printf("Unknown argument: '%s'\n", argv[argn]); + fprintf(stderr, "Unknown argument: '%s'\n", argv[argn]); return 1; } } - return binary_to_compressed_c(argv[argn], argv[argn+1], use_base85_encoding, use_compression) ? 0 : 1; + bool ret = binary_to_compressed_c(argv[argn], argv[argn+1], use_base85_encoding, use_compression); + if (!ret) + fprintf(stderr, "Error opening or reading file: '%s'\n", argv[argn]); + return ret ? 0 : 1; } char Encode85Byte(unsigned int x) From 3436132d4bca81300fca49031cb6bd6dced09335 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 11 Jul 2019 17:20:39 +0200 Subject: [PATCH 463/566] Combo: Hide arrow when there's not enough space even for the square button. + Various todo items. --- docs/CHANGELOG.txt | 1 + docs/README.md | 1 + docs/TODO.txt | 10 ++++++---- imgui_widgets.cpp | 3 ++- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2d507bfe..844a3ddd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,7 @@ Other Changes: would be disabled if ImGuiWindowFlags_NoScrollbar was set on the child window, which is not the case any more. Forwarding can still be disabled by setting ImGuiWindowFlags_NoInputs. (amend #1502, #1380). - Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. +- Combo: Hide arrow when there's not enough space even for the square button. - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/docs/README.md b/docs/README.md index 241eaadd..c5abf581 100644 --- a/docs/README.md +++ b/docs/README.md @@ -137,6 +137,7 @@ Frameworks: - Platform: GLFW, SDL, Win32, OSX, GLUT: [examples/](https://github.com/ocornut/imgui/tree/master/examples) - Framework: Allegro 5, Emscripten, Marmalade: [examples/](https://github.com/ocornut/imgui/tree/master/examples) - Unmerged PR: Android: [#421](https://github.com/ocornut/imgui/pull/421) +- bsf: [bsfimgui](https://github.com/pgruenbacher/bsfImgui) - Cinder: [Cinder-ImGui](https://github.com/simongeilfus/Cinder-ImGui) - Cocos2d-x: [imguix](https://github.com/c0i/imguix), [#551](https://github.com/ocornut/imgui/issues/551) - Flexium: [FlexGUI](https://github.com/DXsmiley/FlexGUI) diff --git a/docs/TODO.txt b/docs/TODO.txt index d5291373..d0f2e84e 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -33,12 +33,13 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window/child: allow SetNextWindowContentSize() to work on child windows. - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - window/tab: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). + ! scrolling: exposing horizontal scrolling with Shift+Wheel even when scrollbar is disabled expose lots of issues (#2424, #1463) - scrolling: while holding down a scrollbar, try to keep the same contents visible (at least while not moving mouse) - scrolling: allow immediately effective change of scroll after Begin() if we haven't appended items yet. - scrolling/clipping: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y). (2017-08-20: can't repro) - scrolling/style: shadows on scrollable areas to denote that there is more contents - - drawdata: make it easy to clone (or swap?) a ImDrawData so user can easily save that data if they use threaded rendering. + - drawdata: make it easy to clone (or swap?) a full ImDrawData so user can easily save that data if they use threaded rendering. (e.g. #2646) ! drawlist: add calctextsize func to facilitate consistent code from user pov (currently need to use ImGui or ImFont alternatives!) - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. - drawlist: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). @@ -205,23 +206,24 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - shortcuts: programmatically access shortcuts "Focus("&Save")) - menus: menu-bar: main menu-bar could affect clamping of windows position (~ akin to modifying DisplayMin) - menus: hovering from menu to menu on a menu-bar has 1 frame without any menu, which is a little annoying. ideally either 0 either longer. + - menus: could merge draw call in most cases (how about storing an optional aabb in ImDrawCmd to move the burden of merging in a single spot). - text: selectable text (for copy) as a generic feature (ItemFlags?) - text: proper alignment options in imgui_internal.h - - text wrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) - text: it's currently impossible to have a window title with "##". perhaps an official workaround would be nice. \ style inhibitor? non-visible ascii code to insert between #? - text: provided a framed text helper, e.g. https://pastebin.com/1Laxy8bT - text: refactor TextUnformatted (or underlying function) to more explicitly request if we need width measurement or not - text link/url button: underlined. should api expose an ID or use text contents as ID? which colors enum to use? + - text/wrapped: should be a more first-class citizen, e.g. wrapped text within a Selectable with known width + - text/wrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) - - tree node / optimization: avoid formatting when clipped. - - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling. - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits? - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) - tree node: tweak color scheme to distinguish headers from selected tree node (#581) - tree node: leaf/non-leaf highlight mismatch. - tree node: _NoIndentOnOpen flag? would require to store a per-depth bit mask to store info for pop (or whatever is cheaper) + - tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height?) - settings: write more decent code to allow saving/loading new fields: columns, selected tree nodes? - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file (#437) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8af935c5..e59836c1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1432,7 +1432,8 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); ImU32 text_col = GetColorU32(ImGuiCol_Text); window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); - RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down); + if (value_x2 + arrow_size - style.FramePadding.x <= frame_bb.Max.x) + RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f); } RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding); if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) From e66799f79a14a533d7b7adb937fc700f6c1168fa Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Jul 2019 11:54:22 +0200 Subject: [PATCH 464/566] Prefixed internal structs exposed in imgui.h with a fully qualified name to facilitate auto-generation with cimgui. --- imgui.cpp | 62 +++++++++++++++++++++++++++---------------------------- imgui.h | 36 ++++++++++++++++---------------- 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4d7ff311..6ec5e241 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1923,15 +1923,15 @@ ImU32 ImGui::GetColorU32(ImU32 col) //----------------------------------------------------------------------------- // std::lower_bound but without the bullshit -static ImGuiStorage::Pair* LowerBound(ImVector& data, ImGuiID key) +static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector& data, ImGuiID key) { - ImGuiStorage::Pair* first = data.Data; - ImGuiStorage::Pair* last = data.Data + data.Size; + ImGuiStorage::ImGuiStoragePair* first = data.Data; + ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size; size_t count = (size_t)(last - first); while (count > 0) { size_t count2 = count >> 1; - ImGuiStorage::Pair* mid = first + count2; + ImGuiStorage::ImGuiStoragePair* mid = first + count2; if (mid->key < key) { first = ++mid; @@ -1953,18 +1953,18 @@ void ImGuiStorage::BuildSortByKey() static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs) { // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. - if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1; - if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1; + if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1; + if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1; return 0; } }; if (Data.Size > 1) - ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID); + ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID); } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { - ImGuiStorage::Pair* it = LowerBound(const_cast&>(Data), key); + ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; @@ -1977,7 +1977,7 @@ bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { - ImGuiStorage::Pair* it = LowerBound(const_cast&>(Data), key); + ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; @@ -1985,7 +1985,7 @@ float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { - ImGuiStorage::Pair* it = LowerBound(const_cast&>(Data), key); + ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; @@ -1994,9 +1994,9 @@ void* ImGuiStorage::GetVoidPtr(ImGuiID key) const // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { - ImGuiStorage::Pair* it = LowerBound(Data, key); + ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) - it = Data.insert(it, Pair(key, default_val)); + it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_i; } @@ -2007,27 +2007,27 @@ bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { - ImGuiStorage::Pair* it = LowerBound(Data, key); + ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) - it = Data.insert(it, Pair(key, default_val)); + it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { - ImGuiStorage::Pair* it = LowerBound(Data, key); + ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) - it = Data.insert(it, Pair(key, default_val)); + it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_p; } // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImGuiID key, int val) { - ImGuiStorage::Pair* it = LowerBound(Data, key); + ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { - Data.insert(it, Pair(key, val)); + Data.insert(it, ImGuiStoragePair(key, val)); return; } it->val_i = val; @@ -2040,10 +2040,10 @@ void ImGuiStorage::SetBool(ImGuiID key, bool val) void ImGuiStorage::SetFloat(ImGuiID key, float val) { - ImGuiStorage::Pair* it = LowerBound(Data, key); + ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { - Data.insert(it, Pair(key, val)); + Data.insert(it, ImGuiStoragePair(key, val)); return; } it->val_f = val; @@ -2051,10 +2051,10 @@ void ImGuiStorage::SetFloat(ImGuiID key, float val) void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { - ImGuiStorage::Pair* it = LowerBound(Data, key); + ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { - Data.insert(it, Pair(key, val)); + Data.insert(it, ImGuiStoragePair(key, val)); return; } it->val_p = val; @@ -2095,7 +2095,7 @@ bool ImGuiTextFilter::Draw(const char* label, float width) return value_changed; } -void ImGuiTextFilter::TextRange::split(char separator, ImVector* out) const +void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector* out) const { out->resize(0); const char* wb = b; @@ -2104,25 +2104,25 @@ void ImGuiTextFilter::TextRange::split(char separator, ImVector* out) { if (*we == separator) { - out->push_back(TextRange(wb, we)); + out->push_back(ImGuiTextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) - out->push_back(TextRange(wb, we)); + out->push_back(ImGuiTextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); - TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); + ImGuiTextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); input_range.split(',', &Filters); CountGrep = 0; for (int i = 0; i != Filters.Size; i++) { - TextRange& f = Filters[i]; + ImGuiTextRange& f = Filters[i]; while (f.b < f.e && ImCharIsBlankA(f.b[0])) f.b++; while (f.e > f.b && ImCharIsBlankA(f.e[-1])) @@ -2144,19 +2144,19 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const for (int i = 0; i != Filters.Size; i++) { - const TextRange& f = Filters[i]; + const ImGuiTextRange& f = Filters[i]; if (f.empty()) continue; if (f.b[0] == '-') { // Subtract - if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) + if (ImStristr(text, text_end, f.b + 1, f.e) != NULL) return false; } else { // Grep - if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) + if (ImStristr(text, text_end, f.b, f.e) != NULL) return true; } } @@ -10102,7 +10102,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) NodeColumns(&window->ColumnsStorage[n]); ImGui::TreePop(); } - ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); + ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.size_in_bytes()); ImGui::TreePop(); } diff --git a/imgui.h b/imgui.h index ec4e1357..a1ee7958 100644 --- a/imgui.h +++ b/imgui.h @@ -1591,21 +1591,19 @@ struct ImGuiTextFilter bool IsActive() const { return !Filters.empty(); } // [Internal] - struct TextRange + struct ImGuiTextRange { - const char* b; - const char* e; - - TextRange() { b = e = NULL; } - TextRange(const char* _b, const char* _e) { b = _b; e = _e; } - const char* begin() const { return b; } - const char* end () const { return e; } - bool empty() const { return b == e; } - IMGUI_API void split(char separator, ImVector* out) const; + 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; }; - char InputBuf[256]; - ImVector Filters; - int CountGrep; + char InputBuf[256]; + ImVectorFilters; + int CountGrep; }; // Helper: Growable text buffer for logging/accumulating text @@ -1639,15 +1637,17 @@ struct ImGuiTextBuffer // Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. struct ImGuiStorage { - struct Pair + // [Internal] + struct ImGuiStoragePair { ImGuiID key; union { int val_i; float val_f; void* val_p; }; - Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } - Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } - Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + ImGuiStoragePair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + ImGuiStoragePair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + ImGuiStoragePair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } }; - ImVector Data; + + ImVector Data; // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) // - Set***() functions find pair, insertion on demand if missing. From d52c6316c8280aac4df66a1380984121fa9d46da Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Jul 2019 11:58:46 +0200 Subject: [PATCH 465/566] Renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Keep redirection typedef (will obsolete). --- docs/CHANGELOG.txt | 1 + imgui.cpp | 1 + imgui.h | 39 +++++++++++++++++++++------------------ imgui_draw.cpp | 14 +++++++------- 4 files changed, 30 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 844a3ddd..9bf1fd63 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,7 @@ Breaking Changes: - IMGUI_ONCE_UPON_A_FRAME macro. If you were still using the old names, read "API Breaking Changes" section of imgui.cpp to find out the new names and equivalent. +- Renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Keep redirection typedef (will obsolete). Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). diff --git a/imgui.cpp b/imgui.cpp index 6ec5e241..f0c7caf1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,7 @@ CODE When you are not sure about a 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. + - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Keep redirection typedef (will obsolete). - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names. - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering. diff --git a/imgui.h b/imgui.h index a1ee7958..3aa10abf 100644 --- a/imgui.h +++ b/imgui.h @@ -2027,6 +2027,19 @@ struct ImFontGlyphRangesBuilder IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges }; +// See ImFontAtlas::AddCustomRectXXX functions. +struct ImFontAtlasCustomRect +{ + unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data. + unsigned short Width, Height; // Input // Desired rectangle dimension + unsigned short X, Y; // Output // Packed position in Atlas + float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance + ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset + ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font + ImFontAtlasCustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } + bool IsPacked() const { return X != 0xFFFF; } +}; + enum ImFontAtlasFlags_ { ImFontAtlasFlags_None = 0, @@ -2091,7 +2104,7 @@ struct ImFontAtlas IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters - IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietname characters + IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters //------------------------------------------- // [BETA] Custom Rectangles/Glyphs API @@ -2102,24 +2115,13 @@ struct ImFontAtlas // You can also 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. // Read misc/fonts/README.txt for more details about using colorful icons. - struct CustomRect - { - unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data. - unsigned short Width, Height; // Input // Desired rectangle dimension - unsigned short X, Y; // Output // Packed position in Atlas - float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance - ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset - ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font - CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } - bool IsPacked() const { return X != 0xFFFF; } - }; - IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font. - const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } + IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font. + const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } // [Internal] - IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max); - IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); + IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max); + IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); //------------------------------------------- // Members @@ -2140,11 +2142,12 @@ struct ImFontAtlas ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel 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 CustomRects; // Rectangles for packing custom texture data into the atlas. + ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector ConfigData; // Internal data int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ #endif }; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 51ff2cd9..e7c5e82e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1720,7 +1720,7 @@ int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) IM_ASSERT(id >= 0x10000); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - CustomRect r; + ImFontAtlasCustomRect r; r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; @@ -1733,7 +1733,7 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); - CustomRect r; + ImFontAtlasCustomRect r; r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; @@ -1744,7 +1744,7 @@ int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int return CustomRects.Size - 1; // Return index } -void ImFontAtlas::CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) +void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) { IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed @@ -1760,7 +1760,7 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou return false; IM_ASSERT(CustomRectIds[0] != -1); - ImFontAtlas::CustomRect& r = CustomRects[CustomRectIds[0]]; + ImFontAtlasCustomRect& r = CustomRects[CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y); ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; @@ -2119,7 +2119,7 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque; IM_ASSERT(pack_context != NULL); - ImVector& user_rects = atlas->CustomRects; + ImVector& user_rects = atlas->CustomRects; IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong. ImVector pack_rects; @@ -2145,7 +2145,7 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->CustomRectIds[0] >= 0); IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; + ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); IM_ASSERT(r.IsPacked()); @@ -2180,7 +2180,7 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) { - const ImFontAtlas::CustomRect& r = atlas->CustomRects[i]; + const ImFontAtlasCustomRect& r = atlas->CustomRects[i]; if (r.Font == NULL || r.ID > 0x10000) continue; From 71d20abbc34342ef6e6fc8c2824b25fa16743858 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 12 Jul 2019 13:33:24 +0200 Subject: [PATCH 466/566] Settings: Minor optimization to reduce calls in SettingsHandlerWindow_WriteAll. --- imgui.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f0c7caf1..22a3ec45 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9558,6 +9558,8 @@ ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) ImGuiContext& g = *GImGui; g.SettingsWindows.push_back(ImGuiWindowSettings()); ImGuiWindowSettings* settings = &g.SettingsWindows.back(); + if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + name = p; settings->Name = ImStrdup(name); settings->ID = ImHashStr(name); return settings; @@ -9743,10 +9745,7 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl const ImGuiWindowSettings* settings = &g.SettingsWindows[i]; if (settings->Pos.x == FLT_MAX) continue; - const char* name = settings->Name; - if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() - name = p; - buf->appendf("[%s][%s]\n", handler->TypeName, name); + buf->appendf("[%s][%s]\n", handler->TypeName, settings->Name); buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); buf->appendf("Collapsed=%d\n", settings->Collapsed); From e461e7bc7af9cb4f7eab21949fad356b9983bae1 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 14 Jul 2019 12:28:42 -0700 Subject: [PATCH 467/566] Moved ImGuiColumnsFlags erroneously forward declared in imgui.h + demo bit. --- imgui.h | 1 - imgui_demo.cpp | 1 + imgui_internal.h | 1 + 3 files changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 3aa10abf..72c19259 100644 --- a/imgui.h +++ b/imgui.h @@ -138,7 +138,6 @@ typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: f typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. -typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: for Columns(), BeginColumns() typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a8d72f2e..81c1ba27 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2606,6 +2606,7 @@ static void ShowDemoWindowColumns() ImGui::Separator(); ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i); ImGui::Text("Width %.2f", ImGui::GetColumnWidth()); + ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x); ImGui::Text("Offset %.2f", ImGui::GetColumnOffset()); ImGui::Text("Long text that is likely to clip"); ImGui::Button("Button", ImVec2(-FLT_MIN, 0.0f)); diff --git a/imgui_internal.h b/imgui_internal.h index 3b96116e..cb5c4086 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -91,6 +91,7 @@ struct ImGuiWindowSettings; // Storage for window settings stored in .in // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() +typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: BeginColumns() typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags From dd80db87a634cf095cfc832e582c0778d11b6103 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 15 Jul 2019 13:35:21 -0700 Subject: [PATCH 468/566] Viewport: Added ImGuiViewportFlags_NoAutoMerge to prevent merging into host viewport in a per-window basis via the ImGuiWindowClass override mechanism. (#1542) --- imgui.cpp | 16 +++++++++------- imgui.h | 7 ++++--- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 24fbb7d0..dcb7c3b7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10532,12 +10532,13 @@ static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) { - // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protude and create their own. + // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own. ImGuiContext& g = *GImGui; - if (g.IO.ConfigViewportsNoAutoMerge && (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) - if (!window->DockIsActive) - if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0) - return true; + if (g.IO.ConfigViewportsNoAutoMerge || ((window->WindowClass.ViewportFlagsOverrideValue & window->WindowClass.ViewportFlagsOverrideMask) & ImGuiViewportFlags_NoAutoMerge)) + if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) + if (!window->DockIsActive) + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0) + return true; return false; } @@ -14812,10 +14813,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGuiWindowFlags flags = viewport->Flags; ImGui::BulletText("Pos: (%.0f,%.0f), Size: (%.0f,%.0f), Monitor: %d, DpiScale: %.0f%%", viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, viewport->PlatformMonitor, viewport->DpiScale * 100.0f); if (viewport->Idx > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200,200); if (viewport->Window) viewport->Window->Pos = ImVec2(200,200); } } - ImGui::BulletText("Flags: 0x%04X =%s%s%s%s%s%s", viewport->Flags, + ImGui::BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s", viewport->Flags, (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "", - (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : ""); + (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "", + (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : ""); for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++) for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++) Funcs::NodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList"); diff --git a/imgui.h b/imgui.h index 1067787f..d9307529 100644 --- a/imgui.h +++ b/imgui.h @@ -1429,7 +1429,7 @@ struct ImGuiIO bool ConfigDockingTransparentPayload;// = false // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) - bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. + bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags_NoAutoMerge on individual viewport. bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. bool ConfigViewportsNoDecoration; // = true // [BETA] Disable default OS window decoration flag for secondary viewports. When a viewport doesn't want window decorations, ImGuiViewportFlags_NoDecoration will be set on it. Enabling decoration can create subsequent issues at OS levels (e.g. minimum window size). bool ConfigViewportsNoDefaultParent; // = false // Disable default OS parenting to main viewport for secondary viewports. By default, viewports are marked with ParentViewportId = , expecting the platform back-end to setup a parent/child relationship between the OS windows (some back-end may ignore this). Set to true if you want the default to be 0, then all viewports will be top-level OS windows. @@ -2383,9 +2383,10 @@ enum ImGuiViewportFlags_ ImGuiViewportFlags_NoFocusOnClick = 1 << 3, // Platform Window: Don't take focus when clicked on. ImGuiViewportFlags_NoInputs = 1 << 4, // Platform Window: Make mouse pass through so we can drag this window while peaking behind it. ImGuiViewportFlags_NoRendererClear = 1 << 5, // Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). - ImGuiViewportFlags_TopMost = 1 << 6, // Platform Window: Display on top (for tooltips only) + ImGuiViewportFlags_TopMost = 1 << 6, // Platform Window: Display on top (for tooltips only). ImGuiViewportFlags_Minimized = 1 << 7, // Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. - ImGuiViewportFlags_CanHostOtherWindows = 1 << 8 // Main viewport: can host multiple imgui windows (secondary viewports are associated to a single window) + ImGuiViewportFlags_NoAutoMerge = 1 << 8, // Platform Window: Avoid merging this widow into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). + ImGuiViewportFlags_CanHostOtherWindows = 1 << 9 // Main viewport: can host multiple imgui windows (secondary viewports are associated to a single window). }; // The viewports created and managed by imgui. The role of the platform back-end is to create the platform/OS windows corresponding to each viewport. From 8bc6d976cbe82611435e4f1c10c405bbd83573e4 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 15 Jul 2019 14:17:01 -0700 Subject: [PATCH 469/566] Docking: Fixed using ImGuiDockNodeFlags_AutoHideTabBar with ConfigDockingTabBarOnSingleWindows. (#2109) --- imgui.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index dcb7c3b7..2751c76b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11855,6 +11855,11 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) DockSettingsRenameNodeReferences(payload_dock_id, node->ID); } } + else + { + // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar + node->WantHiddenTabBarUpdate = true; + } // Update selection immediately if (ImGuiTabBar* tab_bar = node->TabBar) From 7a9d32acee87eb352fcd96e7a356608f6d32a764 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 14 Jul 2019 18:01:06 -0700 Subject: [PATCH 470/566] Fixed unnecessary test in UpdateMouseWheel() (thanks PVS). TreeNodeBehavior: avoid computing bg_col for non-framed non-active tree nodes. Comments, binaries update, minor typos. --- docs/CHANGELOG.txt | 10 +++++----- docs/README.md | 2 +- imgui.cpp | 10 +++++----- imgui.h | 2 +- imgui_widgets.cpp | 3 ++- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9bf1fd63..036f481e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,8 +39,8 @@ Breaking Changes: - IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow() functions. - IMGUI_ONCE_UPON_A_FRAME macro. If you were still using the old names, read "API Breaking Changes" section of imgui.cpp to find out - the new names and equivalent. -- Renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Keep redirection typedef (will obsolete). + the new names or equivalent features. +- Renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). @@ -243,7 +243,7 @@ Breaking Changes: - Renamed ColorEdit/ColorPicker's ImGuiColorEditFlags_RGB/_HSV/_HEX flags to respectively ImGuiColorEditFlags_DisplayRGB/_DisplayHSV/_DisplayHex. This is because the addition of new flag ImGuiColorEditFlags_InputHSV makes the earlier one ambiguous. - Keep redirection enum values (will obsolete). (#2384) [@haldean] + Kept redirection enum values (will obsolete). (#2384) [@haldean] - Renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). (#2391) Other Changes: @@ -388,7 +388,7 @@ Breaking Changes: side-effect because the window would have ID zero. In particular it is causing problems in viewport/docking branches. - Renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges and removed its [Beta] mark. The addition of new configuration options in the Docking branch is pushing for a little reorganization of those names. -- Renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete). +- Renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete). Other Changes: - Added BETA api for Tab Bar/Tabs widgets: (#261, #351) @@ -1129,7 +1129,7 @@ Breaking Changes: - Removed `IsItemRectHovered()`, `IsWindowRectHovered()` recently introduced in 1.51 which were merely the more consistent/correct names for the above functions which are now obsolete anyway. (#1382) - Changed `IsWindowHovered()` default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. (#1382) - Renamed imconfig.h's `IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS`/`IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS` to `IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS`/`IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS` for consistency. -- Renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete). +- Renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete). Other Changes: diff --git a/docs/README.md b/docs/README.md index c5abf581..902b615a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -102,7 +102,7 @@ Demo Binaries ------------- You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me 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-20190219.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20190219.zip) (Windows binaries, Dear ImGui 1.68 built 2019/02/19, master branch, 5 executables) +- [imgui-demo-binaries-20190715.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20190715.zip) (Windows binaries, Dear ImGui 1.72 WIP built 2019/07/15, master branch, 5 executables) The demo applications are unfortunately not yet DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your Style with `style.ScaleAllSizes()`. diff --git a/imgui.cpp b/imgui.cpp index 22a3ec45..d82e8b53 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6,7 +6,7 @@ // Get latest version at https://github.com/ocornut/imgui // Releases change-log at https://github.com/ocornut/imgui/releases // Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started -// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269 +// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/2529 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // See LICENSE.txt for copyright and licensing details (standard MIT License). @@ -369,7 +369,7 @@ CODE When you are not sure about a 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. - - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Keep redirection typedef (will obsolete). + - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names. - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering. @@ -384,7 +384,7 @@ CODE - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete). + - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete). - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files. @@ -457,7 +457,7 @@ CODE IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior] - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead! - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). - - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete). + - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete). - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete). - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)! @@ -3453,7 +3453,7 @@ void ImGui::UpdateMouseWheel() // Zoom / Scale window // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. - if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling && !g.HoveredWindow->Collapsed) + if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) { ImGuiWindow* window = g.HoveredWindow; const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); diff --git a/imgui.h b/imgui.h index 72c19259..03cb9d36 100644 --- a/imgui.h +++ b/imgui.h @@ -1040,7 +1040,7 @@ enum ImGuiCol_ ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, - ImGuiCol_Header, + ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem ImGuiCol_HeaderHovered, ImGuiCol_HeaderActive, ImGuiCol_Separator, diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e59836c1..20ae82e5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5238,13 +5238,13 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render - const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); const ImU32 text_col = GetColorU32(ImGuiCol_Text); const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y); ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin; if (display_frame) { // Framed type + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding); RenderNavHighlight(frame_bb, id, nav_highlight_flags); RenderArrow(window->DrawList, frame_bb.Min + ImVec2(padding.x, text_base_offset_y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); @@ -5269,6 +5269,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Unframed typed for tree nodes if (hovered || selected) { + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false); RenderNavHighlight(frame_bb, id, nav_highlight_flags); } From 3d07c7cbe4db652a775e2a0410c59158f164b6bf Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 15 Jul 2019 17:56:20 -0700 Subject: [PATCH 471/566] TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 036f481e..9b6d6809 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: any more. Forwarding can still be disabled by setting ImGuiWindowFlags_NoInputs. (amend #1502, #1380). - Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Combo: Hide arrow when there's not enough space even for the square button. +- TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 20ae82e5..6ef4ef26 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6347,7 +6347,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG window->DC.CursorPos.x = tab_bar->BarRect.Min.x; // Draw separator - const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_Tab); + const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); const float y = tab_bar->BarRect.Max.y - 1.0f; { const float separator_min_x = tab_bar->BarRect.Min.x - ImFloor(window->WindowPadding.x * 0.5f); From a35f42f1230d1e18885c3fc3a45c5448858bc85d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 15 Jul 2019 18:14:14 -0700 Subject: [PATCH 472/566] Removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete). (#581, #324) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui.h | 5 +++-- imgui_demo.cpp | 2 +- imgui_widgets.cpp | 7 ------- 5 files changed, 7 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9b6d6809..382b2ee1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ Breaking Changes: If you were still using the old names, read "API Breaking Changes" section of imgui.cpp to find out the new names or equivalent features. - Renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). +- Removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). + Kept redirection function (will obsolete). (#581, #324) Other Changes: - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). diff --git a/imgui.cpp b/imgui.cpp index d82e8b53..ac96259e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -369,6 +369,7 @@ CODE When you are not sure about a 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. + - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete). - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names. - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have diff --git a/imgui.h b/imgui.h index 03cb9d36..c5bcb213 100644 --- a/imgui.h +++ b/imgui.h @@ -496,7 +496,6 @@ namespace ImGui IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. IMGUI_API void TreePush(const void* ptr_id = NULL); // " IMGUI_API void TreePop(); // ~ Unindent()+PopId() - IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header @@ -1531,8 +1530,10 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.72 (from July 2019) + static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.71 (from June 2019) - static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } + static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.70 (from May 2019) static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.69 (from Mar 2019) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 81c1ba27..0db2f1db 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -628,7 +628,7 @@ static void ShowDemoWindowWidgets() { // Items 3..5 are Tree Leaves // The only reason we use TreeNode at all is to allow selection of the leaf. - // Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text(). + // Otherwise we can use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i); if (ImGui::IsItemClicked()) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6ef4ef26..e3810022 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4990,7 +4990,6 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl // - TreeNodeBehavior() [Internal] // - TreePush() // - TreePop() -// - TreeAdvanceToLabelPos() // - GetTreeNodeToLabelSpacing() // - SetNextItemOpen() // - CollapsingHeader() @@ -5332,12 +5331,6 @@ void ImGui::TreePop() PopID(); } -void ImGui::TreeAdvanceToLabelPos() -{ - ImGuiContext& g = *GImGui; - g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); -} - // Horizontal distance preceding label when using TreeNode() or Bullet() float ImGui::GetTreeNodeToLabelSpacing() { From 718e15c7de951a0fd3ef8600e6d7e0129ad7050d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 16 Jul 2019 11:45:52 -0700 Subject: [PATCH 473/566] Docking: Fix so that an appearing window making a dock node reappear won't have a zero-size on its first frame (because dock node ->Size was 0.0 unlike ->SizeRef) (#2109) Docking: Added ImGuiDockNode to .natvis file. --- imgui.cpp | 38 ++++++++++++++++++++++++++++++++++---- imgui_internal.h | 1 + misc/natvis/imgui.natvis | 4 ++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2751c76b..aa5a31f8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11373,7 +11373,7 @@ namespace ImGui // ImGuiDockNode tree manipulations static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node); static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child); - static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size); + static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes = false); static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node); static ImGuiDockNode* DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos); static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node); @@ -11953,6 +11953,7 @@ ImGuiDockNode::ImGuiDockNode(ImGuiID id) IsVisible = true; IsFocused = HasCloseButton = HasWindowMenuButton = EnableCloseButton = false; WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; + MarkedForPosSizeWrite = false; } ImGuiDockNode::~ImGuiDockNode() @@ -12286,6 +12287,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) ImGuiContext& g = *GImGui; IM_ASSERT(node->LastFrameActive != g.FrameCount); node->LastFrameAlive = g.FrameCount; + node->MarkedForPosSizeWrite = false; node->CentralNode = node->OnlyNodeWithWindows = NULL; if (node->IsRootNode()) @@ -12533,6 +12535,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) node->LastFrameActive = g.FrameCount; // Recurse into children + // FIXME-DOCK FIXME-OPT: Should not need to recurse into children if (host_window) { if (node->ChildNodes[0]) @@ -13265,10 +13268,17 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG } // Update Pos/Size for a node hierarchy (don't affect child Windows yet) -void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size) +void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes) { - node->Pos = pos; - node->Size = size; + // During the regular dock node update we write to all nodes. + // 'only_write_to_marked_nodes' is only set when turning a node visible mid-frame and we need its size right-away. + const bool write_to_node = (only_write_to_marked_nodes == false) || (node->MarkedForPosSizeWrite); + if (write_to_node) + { + node->Pos = pos; + node->Size = size; + } + if (node->IsLeafNode()) return; @@ -14082,6 +14092,25 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) node->LastFrameAlive = g.FrameCount; } + // If the node just turned visible, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, + // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). + // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. + // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. + if (!node->IsVisible) + { + ImGuiDockNode* ancestor_node = node; + while (!ancestor_node->IsVisible) + { + ancestor_node->IsVisible = true; + ancestor_node->MarkedForPosSizeWrite = true; + if (ancestor_node->ParentNode) + ancestor_node = ancestor_node->ParentNode; + } + IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f); + DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, true); + } + + // Add window to node DockNodeAddWindow(node, window, true); IM_ASSERT(node == window->DockNode); } @@ -14128,6 +14157,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) } IM_ASSERT(node->HostWindow); IM_ASSERT(node->IsLeafNode()); + IM_ASSERT(node->Size.x > 0.0f && node->Size.y > 0.0f); // Position window SetNextWindowPos(node->Pos); diff --git a/imgui_internal.h b/imgui_internal.h index 265292ae..44dff1e7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -956,6 +956,7 @@ struct ImGuiDockNode bool WantMouseMove :1; // After a node extraction we need to transition toward moving the newly created host window bool WantHiddenTabBarUpdate :1; bool WantHiddenTabBarToggle :1; + bool MarkedForPosSizeWrite :1; // Update by DockNodeTreeUpdatePosSize() write-filtering ImGuiDockNode(ImGuiID id); ~ImGuiDockNode(); diff --git a/misc/natvis/imgui.natvis b/misc/natvis/imgui.natvis index cc768bfb..f1082a81 100644 --- a/misc/natvis/imgui.natvis +++ b/misc/natvis/imgui.natvis @@ -35,5 +35,9 @@ {{Name {Name,s} Active {(Active||WasActive)?1:0,d} Child {(Flags & 0x01000000)?1:0,d} Popup {(Flags & 0x04000000)?1:0,d} Hidden {(Hidden)?1:0,d}} + + + {{ID {ID,x} Pos=({Pos.x,g} {Pos.y,g}) Size=({Size.x,g} {Size.y,g}) Parent {(ParentNode==0)?0:ParentNode->ID,x} Childs {(ChildNodes[0] != 0)+(ChildNodes[1] != 0)} Windows {Windows.Size} } + \ No newline at end of file From e6a286b3a567eb1d3b032e6c412565b0ef19677a Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 16 Jul 2019 16:43:21 -0700 Subject: [PATCH 474/566] Style: Added style.ColorButtonButton (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 1 + imgui.h | 1 + imgui_demo.cpp | 3 ++- imgui_widgets.cpp | 21 +++++++++++++-------- 5 files changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 382b2ee1..e6cf69eb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,7 +41,7 @@ Breaking Changes: If you were still using the old names, read "API Breaking Changes" section of imgui.cpp to find out the new names or equivalent features. - Renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). -- Removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). +- Removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete). (#581, #324) Other Changes: @@ -58,6 +58,8 @@ Other Changes: of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. +- Style: Added style.ColorButtonButton (left/right, defaults to ImGuiDir_Right) to move the color button + of ColorEdit3/ColorEdit4 functions to either side of the inputs. - Misc: Added IMGUI_DISABLE_METRICS_WINDOW imconfig.h setting to explicitly compile out ShowMetricsWindow(). - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawList::ChannelsSplit(), ImDrawListSplitter: Fixed an issue with merging draw commands between diff --git a/imgui.cpp b/imgui.cpp index ac96259e..47dc25df 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1164,6 +1164,7 @@ ImGuiStyle::ImGuiStyle() GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. + ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. diff --git a/imgui.h b/imgui.h index c5bcb213..0ffde480 100644 --- a/imgui.h +++ b/imgui.h @@ -1301,6 +1301,7 @@ struct ImGuiStyle float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. + ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text when selectable is larger than text. Defaults to (0.0f, 0.0f) (top-left aligned). ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0db2f1db..4d08a257 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1145,7 +1145,7 @@ static void ShowDemoWindowWidgets() static ImVec4 backup_color; bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags); - ImGui::SameLine(); + ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); open_popup |= ImGui::Button("Palette"); if (open_popup) { @@ -3151,6 +3151,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::Text("Alignment"); ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); ImGui::Combo("WindowMenuButtonPosition", (int*)&style.WindowMenuButtonPosition, "Left\0Right\0"); + ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0"); ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content."); ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content."); ImGui::Text("Safe Area Padding"); ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e3810022..03a2c508 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4137,8 +4137,9 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float square_sz = GetFrameHeight(); - const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); - const float w_items_all = CalcItemWidth() - w_extra; + const float w_full = CalcItemWidth(); + const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); + const float w_inputs = w_full - w_button; const char* label_display_end = FindRenderedTextEnd(label); g.NextItemData.ClearFlags(); @@ -4182,11 +4183,15 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag bool value_changed = false; bool value_changed_as_float = false; + const ImVec2 pos = window->DC.CursorPos; + const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f; + window->DC.CursorPos.x = pos.x + inputs_offset_x; + if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders - const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + const float w_item_one = ImMax(1.0f, (float)(int)((w_inputs - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; @@ -4230,7 +4235,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255)); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255)); - SetNextItemWidth(w_items_all); + SetNextItemWidth(w_inputs); if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { value_changed = true; @@ -4250,8 +4255,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag ImGuiWindow* picker_active_window = NULL; if (!(flags & ImGuiColorEditFlags_NoSmallPreview)) { - if (!(flags & ImGuiColorEditFlags_NoInputs)) - SameLine(0, style.ItemInnerSpacing.x); + const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x; + window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y); const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f); if (ColorButton("##ColorButton", col_v4, flags)) @@ -4285,7 +4290,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) { - SameLine(0, style.ItemInnerSpacing.x); + window->DC.CursorPos = ImVec2(pos.x + w_full + style.ItemInnerSpacing.x, pos.y + style.FramePadding.y); TextEx(label, label_display_end); } From 130b44994e31d4b0b2cc8c87597a9002e4765c74 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 16 Jul 2019 18:25:49 -0700 Subject: [PATCH 475/566] Debug, Metrics: Added "Tools->Item Picker" tool which allow clicking on a widget to break in the debugger within the item code. The tool calls IM_DEBUG_BREAK() which can be redefined in imconfig.h if needed. --- docs/CHANGELOG.txt | 2 ++ imconfig.h | 5 +++++ imgui.cpp | 39 ++++++++++++++++++++++++++++++++++++--- imgui_internal.h | 21 +++++++++++++++++++-- 4 files changed, 62 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e6cf69eb..3167c556 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,8 @@ Other Changes: - Style: Added style.ColorButtonButton (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. - Misc: Added IMGUI_DISABLE_METRICS_WINDOW imconfig.h setting to explicitly compile out ShowMetricsWindow(). +- Debug, Metrics: Added "Tools->Item Picker" tool which allow clicking on a widget to break in the debugger + within the item code. The tool calls IM_DEBUG_BREAK() which can be redefined in imconfig.h if needed. - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawList::ChannelsSplit(), ImDrawListSplitter: Fixed an issue with merging draw commands between channel 0 and 1. (#2624) diff --git a/imconfig.h b/imconfig.h index 5d9caecd..16f8c827 100644 --- a/imconfig.h +++ b/imconfig.h @@ -76,6 +76,11 @@ //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); //#define ImDrawCallback MyImDrawCallback +//---- Debug Tools +// Use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging. +//#define IM_DEBUG_BREAK IM_ASSERT(0) +//#define IM_DEBUG_BREAK __debugbreak() + //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui diff --git a/imgui.cpp b/imgui.cpp index 47dc25df..bde77d2d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2862,6 +2862,16 @@ void ImGui::SetHoveredID(ImGuiID id) g.HoveredIdAllowOverlap = false; if (id != 0 && g.HoveredIdPreviousFrame != id) g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f; + + // [DEBUG] Item Picker tool! + // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making + // the cost of this tool near-zero. We would get slightly better call-stack if we made the test in ItemAdd() + // but that would incur a slightly higher cost and may require us to hide this feature behind a define. + if (id != 0 && id == g.DebugBreakItemId) + { + IM_DEBUG_BREAK(); + g.DebugBreakItemId = 0; + } } ImGuiID ImGui::GetHoveredID() @@ -10180,6 +10190,28 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("Tools")) { + static bool picking_enabled = false; + if (ImGui::Button("Item Picker..")) + picking_enabled = true; + if (picking_enabled) + { + const ImGuiID hovered_id = g.HoveredIdPreviousFrame; + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsKeyPressedMap(ImGuiKey_Escape)) + picking_enabled = false; + if (ImGui::IsMouseClicked(0) && hovered_id) + { + g.DebugBreakItemId = hovered_id; + picking_enabled = false; + } + ImGui::SetNextWindowBgAlpha(0.5f); + ImGui::BeginTooltip(); + ImGui::Text("HoveredId: 0x%08X", hovered_id); + ImGui::Text("Press ESC to abort picking."); + ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!"); + ImGui::EndTooltip(); + } + ImGui::Checkbox("Show windows begin order", &show_windows_begin_order); ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); @@ -10225,10 +10257,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) } ImGui::End(); } + #else -void ImGui::ShowMetricsWindow(bool*) -{ -} + +void ImGui::ShowMetricsWindow(bool*) { } + #endif //----------------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index cb5c4086..d615a942 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -401,7 +401,7 @@ enum ImGuiItemStatusFlags_ ImGuiItemStatusFlags_Deactivated = 1 << 5 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. #ifdef IMGUI_ENABLE_TEST_ENGINE - , // [imgui-test only] + , // [imgui_tests only] ImGuiItemStatusFlags_Openable = 1 << 10, // ImGuiItemStatusFlags_Opened = 1 << 11, // ImGuiItemStatusFlags_Checkable = 1 << 12, // @@ -1028,6 +1028,9 @@ struct ImGuiContext int LogDepthToExpand; int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. + // Debug Tools + ImGuiID DebugBreakItemId; + // Misc float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds. int FramerateSecPerFrameIdx; @@ -1153,6 +1156,8 @@ struct ImGuiContext LogDepthRef = 0; LogDepthToExpand = LogDepthToExpandDefault = 2; + DebugBreakItemId = 0; + memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); FramerateSecPerFrameIdx = 0; FramerateSecPerFrameAccum = 0.0f; @@ -1662,7 +1667,19 @@ IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); -// Test engine hooks (imgui-test) +// Debug Tools +// Use 'Metrics->Tools->Item Picker' to break into the call-stack of a specific item. +#ifndef IM_DEBUG_BREAK +#if defined(__clang__) +#define IM_DEBUG_BREAK() __builtin_debugtrap() +#elif defined (_MSC_VER) +#define IM_DEBUG_BREAK() __debugbreak() +#else +#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger! +#endif +#endif // #ifndef IM_DEBUG_BREAK + +// Test Engine Hooks (imgui_tests) //#define IMGUI_ENABLE_TEST_ENGINE #ifdef IMGUI_ENABLE_TEST_ENGINE extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); From ea79992d9add90f5e6d23b7b7941aceb20734bd5 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Jul 2019 09:59:10 -0700 Subject: [PATCH 476/566] Fixed old SetWindowFontScale() api value from not being inherited by child window. Added comments about the right way to scale your UI (load a font at the right side, rebuild atlas, scale style). + Added missing IMGUI_API marker to the EmptyString storage used by ImGuiTextBuffer. (#2672) --- docs/CHANGELOG.txt | 4 +++- imgui.h | 4 ++-- imgui_demo.cpp | 3 ++- imgui_internal.h | 14 +++++++------- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3167c556..c7a88164 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,8 @@ Other Changes: Also still case if ImGuiWindowFlags_NoScrollWithMouse is set (not new), but previously the forwarding would be disabled if ImGuiWindowFlags_NoScrollbar was set on the child window, which is not the case any more. Forwarding can still be disabled by setting ImGuiWindowFlags_NoInputs. (amend #1502, #1380). +- Window: Fixed old SetWindowFontScale() api value from not being inherited by child window. Added + comments about the right way to scale your UI (load a font at the right side, rebuild atlas, scale style). - Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Combo: Hide arrow when there's not enough space even for the square button. - TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). @@ -58,7 +60,7 @@ Other Changes: of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. -- Style: Added style.ColorButtonButton (left/right, defaults to ImGuiDir_Right) to move the color button +- Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. - Misc: Added IMGUI_DISABLE_METRICS_WINDOW imconfig.h setting to explicitly compile out ShowMetricsWindow(). - Debug, Metrics: Added "Tools->Item Picker" tool which allow clicking on a widget to break in the debugger diff --git a/imgui.h b/imgui.h index 0ffde480..a81296fd 100644 --- a/imgui.h +++ b/imgui.h @@ -280,7 +280,7 @@ namespace ImGui IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). - IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows + IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state @@ -1612,7 +1612,7 @@ struct ImGuiTextFilter struct ImGuiTextBuffer { ImVector Buf; - static char EmptyString[1]; + IMGUI_API static char EmptyString[1]; ImGuiTextBuffer() { } inline char operator[](int i) { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4d08a257..e1c07dcf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3295,8 +3295,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::TreePop(); } + HelpMarker("Those are old settings provided for convenience.\nHowever, the _correct_ way of scaling your UI is currently to reload your font at the designed size, rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure."); static float window_scale = 1.0f; - if (ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.2f")) // scale only this window + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.2f")) // scale only this window ImGui::SetWindowFontScale(window_scale); ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.2f"); // scale everything ImGui::PopItemWidth(); diff --git a/imgui_internal.h b/imgui_internal.h index d615a942..33f71139 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1317,7 +1317,7 @@ struct IMGUI_API ImGuiWindow ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items ImGuiStorage StateStorage; ImVector ColumnsStorage; - float FontWindowScale; // User scale multiplier per-window + float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() int SettingsIdx; // Index into SettingsWindow[] (indices are always valid as we only grow the array from the back) ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) @@ -1344,12 +1344,12 @@ public: ImGuiID GetIDFromRectangle(const ImRect& r_abs); // We don't use g.FontSize because the window may be != g.CurrentWidow. - ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } - float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } - float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } - ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } - float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; } - ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } + float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } + float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } + float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } }; // Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data. From bb2aa5e77062e7e16c59741aab9c48eed1b6722f Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Jul 2019 13:55:00 -0700 Subject: [PATCH 477/566] Docking: Making it possible to undock a node by clicking on the tab bar / title bar for the node. (#2645, #2109) --- imgui.cpp | 45 ++++++++++++++++++++++++++++++++++++++------- imgui_internal.h | 1 + imgui_widgets.cpp | 27 ++------------------------- 3 files changed, 41 insertions(+), 32 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7ec5d599..ce7e3cc7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3403,6 +3403,32 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) g.MovingWindow = window; } +void ImGui::StartMouseDragFromTitleBar(ImGuiWindow* window, ImGuiDockNode* node, bool from_collapse_button) +{ + ImGuiContext& g = *GImGui; + bool can_extract_dock_node = false; + if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0) + { + ImGuiDockNode* root_node = DockNodeGetRootNode(node); + if (root_node->OnlyNodeWithWindows != node || (root_node->CentralNode != NULL)) + if (from_collapse_button || root_node->IsDockSpace()) + can_extract_dock_node = true; + } + + const bool clicked = IsMouseClicked(0); + const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f); + if (can_extract_dock_node && dragging) + { + DockContextQueueUndockNode(&g, node); + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; + } + else if (!can_extract_dock_node && (clicked || dragging) && g.MovingWindow != window) + { + StartMouseMovingWindow(window); + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos; + } +} + // Handle mouse moving window // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() void ImGui::UpdateMouseMovingWindowNewFrame() @@ -12802,15 +12828,20 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w } // When clicking on the title bar outside of tabs, we still focus the selected tab for that node - if (g.HoveredWindow == host_window && g.HoveredId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max)) + // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) + ImGuiID title_bar_id = host_window->GetID("#TITLEBAR"); + if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id) { - if (IsMouseClicked(0)) + bool held; + ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held); + if (held) { - focus_tab_id = tab_bar->SelectedTabId; + if (IsMouseClicked(0)) + focus_tab_id = tab_bar->SelectedTabId; // Forward moving request to selected window - if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id)) - StartMouseMovingWindow(tab->Window); + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) + StartMouseDragFromTitleBar(tab->Window, node, false); } } @@ -13418,7 +13449,7 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) /* // [DEBUG] Render limits - ImDrawList* draw_list = node->HostWindow ? GetOverlayDrawList(node->HostWindow) : GetOverlayDrawList((ImGuiViewportP*)GetMainViewport()); + ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); for (int n = 0; n < 2; n++) if (axis == ImGuiAxis_X) draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f); @@ -13446,7 +13477,7 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++) { ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n]; - //ImDrawList* draw_list = node->HostWindow ? GetOverlayDrawList(node->HostWindow) : GetOverlayDrawList((ImGuiViewportP*)GetMainViewport()); + //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255)); while (touching_node->ParentNode != node) { diff --git a/imgui_internal.h b/imgui_internal.h index e9907a96..6392ecf2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1661,6 +1661,7 @@ namespace ImGui // NewFrame IMGUI_API void UpdateHoveredWindowAndCaptureFlags(); IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); + IMGUI_API void StartMouseDragFromTitleBar(ImGuiWindow* window, ImGuiDockNode* node, bool from_collapse_button); IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4de236d5..076b3e80 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -776,30 +776,7 @@ bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_no // Switch to moving the window after mouse is moved beyond the initial drag threshold if (IsItemActive() && IsMouseDragging(0)) - { - bool can_extract_dock_node = false; - if (dock_node != NULL && dock_node->VisibleWindow && !(dock_node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove)) - { - ImGuiDockNode* root_node = DockNodeGetRootNode(dock_node); - if (root_node->OnlyNodeWithWindows != dock_node || (root_node->CentralNode != NULL)) - can_extract_dock_node = true; - } - if (can_extract_dock_node) - { - float threshold_base = g.FontSize; - float threshold_x = (threshold_base * 2.2f); - float threshold_y = (threshold_base * 1.5f); - IM_ASSERT(window->DockNodeAsHost != NULL); - if (g.IO.MouseDragMaxDistanceAbs[0].x > threshold_x || g.IO.MouseDragMaxDistanceAbs[0].y > threshold_y) - DockContextQueueUndockNode(&g, dock_node); - } - else - { - ImVec2 backup_active_click_offset = g.ActiveIdClickOffset + (pos - window->Pos); - StartMouseMovingWindow(window); - g.ActiveIdClickOffset = backup_active_click_offset; - } - } + StartMouseDragFromTitleBar(window, dock_node, true); return pressed; } @@ -7048,7 +7025,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, //float threshold_base = g.IO.ConfigDockingWithShift ? g.FontSize * 0.5f : g.FontSize; float threshold_x = (threshold_base * 2.2f); float threshold_y = (threshold_base * 1.5f) + ImClamp((ImFabs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0f) * 0.20f, 0.0f, threshold_base * 4.0f); - //GetOverlayDrawList(window)->AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE); // [DEBUG] + //GetForegroundDrawList()->AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE); // [DEBUG] float distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y); if (distance_from_edge_y >= threshold_y) From 1f3feb481e936c821b07ad0b0c91dbd0417133b9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Jul 2019 14:02:45 -0700 Subject: [PATCH 478/566] Internals: Refactor: Moved all Columns code from imgui.cpp to imgui_widgets.cpp (#125) Also moved NextColumn between BeginColumn and NextColumn which makes it easier to work on that code. --- imgui.cpp | 391 +------------------------------------------- imgui_internal.h | 2 + imgui_widgets.cpp | 407 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 410 insertions(+), 390 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bde77d2d..659239df 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -75,7 +75,6 @@ CODE // [SECTION] TOOLTIPS // [SECTION] POPUPS // [SECTION] KEYBOARD/GAMEPAD NAVIGATION -// [SECTION] COLUMNS // [SECTION] DRAG AND DROP // [SECTION] LOGGING/CAPTURING // [SECTION] SETTINGS @@ -8664,394 +8663,6 @@ void ImGui::NavUpdateWindowingList() PopStyleVar(); } -//----------------------------------------------------------------------------- -// [SECTION] COLUMNS -// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. -//----------------------------------------------------------------------------- - -void ImGui::NextColumn() -{ - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems || window->DC.CurrentColumns == NULL) - return; - - ImGuiContext& g = *GImGui; - ImGuiColumns* columns = window->DC.CurrentColumns; - - if (columns->Count == 1) - { - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); - IM_ASSERT(columns->Current == 0); - return; - } - - PopItemWidth(); - PopClipRect(); - - columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (++columns->Current < columns->Count) - { - // Columns 1+ cancel out IndentX - // FIXME-COLUMNS: Unnecessary, could be locked? - window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; - window->DrawList->ChannelsSetCurrent(columns->Current + 1); - } - else - { - // New row/line - window->DC.ColumnsOffset.x = 0.0f; - window->DrawList->ChannelsSetCurrent(1); - columns->Current = 0; - columns->LineMinY = columns->LineMaxY; - } - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); - window->DC.CursorPos.y = columns->LineMinY; - window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); - window->DC.CurrLineTextBaseOffset = 0.0f; - - PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? - - // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. - float offset_0 = GetColumnOffset(columns->Current); - float offset_1 = GetColumnOffset(columns->Current + 1); - float width = offset_1 - offset_0; - PushItemWidth(width * 0.65f); - window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; -} - -int ImGui::GetColumnIndex() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; -} - -int ImGui::GetColumnsCount() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; -} - -static float OffsetNormToPixels(const ImGuiColumns* columns, float offset_norm) -{ - return offset_norm * (columns->OffMaxX - columns->OffMinX); -} - -static float PixelsToOffsetNorm(const ImGuiColumns* columns, float offset) -{ - return offset / (columns->OffMaxX - columns->OffMinX); -} - -static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; - -static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) -{ - // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing - // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. - IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); - - float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; - x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); - if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) - x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); - - return x; -} - -float ImGui::GetColumnOffset(int column_index) -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - if (column_index < 0) - column_index = columns->Current; - IM_ASSERT(column_index < columns->Columns.Size); - - const float t = columns->Columns[column_index].OffsetNorm; - const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); - return x_offset; -} - -static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false) -{ - if (column_index < 0) - column_index = columns->Current; - - float offset_norm; - if (before_resize) - offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; - else - offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; - return OffsetNormToPixels(columns, offset_norm); -} - -float ImGui::GetColumnWidth(int column_index) -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - if (column_index < 0) - column_index = columns->Current; - return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); -} - -void ImGui::SetColumnOffset(int column_index, float offset) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - ImGuiColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - if (column_index < 0) - column_index = columns->Current; - IM_ASSERT(column_index < columns->Columns.Size); - - const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1); - const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; - - if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) - offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); - columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->OffMinX); - - if (preserve_width) - SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); -} - -void ImGui::SetColumnWidth(int column_index, float width) -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - if (column_index < 0) - column_index = columns->Current; - SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); -} - -void ImGui::PushColumnClipRect(int column_index) -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; - if (column_index < 0) - column_index = columns->Current; - - ImGuiColumnData* column = &columns->Columns[column_index]; - PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); -} - -// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) -void ImGui::PushColumnsBackground() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; - window->DrawList->ChannelsSetCurrent(0); - int cmd_size = window->DrawList->CmdBuffer.Size; - PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); - IM_UNUSED(cmd_size); - IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd -} - -void ImGui::PopColumnsBackground() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; - window->DrawList->ChannelsSetCurrent(columns->Current + 1); - PopClipRect(); -} - -ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) -{ - // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. - for (int n = 0; n < window->ColumnsStorage.Size; n++) - if (window->ColumnsStorage[n].ID == id) - return &window->ColumnsStorage[n]; - - window->ColumnsStorage.push_back(ImGuiColumns()); - ImGuiColumns* columns = &window->ColumnsStorage.back(); - columns->ID = id; - return columns; -} - -ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) -{ - ImGuiWindow* window = GetCurrentWindow(); - - // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. - // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. - PushID(0x11223347 + (str_id ? 0 : columns_count)); - ImGuiID id = window->GetID(str_id ? str_id : "columns"); - PopID(); - - return id; -} - -void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - - IM_ASSERT(columns_count >= 1); - IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported - - // Acquire storage for the columns set - ImGuiID id = GetColumnsID(str_id, columns_count); - ImGuiColumns* columns = FindOrCreateColumns(window, id); - IM_ASSERT(columns->ID == id); - columns->Current = 0; - columns->Count = columns_count; - columns->Flags = flags; - window->DC.CurrentColumns = columns; - - // Set state for first column - columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; - columns->OffMaxX = ImMax(window->WorkRect.Max.x - window->Pos.x, columns->OffMinX + 1.0f); - columns->HostCursorPosY = window->DC.CursorPos.y; - columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; - columns->HostClipRect = window->ClipRect; - columns->HostWorkRect = window->WorkRect; - columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; - window->DC.ColumnsOffset.x = 0.0f; - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); - - // Clear data if columns count changed - if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) - columns->Columns.resize(0); - - // Initialize default widths - columns->IsFirstFrame = (columns->Columns.Size == 0); - if (columns->Columns.Size == 0) - { - columns->Columns.reserve(columns_count + 1); - for (int n = 0; n < columns_count + 1; n++) - { - ImGuiColumnData column; - column.OffsetNorm = n / (float)columns_count; - columns->Columns.push_back(column); - } - } - - for (int n = 0; n < columns_count; n++) - { - // Compute clipping rectangle - ImGuiColumnData* column = &columns->Columns[n]; - float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n)); - float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); - column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); - column->ClipRect.ClipWith(window->ClipRect); - } - - if (columns->Count > 1) - { - window->DrawList->ChannelsSplit(1 + columns->Count); - window->DrawList->ChannelsSetCurrent(1); - PushColumnClipRect(0); - } - - float offset_0 = GetColumnOffset(columns->Current); - float offset_1 = GetColumnOffset(columns->Current + 1); - float width = offset_1 - offset_0; - PushItemWidth(width * 0.65f); - window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; -} - -void ImGui::EndColumns() -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - ImGuiColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - PopItemWidth(); - if (columns->Count > 1) - { - PopClipRect(); - window->DrawList->ChannelsMerge(); - } - - const ImGuiColumnsFlags flags = columns->Flags; - columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - window->DC.CursorPos.y = columns->LineMaxY; - if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize)) - window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent - - // Draw columns borders and handle resize - // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy - bool is_being_resized = false; - if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) - { - // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. - const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); - const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); - int dragging_column = -1; - for (int n = 1; n < columns->Count; n++) - { - ImGuiColumnData* column = &columns->Columns[n]; - float x = window->Pos.x + GetColumnOffset(n); - const ImGuiID column_id = columns->ID + ImGuiID(n); - const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; - const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); - KeepAliveID(column_id); - if (IsClippedEx(column_hit_rect, column_id, false)) - continue; - - bool hovered = false, held = false; - if (!(flags & ImGuiColumnsFlags_NoResize)) - { - ButtonBehavior(column_hit_rect, column_id, &hovered, &held); - if (hovered || held) - g.MouseCursor = ImGuiMouseCursor_ResizeEW; - if (held && !(column->Flags & ImGuiColumnsFlags_NoResize)) - dragging_column = n; - } - - // Draw column - const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); - const float xi = (float)(int)x; - window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); - } - - // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. - if (dragging_column != -1) - { - if (!columns->IsBeingResized) - for (int n = 0; n < columns->Count + 1; n++) - columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; - columns->IsBeingResized = is_being_resized = true; - float x = GetDraggedColumnOffset(columns, dragging_column); - SetColumnOffset(dragging_column, x); - } - } - columns->IsBeingResized = is_being_resized; - - window->WorkRect = columns->HostWorkRect; - window->DC.CurrentColumns = NULL; - window->DC.ColumnsOffset.x = 0.0f; - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); -} - -// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] -void ImGui::Columns(int columns_count, const char* id, bool border) -{ - ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(columns_count >= 1); - - ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); - //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior - ImGuiColumns* columns = window->DC.CurrentColumns; - if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) - return; - - if (columns != NULL) - EndColumns(); - - if (columns_count != 1) - BeginColumns(id, columns_count, flags); -} - //----------------------------------------------------------------------------- // [SECTION] DRAG AND DROP @@ -10072,7 +9683,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); for (int column_n = 0; column_n < columns->Columns.Size; column_n++) - ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm)); + ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm)); ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index 33f71139..2eacac94 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1563,6 +1563,8 @@ namespace ImGui IMGUI_API void PopColumnsBackground(); IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count); IMGUI_API ImGuiColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); + IMGUI_API float GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm); + IMGUI_API float GetColumnNormFromOffset(const ImGuiColumns* columns, float offset); // Tab Bars IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 03a2c508..0b2b2be7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -24,6 +24,7 @@ Index of this file: // [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. // [SECTION] Widgets: BeginTabBar, EndTabBar, etc. // [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. */ @@ -7088,3 +7089,409 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, return close_button_pressed; } + + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. +// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. +//------------------------------------------------------------------------- +// - GetColumnIndex() +// - GetColumnCount() +// - GetColumnOffset() +// - GetColumnWidth() +// - SetColumnOffset() +// - SetColumnWidth() +// - PushColumnClipRect() [Internal] +// - PushColumnsBackground() [Internal] +// - PopColumnsBackground() [Internal] +// - FindOrCreateColumns() [Internal] +// - GetColumnsID() [Internal] +// - BeginColumns() +// - NextColumn() +// - EndColumns() +// - Columns() +//------------------------------------------------------------------------- + +int ImGui::GetColumnIndex() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; +} + +int ImGui::GetColumnsCount() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; +} + +float ImGui::GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm) +{ + return offset_norm * (columns->OffMaxX - columns->OffMinX); +} + +float ImGui::GetColumnNormFromOffset(const ImGuiColumns* columns, float offset) +{ + return offset / (columns->OffMaxX - columns->OffMinX); +} + +static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; + +static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. + IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; + x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); + if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) + x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); + + return x; +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const float t = columns->Columns[column_index].OffsetNorm; + const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); + return x_offset; +} + +static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false) +{ + if (column_index < 0) + column_index = columns->Current; + + float offset_norm; + if (before_resize) + offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; + else + offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; + return ImGui::GetColumnOffsetFromNorm(columns, offset_norm); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1); + const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; + + if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) + offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); + columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX); + + if (preserve_width) + SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); +} + +void ImGui::SetColumnWidth(int column_index, float width) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); +} + +void ImGui::PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + if (column_index < 0) + column_index = columns->Current; + + ImGuiColumnData* column = &columns->Columns[column_index]; + PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); +} + +// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) +void ImGui::PushColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + window->DrawList->ChannelsSetCurrent(0); + int cmd_size = window->DrawList->CmdBuffer.Size; + PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); + IM_UNUSED(cmd_size); + IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd +} + +void ImGui::PopColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiColumns* columns = window->DC.CurrentColumns; + window->DrawList->ChannelsSetCurrent(columns->Current + 1); + PopClipRect(); +} + +ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) +{ + // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. + for (int n = 0; n < window->ColumnsStorage.Size; n++) + if (window->ColumnsStorage[n].ID == id) + return &window->ColumnsStorage[n]; + + window->ColumnsStorage.push_back(ImGuiColumns()); + ImGuiColumns* columns = &window->ColumnsStorage.back(); + columns->ID = id; + return columns; +} + +ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) +{ + ImGuiWindow* window = GetCurrentWindow(); + + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (str_id ? 0 : columns_count)); + ImGuiID id = window->GetID(str_id ? str_id : "columns"); + PopID(); + + return id; +} + +void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(columns_count >= 1); + IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported + + // Acquire storage for the columns set + ImGuiID id = GetColumnsID(str_id, columns_count); + ImGuiColumns* columns = FindOrCreateColumns(window, id); + IM_ASSERT(columns->ID == id); + columns->Current = 0; + columns->Count = columns_count; + columns->Flags = flags; + window->DC.CurrentColumns = columns; + + // Set state for first column + columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; + columns->OffMaxX = ImMax(window->WorkRect.Max.x - window->Pos.x, columns->OffMinX + 1.0f); + columns->HostCursorPosY = window->DC.CursorPos.y; + columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; + columns->HostClipRect = window->ClipRect; + columns->HostWorkRect = window->WorkRect; + columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + + // Clear data if columns count changed + if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) + columns->Columns.resize(0); + + // Initialize default widths + columns->IsFirstFrame = (columns->Columns.Size == 0); + if (columns->Columns.Size == 0) + { + columns->Columns.reserve(columns_count + 1); + for (int n = 0; n < columns_count + 1; n++) + { + ImGuiColumnData column; + column.OffsetNorm = n / (float)columns_count; + columns->Columns.push_back(column); + } + } + + for (int n = 0; n < columns_count; n++) + { + // Compute clipping rectangle + ImGuiColumnData* column = &columns->Columns[n]; + float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n)); + float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); + column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); + column->ClipRect.ClipWith(window->ClipRect); + } + + if (columns->Count > 1) + { + window->DrawList->ChannelsSplit(1 + columns->Count); + window->DrawList->ChannelsSetCurrent(1); + PushColumnClipRect(0); + } + + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; +} + +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.CurrentColumns == NULL) + return; + + ImGuiContext& g = *GImGui; + ImGuiColumns* columns = window->DC.CurrentColumns; + + if (columns->Count == 1) + { + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + IM_ASSERT(columns->Current == 0); + return; + } + PopItemWidth(); + PopClipRect(); + + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + if (++columns->Current < columns->Count) + { + // Columns 1+ cancel out IndentX + // FIXME-COLUMNS: Unnecessary, could be locked? + window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; + window->DrawList->ChannelsSetCurrent(columns->Current + 1); + } + else + { + // New row/line + window->DC.ColumnsOffset.x = 0.0f; + window->DrawList->ChannelsSetCurrent(1); + columns->Current = 0; + columns->LineMinY = columns->LineMaxY; + } + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->DC.CursorPos.y = columns->LineMinY; + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = 0.0f; + + PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? + + // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; +} + +void ImGui::EndColumns() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + ImGuiColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + PopItemWidth(); + if (columns->Count > 1) + { + PopClipRect(); + window->DrawList->ChannelsMerge(); + } + + const ImGuiColumnsFlags flags = columns->Flags; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = columns->LineMaxY; + if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize)) + window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent + + // Draw columns borders and handle resize + // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy + bool is_being_resized = false; + if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) + { + // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. + const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); + const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); + int dragging_column = -1; + for (int n = 1; n < columns->Count; n++) + { + ImGuiColumnData* column = &columns->Columns[n]; + float x = window->Pos.x + GetColumnOffset(n); + const ImGuiID column_id = columns->ID + ImGuiID(n); + const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; + const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); + KeepAliveID(column_id); + if (IsClippedEx(column_hit_rect, column_id, false)) + continue; + + bool hovered = false, held = false; + if (!(flags & ImGuiColumnsFlags_NoResize)) + { + ButtonBehavior(column_hit_rect, column_id, &hovered, &held); + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeEW; + if (held && !(column->Flags & ImGuiColumnsFlags_NoResize)) + dragging_column = n; + } + + // Draw column + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + const float xi = (float)(int)x; + window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); + } + + // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. + if (dragging_column != -1) + { + if (!columns->IsBeingResized) + for (int n = 0; n < columns->Count + 1; n++) + columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; + columns->IsBeingResized = is_being_resized = true; + float x = GetDraggedColumnOffset(columns, dragging_column); + SetColumnOffset(dragging_column, x); + } + } + columns->IsBeingResized = is_being_resized; + + window->WorkRect = columns->HostWorkRect; + window->DC.CurrentColumns = NULL; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); +} + +// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] +void ImGui::Columns(int columns_count, const char* id, bool border) +{ + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); + + ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); + //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior + ImGuiColumns* columns = window->DC.CurrentColumns; + if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) + return; + + if (columns != NULL) + EndColumns(); + + if (columns_count != 1) + BeginColumns(id, columns_count, flags); +} + +//------------------------------------------------------------------------- From 61c7f0194e9027f86b3bc476f0a7db4129d54e5c Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Jul 2019 15:11:52 -0700 Subject: [PATCH 479/566] Misc: Made Button(), ColorButton() not trigger an "edited" event leading to IsItemDeactivatedAfterEdit() returning true. This also effectively make ColorEdit4() not incorrect trigger IsItemDeactivatedAfterEdit() when clicking the color button to open the picker popup. (#1875) Demo: Added Button with repeater and InputFloat with +/- button to the status query test demo. --- docs/CHANGELOG.txt | 3 +++ imgui_demo.cpp | 32 +++++++++++++------------------- imgui_widgets.cpp | 5 ----- 3 files changed, 16 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c7a88164..0bcc2136 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,9 @@ Other Changes: - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. +- Misc: Made Button(), ColorButton() not trigger an "edited" event leading to IsItemDeactivatedAfterEdit() + returning true. This also effectively make ColorEdit4() not incorrect trigger IsItemDeactivatedAfterEdit() + when clicking the color button to open the picker popup. (#1875) - Misc: Added IMGUI_DISABLE_METRICS_WINDOW imconfig.h setting to explicitly compile out ShowMetricsWindow(). - Debug, Metrics: Added "Tools->Item Picker" tool which allow clicking on a widget to break in the debugger within the item code. The tool calls IM_DEBUG_BREAK() which can be redefined in imconfig.h if needed. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e1c07dcf..756f8ada 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1545,28 +1545,22 @@ static void ShowDemoWindowWidgets() static bool b = false; static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; static char str[16] = {}; - ImGui::RadioButton("Text", &item_type, 0); - ImGui::RadioButton("Button", &item_type, 1); - ImGui::RadioButton("Checkbox", &item_type, 2); - ImGui::RadioButton("SliderFloat", &item_type, 3); - ImGui::RadioButton("InputText", &item_type, 4); - ImGui::RadioButton("InputFloat3", &item_type, 5); - ImGui::RadioButton("ColorEdit4", &item_type, 6); - ImGui::RadioButton("MenuItem", &item_type, 7); - ImGui::RadioButton("TreeNode (w/ double-click)", &item_type, 8); - ImGui::RadioButton("ListBox", &item_type, 9); - ImGui::Separator(); + ImGui::Combo("Item Type", &item_type, "Text\0Button\0Button (w/ repeat)\0Checkbox\0SliderFloat\0InputText\0InputFloat\0InputFloat3\0ColorEdit4\0MenuItem\0TreeNode (w/ double-click)\0ListBox\0"); + ImGui::SameLine(); + HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions."); bool ret = false; if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button - if (item_type == 2) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox - if (item_type == 3) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item - if (item_type == 4) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) - if (item_type == 5) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) - if (item_type == 6) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) - if (item_type == 7) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) - if (item_type == 8) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. - if (item_type == 9) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } + if (item_type == 2) { ImGui::PushButtonRepeat(true); ret = ImGui::Button("ITEM: Button"); ImGui::PopButtonRepeat(); } // Testing button (with repeater) + if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox + if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item + if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing) + if (item_type == 6) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input + if (item_type == 7) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 8) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged) + if (item_type == 9) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy) + if (item_type == 10){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. + if (item_type == 11){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } ImGui::BulletText( "Return value = %d\n" "IsItemFocused() = %d\n" diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0b2b2be7..53fab788 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -626,8 +626,6 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); - if (pressed) - MarkItemEdited(id); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); @@ -4840,9 +4838,6 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered) ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); - if (pressed) - MarkItemEdited(id); - return pressed; } From e28d20c3e2d33261f2542095751561ea3022f6d0 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Jul 2019 17:09:47 -0700 Subject: [PATCH 480/566] Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column would wrongly use a WindowPadding.x instead of ItemSpacing.x like it always did. (#125, #2666) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 16 ++++++++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0bcc2136..10d36d08 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,8 @@ Other Changes: - Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Combo: Hide arrow when there's not enough space even for the square button. - TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). +- Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column + would wrongly use a WindowPadding.x instead of ItemSpacing.x like it always did. (#125, #2666) - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 53fab788..25057426 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7295,8 +7295,10 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag window->DC.CurrentColumns = columns; // Set state for first column - columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; - columns->OffMaxX = ImMax(window->WorkRect.Max.x - window->Pos.x, columns->OffMinX + 1.0f); + const float column_padding = g.Style.ItemSpacing.x; + columns->OffMinX = window->DC.Indent.x - column_padding; + columns->OffMaxX = window->WorkRect.Max.x - window->Pos.x; + columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostClipRect = window->ClipRect; @@ -7343,7 +7345,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); - window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; } void ImGui::NextColumn() @@ -7364,17 +7366,19 @@ void ImGui::NextColumn() PopItemWidth(); PopClipRect(); + const float column_padding = g.Style.ItemSpacing.x; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); if (++columns->Current < columns->Count) { - // Columns 1+ cancel out IndentX + // Columns 1+ ignore IndentX (by canceling it out) // FIXME-COLUMNS: Unnecessary, could be locked? - window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; + window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding; window->DrawList->ChannelsSetCurrent(columns->Current + 1); } else { // New row/line + // Column 0 honor IndentX window->DC.ColumnsOffset.x = 0.0f; window->DrawList->ChannelsSetCurrent(1); columns->Current = 0; @@ -7392,7 +7396,7 @@ void ImGui::NextColumn() float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); - window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; } void ImGui::EndColumns() From 6c16ba649092bc90e219d30990f53ee8c59abc7c Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 17 Jul 2019 18:40:48 -0700 Subject: [PATCH 481/566] Columns: Improved honoring left-most and right-most alignment with various values of ItemSpacing.x and WindowPadding.x. In particular, the right-most edge now reaches up to the clipping rectangle while ensuring that the right-most column clipping width matches others. (#125, #2666) --- docs/CHANGELOG.txt | 3 +++ imgui_widgets.cpp | 19 +++++++++++-------- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 10d36d08..d60e7cd1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,9 @@ Other Changes: - TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). - Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column would wrongly use a WindowPadding.x instead of ItemSpacing.x like it always did. (#125, #2666) +- Columns: Improved honoring left-most and right-most alignment with various values of ItemSpacing.x and + WindowPadding.x. In particular, the right-most edge now reaches up to the clipping rectangle while + ensuring that the right-most column clipping width matches others. (#125, #2666) - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 25057426..61ed2267 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7294,18 +7294,19 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->Flags = flags; window->DC.CurrentColumns = columns; - // Set state for first column - const float column_padding = g.Style.ItemSpacing.x; - columns->OffMinX = window->DC.Indent.x - column_padding; - columns->OffMaxX = window->WorkRect.Max.x - window->Pos.x; - columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostClipRect = window->ClipRect; columns->HostWorkRect = window->WorkRect; + + // Set state for first column + // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect + const float column_padding = g.Style.ItemSpacing.x; + const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); + columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f); + columns->OffMaxX = ImMin(window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f), window->WorkRect.Max.x + half_clip_extend_x) - window->Pos.x; + columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; - window->DC.ColumnsOffset.x = 0.0f; - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Clear data if columns count changed if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) @@ -7345,6 +7346,8 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); + window->DC.ColumnsOffset.x = columns->OffMinX - window->DC.Indent.x + column_padding; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; } @@ -7379,7 +7382,7 @@ void ImGui::NextColumn() { // New row/line // Column 0 honor IndentX - window->DC.ColumnsOffset.x = 0.0f; + window->DC.ColumnsOffset.x = columns->OffMinX - window->DC.Indent.x + column_padding; window->DrawList->ChannelsSetCurrent(1); columns->Current = 0; columns->LineMinY = columns->LineMaxY; From 44336950e9590f40ef89b00bad1841d46d1ac391 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jul 2019 11:22:39 -0700 Subject: [PATCH 482/566] Revert "Columns: Improved honoring left-most and right-most alignment with various values of ItemSpacing.x and WindowPadding.x. In particular, the right-most edge now reaches up to the clipping rectangle while ensuring that the right-most column clipping width matches others. (#125, #2666)" This reverts commit 6c16ba649092bc90e219d30990f53ee8c59abc7c. --- docs/CHANGELOG.txt | 3 --- imgui_widgets.cpp | 19 ++++++++----------- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d60e7cd1..10d36d08 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,9 +58,6 @@ Other Changes: - TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). - Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column would wrongly use a WindowPadding.x instead of ItemSpacing.x like it always did. (#125, #2666) -- Columns: Improved honoring left-most and right-most alignment with various values of ItemSpacing.x and - WindowPadding.x. In particular, the right-most edge now reaches up to the clipping rectangle while - ensuring that the right-most column clipping width matches others. (#125, #2666) - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 61ed2267..25057426 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7294,19 +7294,18 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->Flags = flags; window->DC.CurrentColumns = columns; + // Set state for first column + const float column_padding = g.Style.ItemSpacing.x; + columns->OffMinX = window->DC.Indent.x - column_padding; + columns->OffMaxX = window->WorkRect.Max.x - window->Pos.x; + columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostClipRect = window->ClipRect; columns->HostWorkRect = window->WorkRect; - - // Set state for first column - // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect - const float column_padding = g.Style.ItemSpacing.x; - const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); - columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f); - columns->OffMaxX = ImMin(window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f), window->WorkRect.Max.x + half_clip_extend_x) - window->Pos.x; - columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Clear data if columns count changed if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) @@ -7346,8 +7345,6 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); - window->DC.ColumnsOffset.x = columns->OffMinX - window->DC.Indent.x + column_padding; - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; } @@ -7382,7 +7379,7 @@ void ImGui::NextColumn() { // New row/line // Column 0 honor IndentX - window->DC.ColumnsOffset.x = columns->OffMinX - window->DC.Indent.x + column_padding; + window->DC.ColumnsOffset.x = 0.0f; window->DrawList->ChannelsSetCurrent(1); columns->Current = 0; columns->LineMinY = columns->LineMaxY; From 047dc16af5548335d4a32232b6cf5d09d88603cb Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 19 Jul 2019 10:48:22 -0700 Subject: [PATCH 483/566] Debug Tools: Added DebugStartItemPicker() in imgui_internal.h to facilitate binding this anywhere in user's tool. Adedd highlight. Added IMGUI_DEBUG_TOOL_ITEM_PICKER_EX to break in ItemAdd(). --- imconfig.h | 3 ++ imgui.cpp | 73 ++++++++++++++++++++++++++++-------------------- imgui_internal.h | 9 ++++-- 3 files changed, 53 insertions(+), 32 deletions(-) diff --git a/imconfig.h b/imconfig.h index 16f8c827..2b771298 100644 --- a/imconfig.h +++ b/imconfig.h @@ -80,6 +80,9 @@ // Use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging. //#define IM_DEBUG_BREAK IM_ASSERT(0) //#define IM_DEBUG_BREAK __debugbreak() +// Have the Item Picker break in the ItemAdd() function instead of ItemHoverable() - which is earlier in the code, will catch a few extra items, allow picking items other than Hovered one. +// This adds a small runtime cost which is why it is not enabled by default. +//#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* diff --git a/imgui.cpp b/imgui.cpp index 659239df..3b9996a3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2861,16 +2861,6 @@ void ImGui::SetHoveredID(ImGuiID id) g.HoveredIdAllowOverlap = false; if (id != 0 && g.HoveredIdPreviousFrame != id) g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f; - - // [DEBUG] Item Picker tool! - // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making - // the cost of this tool near-zero. We would get slightly better call-stack if we made the test in ItemAdd() - // but that would incur a slightly higher cost and may require us to hide this feature behind a define. - if (id != 0 && id == g.DebugBreakItemId) - { - IM_DEBUG_BREAK(); - g.DebugBreakItemId = 0; - } } ImGuiID ImGui::GetHoveredID() @@ -2979,6 +2969,15 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id); + + // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd() +#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX + if (id == g.DebugItemPickerBreakID) + { + IM_DEBUG_BREAK(); + g.DebugItemPickerBreakID = 0; + } +#endif } window->DC.LastItemId = id; @@ -3067,6 +3066,17 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) return false; SetHoveredID(id); + + // [DEBUG] Item Picker tool! + // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making + // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered + // items if we perform the test in ItemAdd(), but that would incur a small runtime cost. + // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd(). + if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id) + GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255)); + if (g.DebugItemPickerBreakID == id) + IM_DEBUG_BREAK(); + return true; } @@ -3787,6 +3797,27 @@ void ImGui::NewFrame() g.BeginPopupStack.resize(0); ClosePopupsOverWindow(g.NavWindow, false); + // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. + g.DebugItemPickerBreakID = 0; + if (g.DebugItemPickerActive) + { + const ImGuiID hovered_id = g.HoveredIdPreviousFrame; + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (ImGui::IsKeyPressedMap(ImGuiKey_Escape)) + g.DebugItemPickerActive = false; + if (ImGui::IsMouseClicked(0) && hovered_id) + { + g.DebugItemPickerBreakID = hovered_id; + g.DebugItemPickerActive = false; + } + ImGui::SetNextWindowBgAlpha(0.60f); + ImGui::BeginTooltip(); + ImGui::Text("HoveredId: 0x%08X", hovered_id); + ImGui::Text("Press ESC to abort picking."); + ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!"); + ImGui::EndTooltip(); + } + // Create implicit/fallback window - which we will only render it if the user has added something to it. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. // This fallback is particularly important as it avoid ImGui:: calls from crashing. @@ -9801,27 +9832,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("Tools")) { - static bool picking_enabled = false; + // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted. if (ImGui::Button("Item Picker..")) - picking_enabled = true; - if (picking_enabled) - { - const ImGuiID hovered_id = g.HoveredIdPreviousFrame; - ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); - if (ImGui::IsKeyPressedMap(ImGuiKey_Escape)) - picking_enabled = false; - if (ImGui::IsMouseClicked(0) && hovered_id) - { - g.DebugBreakItemId = hovered_id; - picking_enabled = false; - } - ImGui::SetNextWindowBgAlpha(0.5f); - ImGui::BeginTooltip(); - ImGui::Text("HoveredId: 0x%08X", hovered_id); - ImGui::Text("Press ESC to abort picking."); - ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!"); - ImGui::EndTooltip(); - } + ImGui::DebugStartItemPicker(); ImGui::Checkbox("Show windows begin order", &show_windows_begin_order); ImGui::Checkbox("Show windows rectangles", &show_windows_rects); diff --git a/imgui_internal.h b/imgui_internal.h index 2eacac94..366c682c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1029,7 +1029,8 @@ struct ImGuiContext int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. // Debug Tools - ImGuiID DebugBreakItemId; + bool DebugItemPickerActive; + ImGuiID DebugItemPickerBreakID; // Will call IM_DEBUG_BREAK() when encountering this id // Misc float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds. @@ -1156,7 +1157,8 @@ struct ImGuiContext LogDepthRef = 0; LogDepthToExpand = LogDepthToExpandDefault = 2; - DebugBreakItemId = 0; + DebugItemPickerActive = false; + DebugItemPickerBreakID = 0; memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); FramerateSecPerFrameIdx = 0; @@ -1658,6 +1660,9 @@ namespace ImGui IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp); + // Debug Tools + inline void DebugStartItemPicker() { GImGui->DebugItemPickerActive = true; } + } // namespace ImGui // ImFontAtlas internals From 493795cdd1890d9cf1b2648c3e7ca9993f1d8971 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jul 2019 12:11:00 -0700 Subject: [PATCH 484/566] Columns: Fix support for BeginColumns() with a count of 1 (not that this isn't available via the old Columns() api). Tweaked Demo to facilitate testing for it. --- imgui_demo.cpp | 9 +++++++-- imgui_widgets.cpp | 13 +++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 756f8ada..b59fe602 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2590,11 +2590,16 @@ static void ShowDemoWindowColumns() // NB: Future columns API should allow automatic horizontal borders. static bool h_borders = true; static bool v_borders = true; + static int columns_count = 4; + const int lines_count = 3; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); + ImGui::DragInt("##columns_count", &columns_count, 0.1f, 1, 10, "%d columns"); + ImGui::SameLine(); ImGui::Checkbox("horizontal", &h_borders); ImGui::SameLine(); ImGui::Checkbox("vertical", &v_borders); - ImGui::Columns(4, NULL, v_borders); - for (int i = 0; i < 4 * 3; i++) + ImGui::Columns(columns_count, NULL, v_borders); + for (int i = 0; i < columns_count * lines_count; i++) { if (h_borders && ImGui::GetColumnIndex() == 0) ImGui::Separator(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 25057426..0878b46c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7236,6 +7236,8 @@ void ImGui::PushColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; window->DrawList->ChannelsSetCurrent(0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); @@ -7247,6 +7249,8 @@ void ImGui::PopColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; window->DrawList->ChannelsSetCurrent(columns->Current + 1); PopClipRect(); } @@ -7294,15 +7298,16 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->Flags = flags; window->DC.CurrentColumns = columns; + columns->HostCursorPosY = window->DC.CursorPos.y; + columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; + columns->HostClipRect = window->ClipRect; + columns->HostWorkRect = window->WorkRect; + // Set state for first column const float column_padding = g.Style.ItemSpacing.x; columns->OffMinX = window->DC.Indent.x - column_padding; columns->OffMaxX = window->WorkRect.Max.x - window->Pos.x; columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); - columns->HostCursorPosY = window->DC.CursorPos.y; - columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; - columns->HostClipRect = window->ClipRect; - columns->HostWorkRect = window->WorkRect; columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); From 4abc2a82e0f258288ec252d810a1ab772619a528 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jul 2019 13:28:40 -0700 Subject: [PATCH 485/566] Columns: Made the right-most edge reaches up to the clipping rectangle (removing WindowPadding.x*0.5 worth of asymmetrical/extraneous padding). (#125, #2666) + Moved a few things in BeginColumns(). --- docs/CHANGELOG.txt | 3 +++ imgui_widgets.cpp | 9 ++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 10d36d08..3722438f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,9 @@ Other Changes: - TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). - Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column would wrongly use a WindowPadding.x instead of ItemSpacing.x like it always did. (#125, #2666) +- Columns: Made the right-most edge reaches up to the clipping rectangle (removing half of WindowPadding.x + worth of asymmetrical/extraneous padding, note that there's another half that conservatively has to offset + the right-most column, otherwise it's clipping width won't match the other column). (#125, #2666) - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0878b46c..3c2405ff 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7304,13 +7304,13 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->HostWorkRect = window->WorkRect; // Set state for first column + // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect const float column_padding = g.Style.ItemSpacing.x; + const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); columns->OffMinX = window->DC.Indent.x - column_padding; - columns->OffMaxX = window->WorkRect.Max.x - window->Pos.x; + columns->OffMaxX = window->WorkRect.Max.x + half_clip_extend_x - window->Pos.x; columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; - window->DC.ColumnsOffset.x = 0.0f; - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Clear data if columns count changed if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) @@ -7346,10 +7346,13 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag PushColumnClipRect(0); } + // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user. float offset_0 = GetColumnOffset(columns->Current); float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; } From b443bc0a64d5e22d445d2c9cb52f7f39da6b98c9 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jul 2019 14:22:33 -0700 Subject: [PATCH 486/566] Columns: Improved honoring alignment with various values of ItemSpacing.x and WindowPadding.x. (#125, #2666) --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3722438f..93f7a7fc 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,7 @@ Other Changes: - Columns: Made the right-most edge reaches up to the clipping rectangle (removing half of WindowPadding.x worth of asymmetrical/extraneous padding, note that there's another half that conservatively has to offset the right-most column, otherwise it's clipping width won't match the other column). (#125, #2666) +- Columns: Improved honoring alignment with various values of ItemSpacing.x and WindowPadding.x. (#125, #2666) - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3c2405ff..1373ea74 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7307,9 +7307,10 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect const float column_padding = g.Style.ItemSpacing.x; const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); - columns->OffMinX = window->DC.Indent.x - column_padding; - columns->OffMaxX = window->WorkRect.Max.x + half_clip_extend_x - window->Pos.x; - columns->OffMaxX = ImMax(columns->OffMaxX, columns->OffMinX + 1.0f); + const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f); + const float max_2 = window->WorkRect.Max.x + half_clip_extend_x; + columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f); + columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f); columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; // Clear data if columns count changed @@ -7351,7 +7352,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); - window->DC.ColumnsOffset.x = 0.0f; + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; } @@ -7387,7 +7388,7 @@ void ImGui::NextColumn() { // New row/line // Column 0 honor IndentX - window->DC.ColumnsOffset.x = 0.0f; + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); window->DrawList->ChannelsSetCurrent(1); columns->Current = 0; columns->LineMinY = columns->LineMaxY; From c37f21788fcd8824d807c575947062223490b807 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 21 Jul 2019 11:23:15 -0700 Subject: [PATCH 487/566] Columns: Made GetColumnOffset() and GetColumnWidth() behave when there's no column set, consistently with other column functions + fixed Columns demo (#2683) --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 4 +++- imgui_widgets.cpp | 9 ++++++--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 93f7a7fc..c06e2e57 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Other Changes: - Columns: Improved honoring alignment with various values of ItemSpacing.x and WindowPadding.x. (#125, #2666) - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). +- Columns: Made GetColumnOffset() and GetColumnWidth() behave when there's no column set, consistently with + other column functions. (#2683) - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b59fe602..53e2bf1c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2593,7 +2593,9 @@ static void ShowDemoWindowColumns() static int columns_count = 4; const int lines_count = 3; ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); - ImGui::DragInt("##columns_count", &columns_count, 0.1f, 1, 10, "%d columns"); + ImGui::DragInt("##columns_count", &columns_count, 0.1f, 2, 10, "%d columns"); + if (columns_count < 2) + columns_count = 2; ImGui::SameLine(); ImGui::Checkbox("horizontal", &h_borders); ImGui::SameLine(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1373ea74..c42c518f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7152,7 +7152,8 @@ float ImGui::GetColumnOffset(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); + if (columns == NULL) + return 0.0f; if (column_index < 0) column_index = columns->Current; @@ -7178,9 +7179,11 @@ static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool befo float ImGui::GetColumnWidth(int column_index) { - ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; ImGuiColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); + if (columns == NULL) + return GetContentRegionAvail().x; if (column_index < 0) column_index = columns->Current; From 47f5ad32b77a6d0a19f5ac04cb5d816e24da4133 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 21 Jul 2019 12:05:04 -0700 Subject: [PATCH 488/566] Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. (#2109) --- imgui.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 113bca25..437a7196 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3782,6 +3782,13 @@ void ImGui::NewFrame() if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) g.IO.ConfigWindowsResizeFromEdges = false; + // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. + const ImGuiColumnsFlags prev_config_flags = g.ConfigFlagsForFrame; + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (prev_config_flags & ImGuiConfigFlags_DockingEnable) == 0) + IM_ASSERT(0 && "Please DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (prev_config_flags & ImGuiConfigFlags_ViewportsEnable) == 0) + IM_ASSERT(0 && "Please ViewportEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + // Perform simple checks: multi-viewport and platform windows support if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { From f1ba217a92846416475576b5983652f7f716cd71 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 21 Jul 2019 12:13:44 -0700 Subject: [PATCH 489/566] Internals: Extracted some code out of the NewFrame() function. --- imgui.cpp | 51 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3b9996a3..1cfaeabf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1089,6 +1089,7 @@ static int FindWindowFocusIndex(ImGuiWindow* window); static void UpdateMouseInputs(); static void UpdateMouseWheel(); static bool UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); +static void UpdateDebugToolItemPicker(); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, 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); @@ -3584,15 +3585,10 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } -void ImGui::NewFrame() +static void NewFrameSanityChecks() { - IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); ImGuiContext& g = *GImGui; -#ifdef IMGUI_ENABLE_TEST_ENGINE - ImGuiTestEngineHook_PreNewFrame(&g); -#endif - // Check user data // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) IM_ASSERT(g.Initialized); @@ -3605,7 +3601,6 @@ void ImGui::NewFrame() IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!"); IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); - for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); @@ -3616,6 +3611,19 @@ void ImGui::NewFrame() // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) g.IO.ConfigWindowsResizeFromEdges = false; +} + +void ImGui::NewFrame() +{ + IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); + ImGuiContext& g = *GImGui; + +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGuiTestEngineHook_PreNewFrame(&g); +#endif + + // Check and assert for various common IO and Configuration mistakes + NewFrameSanityChecks(); // Load settings on first frame (if not explicitly loaded manually before) if (!g.SettingsLoaded) @@ -3798,6 +3806,24 @@ void ImGui::NewFrame() ClosePopupsOverWindow(g.NavWindow, false); // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. + UpdateDebugToolItemPicker(); + + // Create implicit/fallback window - which we will only render it if the user has added something to it. + // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. + // This fallback is particularly important as it avoid ImGui:: calls from crashing. + SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); + Begin("Debug##Default"); + g.FrameScopePushedImplicitWindow = true; + +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGuiTestEngineHook_PostNewFrame(&g); +#endif +} + +// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. +void ImGui::UpdateDebugToolItemPicker() +{ + ImGuiContext& g = *GImGui; g.DebugItemPickerBreakID = 0; if (g.DebugItemPickerActive) { @@ -3817,17 +3843,6 @@ void ImGui::NewFrame() ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!"); ImGui::EndTooltip(); } - - // Create implicit/fallback window - which we will only render it if the user has added something to it. - // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. - // This fallback is particularly important as it avoid ImGui:: calls from crashing. - SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); - Begin("Debug##Default"); - g.FrameScopePushedImplicitWindow = true; - -#ifdef IMGUI_ENABLE_TEST_ENGINE - ImGuiTestEngineHook_PostNewFrame(&g); -#endif } void ImGui::Initialize(ImGuiContext* context) From 4b44f25c9a5044d230b58deb38196e0a90ac9c68 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 21 Jul 2019 18:19:56 -0700 Subject: [PATCH 490/566] Fixed incorrect application of io.DisplaySafeAreaPadding which would be problematic with multi-viewports when a monitor uses negative coordinates (correct clamping is done right below). (#2674) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 1cfaeabf..a2e22807 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5596,7 +5596,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); if (window_pos_with_pivot) - SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering) + SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) 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 0f86116a69dfbd3d705484d8ba031e10e523335e Mon Sep 17 00:00:00 2001 From: Aaron Cooper <1531573+amc522@users.noreply.github.com> Date: Thu, 18 Jul 2019 17:24:56 -0700 Subject: [PATCH 491/566] Adding an ImGuiKey 'ImGuiKey_EnterSecondary' to support platforms that differentiate the enter (return key) and the numpad enter key. --- examples/imgui_impl_allegro5.cpp | 1 + examples/imgui_impl_glfw.cpp | 1 + examples/imgui_impl_marmalade.cpp | 1 + examples/imgui_impl_osx.mm | 43 ++++++++++++++++--------------- examples/imgui_impl_sdl.cpp | 1 + examples/imgui_impl_win32.cpp | 1 + imgui.h | 1 + imgui_widgets.cpp | 2 +- 8 files changed, 29 insertions(+), 22 deletions(-) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 46893390..8228c416 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -281,6 +281,7 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) io.KeyMap[ImGuiKey_Backspace] = ALLEGRO_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = ALLEGRO_KEY_SPACE; io.KeyMap[ImGuiKey_Enter] = ALLEGRO_KEY_ENTER; + io.KeyMap[ImGuiKey_EnterSecondary] = ALLEGRO_KEY_PAD_ENTER; io.KeyMap[ImGuiKey_Escape] = ALLEGRO_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = ALLEGRO_KEY_A; io.KeyMap[ImGuiKey_C] = ALLEGRO_KEY_C; diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index bcfeac45..c1a27496 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -150,6 +150,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE; io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; + io.KeyMap[ImGuiKey_EnterSecondary] = GLFW_KEY_KP_ENTER; io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index a101c69a..865810ec 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -234,6 +234,7 @@ bool ImGui_Marmalade_Init(bool install_callbacks) io.KeyMap[ImGuiKey_Backspace] = s3eKeyBackspace; io.KeyMap[ImGuiKey_Space] = s3eKeySpace; io.KeyMap[ImGuiKey_Enter] = s3eKeyEnter; + io.KeyMap[ImGuiKey_EnterSecondary] = s3eKeyNumPadEnter; io.KeyMap[ImGuiKey_Escape] = s3eKeyEsc; io.KeyMap[ImGuiKey_A] = s3eKeyA; io.KeyMap[ImGuiKey_C] = s3eKeyC; diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index cfcd3a74..60cb8e23 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -47,27 +47,28 @@ bool ImGui_ImplOSX_Init() // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. const int offset_for_function_keys = 256 - 0xF700; - io.KeyMap[ImGuiKey_Tab] = '\t'; - io.KeyMap[ImGuiKey_LeftArrow] = NSLeftArrowFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_RightArrow] = NSRightArrowFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_UpArrow] = NSUpArrowFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_DownArrow] = NSDownArrowFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_PageUp] = NSPageUpFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_PageDown] = NSPageDownFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_Home] = NSHomeFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_End] = NSEndFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_Insert] = NSInsertFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_Delete] = NSDeleteFunctionKey + offset_for_function_keys; - io.KeyMap[ImGuiKey_Backspace] = 127; - io.KeyMap[ImGuiKey_Space] = 32; - io.KeyMap[ImGuiKey_Enter] = 13; - io.KeyMap[ImGuiKey_Escape] = 27; - io.KeyMap[ImGuiKey_A] = 'A'; - io.KeyMap[ImGuiKey_C] = 'C'; - io.KeyMap[ImGuiKey_V] = 'V'; - io.KeyMap[ImGuiKey_X] = 'X'; - io.KeyMap[ImGuiKey_Y] = 'Y'; - io.KeyMap[ImGuiKey_Z] = 'Z'; + io.KeyMap[ImGuiKey_Tab] = '\t'; + io.KeyMap[ImGuiKey_LeftArrow] = NSLeftArrowFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_RightArrow] = NSRightArrowFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_UpArrow] = NSUpArrowFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_DownArrow] = NSDownArrowFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_PageUp] = NSPageUpFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_PageDown] = NSPageDownFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_Home] = NSHomeFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_End] = NSEndFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_Insert] = NSInsertFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_Delete] = NSDeleteFunctionKey + offset_for_function_keys; + io.KeyMap[ImGuiKey_Backspace] = 127; + io.KeyMap[ImGuiKey_Space] = 32; + io.KeyMap[ImGuiKey_Enter] = 13; + io.KeyMap[ImGuiKey_EnterSecondary] = 13; + io.KeyMap[ImGuiKey_Escape] = 27; + io.KeyMap[ImGuiKey_A] = 'A'; + io.KeyMap[ImGuiKey_C] = 'C'; + io.KeyMap[ImGuiKey_V] = 'V'; + io.KeyMap[ImGuiKey_X] = 'X'; + io.KeyMap[ImGuiKey_Y] = 'Y'; + io.KeyMap[ImGuiKey_Z] = 'Z'; // Load cursors. Some of them are undocumented. g_MouseCursorHidden = false; diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 0cf937a4..86aa70a1 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -143,6 +143,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window) io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE; io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; + io.KeyMap[ImGuiKey_EnterSecondary] = SDL_SCANCODE_RETURN2; io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE; io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A; io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C; diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 85dede4e..9581e7ca 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -77,6 +77,7 @@ bool ImGui_ImplWin32_Init(void* hwnd) io.KeyMap[ImGuiKey_Backspace] = VK_BACK; io.KeyMap[ImGuiKey_Space] = VK_SPACE; io.KeyMap[ImGuiKey_Enter] = VK_RETURN; + io.KeyMap[ImGuiKey_EnterSecondary] = VK_RETURN; io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; diff --git a/imgui.h b/imgui.h index a81296fd..5aa93677 100644 --- a/imgui.h +++ b/imgui.h @@ -940,6 +940,7 @@ enum ImGuiKey_ ImGuiKey_Backspace, ImGuiKey_Space, ImGuiKey_Enter, + ImGuiKey_EnterSecondary, ImGuiKey_Escape, ImGuiKey_A, // for text edit CTRL+A: select all ImGuiKey_C, // for text edit CTRL+C: copy diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c42c518f..176d2167 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3653,7 +3653,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Enter)) + else if (IsKeyPressedMap(ImGuiKey_Enter) || IsKeyPressedMap(ImGuiKey_EnterSecondary)) { bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) From f0348ddffc41a9ef1e34e930796ab68fe959079e Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 21 Jul 2019 18:39:50 -0700 Subject: [PATCH 492/566] Amend 0f86116, renamed to ImGuiKey_KeyPadEnter Changelog.. (#2677, #2005) --- docs/CHANGELOG.txt | 3 +++ examples/imgui_impl_allegro5.cpp | 3 ++- examples/imgui_impl_glfw.cpp | 3 ++- examples/imgui_impl_glut.cpp | 1 + examples/imgui_impl_marmalade.cpp | 3 ++- examples/imgui_impl_osx.mm | 2 +- examples/imgui_impl_sdl.cpp | 3 ++- examples/imgui_impl_win32.cpp | 2 +- imgui.h | 2 +- imgui_widgets.cpp | 2 +- 10 files changed, 16 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c06e2e57..98cc1960 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,9 @@ Other Changes: - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. +- IO: Added ImGuiKey_KeyPadEnter and support in various back-ends (previously back-ends would need to + specifically redirect key-pad keys to their regular counterpart). This is a temporary attenuating measure + until we actually refactor and add whole sets of keys into the ImGuiKey enum. (#2677, #2005) [@amc522] - Misc: Made Button(), ColorButton() not trigger an "edited" event leading to IsItemDeactivatedAfterEdit() returning true. This also effectively make ColorEdit4() not incorrect trigger IsItemDeactivatedAfterEdit() when clicking the color button to open the picker popup. (#1875) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 8228c416..525ad5c9 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-05-11: Inputs: Don't filter character value from ALLEGRO_EVENT_KEY_CHAR before calling AddInputCharacter(). // 2019-04-30: Renderer: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-11-30: Platform: Added touchscreen support. @@ -281,8 +282,8 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) io.KeyMap[ImGuiKey_Backspace] = ALLEGRO_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = ALLEGRO_KEY_SPACE; io.KeyMap[ImGuiKey_Enter] = ALLEGRO_KEY_ENTER; - io.KeyMap[ImGuiKey_EnterSecondary] = ALLEGRO_KEY_PAD_ENTER; io.KeyMap[ImGuiKey_Escape] = ALLEGRO_KEY_ESCAPE; + io.KeyMap[ImGuiKey_KeyPadEnter] = ALLEGRO_KEY_PAD_ENTER; io.KeyMap[ImGuiKey_A] = ALLEGRO_KEY_A; io.KeyMap[ImGuiKey_C] = ALLEGRO_KEY_C; io.KeyMap[ImGuiKey_V] = ALLEGRO_KEY_V; diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index c1a27496..a9e72c6c 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter(). // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. @@ -150,8 +151,8 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE; io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; - io.KeyMap[ImGuiKey_EnterSecondary] = GLFW_KEY_KP_ENTER; io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; + io.KeyMap[ImGuiKey_KeyPadEnter] = GLFW_KEY_KP_ENTER; io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index 6b800bf1..56d8c553 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -59,6 +59,7 @@ bool ImGui_ImplGLUT_Init() io.KeyMap[ImGuiKey_Space] = ' '; io.KeyMap[ImGuiKey_Enter] = 13; // == CTRL+M io.KeyMap[ImGuiKey_Escape] = 27; + io.KeyMap[ImGuiKey_KeyPadEnter] = 13; // == CTRL+M io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index 865810ec..497a5705 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -12,6 +12,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter(). // 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_Marmalade_RenderDrawData() in the .h file so you can call it yourself. @@ -234,8 +235,8 @@ bool ImGui_Marmalade_Init(bool install_callbacks) io.KeyMap[ImGuiKey_Backspace] = s3eKeyBackspace; io.KeyMap[ImGuiKey_Space] = s3eKeySpace; io.KeyMap[ImGuiKey_Enter] = s3eKeyEnter; - io.KeyMap[ImGuiKey_EnterSecondary] = s3eKeyNumPadEnter; io.KeyMap[ImGuiKey_Escape] = s3eKeyEsc; + io.KeyMap[ImGuiKey_KeyPadEnter] = s3eKeyNumPadEnter; io.KeyMap[ImGuiKey_A] = s3eKeyA; io.KeyMap[ImGuiKey_C] = s3eKeyC; io.KeyMap[ImGuiKey_V] = s3eKeyV; diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 60cb8e23..179306e4 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -61,8 +61,8 @@ bool ImGui_ImplOSX_Init() io.KeyMap[ImGuiKey_Backspace] = 127; io.KeyMap[ImGuiKey_Space] = 32; io.KeyMap[ImGuiKey_Enter] = 13; - io.KeyMap[ImGuiKey_EnterSecondary] = 13; io.KeyMap[ImGuiKey_Escape] = 27; + io.KeyMap[ImGuiKey_KeyPadEnter] = 13; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 86aa70a1..42677581 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application). // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls. @@ -143,8 +144,8 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window) io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE; io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; - io.KeyMap[ImGuiKey_EnterSecondary] = SDL_SCANCODE_RETURN2; io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE; + io.KeyMap[ImGuiKey_KeyPadEnter] = SDL_SCANCODE_RETURN2; io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A; io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C; io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V; diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 9581e7ca..8d46d942 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -77,8 +77,8 @@ bool ImGui_ImplWin32_Init(void* hwnd) io.KeyMap[ImGuiKey_Backspace] = VK_BACK; io.KeyMap[ImGuiKey_Space] = VK_SPACE; io.KeyMap[ImGuiKey_Enter] = VK_RETURN; - io.KeyMap[ImGuiKey_EnterSecondary] = VK_RETURN; io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; + io.KeyMap[ImGuiKey_KeyPadEnter] = VK_RETURN; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; diff --git a/imgui.h b/imgui.h index 5aa93677..ef2014a5 100644 --- a/imgui.h +++ b/imgui.h @@ -940,8 +940,8 @@ enum ImGuiKey_ ImGuiKey_Backspace, ImGuiKey_Space, ImGuiKey_Enter, - ImGuiKey_EnterSecondary, ImGuiKey_Escape, + ImGuiKey_KeyPadEnter, ImGuiKey_A, // for text edit CTRL+A: select all ImGuiKey_C, // for text edit CTRL+C: copy ImGuiKey_V, // for text edit CTRL+V: paste diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 176d2167..13875ea2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3653,7 +3653,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Enter) || IsKeyPressedMap(ImGuiKey_EnterSecondary)) + else if (IsKeyPressedMap(ImGuiKey_Enter) || IsKeyPressedMap(ImGuiKey_KeyPadEnter)) { bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) From 29d9394a41939e8d033814704d5e9bcca516bf37 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 21 Jul 2019 19:06:07 -0700 Subject: [PATCH 493/566] OSX: Disabled default native Mac clipboard copy/paste implementation in core library (added in 1.71), because it needs application to be linked with '-framework ApplicationServices'. It can be explicitly enabled back by using '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h. Re-added equivalent using NSPasteboard api in the imgui_impl_osx.mm experimental back-end. (#2546) --- docs/CHANGELOG.txt | 4 ++++ examples/imgui_impl_osx.mm | 31 +++++++++++++++++++++++++++++-- imconfig.h | 2 +- imgui.cpp | 3 ++- 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 98cc1960..8250c56d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,10 @@ Other Changes: - ImDrawListSplitter: Fixed memory leak when using low-level split api (was not affecting ImDrawList api, also this type was added in 1.71 and not advertised as a public-facing feature). - Fonts: binary_to_compressed_c.cpp: Display an error message if failing to open/read the input font file. +- Backends: OSX: Disabled default native Mac clipboard copy/paste implementation in core library (added in 1.71), + because it needs application to be linked with '-framework ApplicationServices'. It can be explicitly + enabled back by using '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h. Re-added + equivalent using NSPasteboard api in the imgui_impl_osx.mm experimental back-end. (#2546) - Backends: SDL2: Added dummy ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. (#2482, #2632) [@josiahmanson] - Examples: Added SDL2+DirectX11 example application. (#2632, #2612, #2482) [@vincenthamm] diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 179306e4..9042e15f 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -14,6 +14,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-07-21: Readded clipboard handlers as they are not enabled by default in core imgui.cpp (reverted 2019-05-18 change). // 2019-05-28: Inputs: Added mouse cursor shape and visibility support. // 2019-05-18: Misc: Removed clipboard handlers as they are now supported by core imgui.cpp. // 2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range. @@ -81,8 +82,34 @@ bool ImGui_ImplOSX_Init() g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor]; g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor]; - // We don't set the io.SetClipboardTextFn/io.GetClipboardTextFn handlers, - // because imgui.cpp has a default for them that works with OSX. + // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled + // by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line. + // Since we are already in ObjC land here, it is easy for us to add a clipboard handler using the NSPasteboard api. + io.SetClipboardTextFn = [](void*, const char* str) -> void + { + NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; + [pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil]; + [pasteboard setString:[NSString stringWithUTF8String:str] forType:NSPasteboardTypeString]; + }; + + io.GetClipboardTextFn = [](void*) -> const char* + { + NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; + NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]]; + if (![available isEqualToString:NSPasteboardTypeString]) + return NULL; + + NSString* string = [pasteboard stringForType:NSPasteboardTypeString]; + if (string == nil) + return NULL; + + const char* string_c = (const char*)[string UTF8String]; + size_t string_len = strlen(string_c); + static ImVector s_clipboard; + s_clipboard.resize((int)string_len + 1); + strcpy(s_clipboard.Data, string_c); + return s_clipboard.Data; + }; return true; } diff --git a/imconfig.h b/imconfig.h index 2b771298..22a21db0 100644 --- a/imconfig.h +++ b/imconfig.h @@ -34,7 +34,7 @@ //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow. //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). -//#define IMGUI_DISABLE_OSX_FUNCTIONS // [OSX] Won't use and link with any OSX function (clipboard). +//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices'). //#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf. //#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h. //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). diff --git a/imgui.cpp b/imgui.cpp index a2e22807..fdc12c78 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9504,12 +9504,13 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) ::CloseClipboard(); } -#elif defined(__APPLE__) && TARGET_OS_OSX && !defined(IMGUI_DISABLE_OSX_FUNCTIONS) +#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS) #include // Use old API to avoid need for separate .mm file static PasteboardRef main_clipboard = 0; // OSX clipboard implementation +// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line! static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!main_clipboard) From cbd5a21fb0782d489b56430fdbf32d7e08aff583 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 21 Jul 2019 19:26:13 -0700 Subject: [PATCH 494/566] Backends: DX10/DX11: Backup, clear and restore Geometry Shader is any is bound when calling renderer. Backends: DX11: Clear Hull Shader, Domain Shader, Compute Shader before rendering. Not backing/restoring them. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_dx10.cpp | 5 +++++ examples/imgui_impl_dx11.cpp | 13 +++++++++++-- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8250c56d..3869166f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,8 @@ Other Changes: - ImDrawListSplitter: Fixed memory leak when using low-level split api (was not affecting ImDrawList api, also this type was added in 1.71 and not advertised as a public-facing feature). - Fonts: binary_to_compressed_c.cpp: Display an error message if failing to open/read the input font file. +- Backends: DX10/DX11: Backup, clear and restore Geometry Shader is any is bound when calling renderer. +- Backends: DX11: Clear Hull Shader, Domain Shader, Compute Shader before rendering. Not backing/restoring them. - Backends: OSX: Disabled default native Mac clipboard copy/paste implementation in core library (added in 1.71), because it needs application to be linked with '-framework ApplicationServices'. It can be explicitly enabled back by using '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h. Re-added diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 22c4b9d0..6dec6147 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -11,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData(). // 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). @@ -81,6 +82,7 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); ctx->PSSetShader(g_pPixelShader); ctx->PSSetSamplers(0, 1, &g_pFontSampler); + ctx->GSSetShader(NULL); // Setup render state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; @@ -183,6 +185,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ID3D10SamplerState* PSSampler; ID3D10PixelShader* PS; ID3D10VertexShader* VS; + ID3D10GeometryShader* GS; D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology; ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; @@ -201,6 +204,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ctx->PSGetShader(&old.PS); ctx->VSGetShader(&old.VS); ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); + ctx->GSGetShader(&old.GS); ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology); ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); @@ -255,6 +259,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release(); ctx->PSSetShader(old.PS); if (old.PS) old.PS->Release(); ctx->VSSetShader(old.VS); if (old.VS) old.VS->Release(); + ctx->GSSetShader(old.GS); if (old.GS) old.GS->Release(); ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); ctx->IASetPrimitiveTopology(old.PrimitiveTopology); ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 3bcb03a2..89b88dea 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -11,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore. // 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). @@ -81,6 +82,10 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); ctx->PSSetShader(g_pPixelShader, NULL, 0); ctx->PSSetSamplers(0, 1, &g_pFontSampler); + ctx->GSSetShader(NULL, NULL, 0); + ctx->HSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used.. + ctx->DSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used.. + ctx->CSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used.. // Setup blend state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; @@ -185,8 +190,9 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ID3D11SamplerState* PSSampler; ID3D11PixelShader* PS; ID3D11VertexShader* VS; - UINT PSInstancesCount, VSInstancesCount; - ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation + ID3D11GeometryShader* GS; + UINT PSInstancesCount, VSInstancesCount, GSInstancesCount; + ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology; ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; @@ -206,6 +212,8 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount); ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount); ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); + ctx->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount); + ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology); ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); @@ -262,6 +270,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release(); ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release(); ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); + ctx->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release(); for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release(); ctx->IASetPrimitiveTopology(old.PrimitiveTopology); ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); From 363d33f64ea988f11c124207b89d9f4f15f11be9 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 10:23:27 -0700 Subject: [PATCH 495/566] Increased IMGUI_VERSION_NUM to facilitate transition of OSX clipboard support for framework using/embedding any version of imgui. Amend 29d9394. (#2546) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index ef2014a5..cdfa426d 100644 --- a/imgui.h +++ b/imgui.h @@ -47,7 +47,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.72 WIP" -#define IMGUI_VERSION_NUM 17101 +#define IMGUI_VERSION_NUM 17102 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) From 6f8d34768da2c5bf16c67e1385158fcf76ce1598 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 10:54:17 -0700 Subject: [PATCH 496/566] Docking: Removed seemingly unnecessary test in TabItemEx() for undocking tab leading to window move. Added ImGuiDockNode::IsFloatingNode() helper to clarify code intent in various places. --- imgui.cpp | 9 +++++---- imgui.h | 2 +- imgui_internal.h | 1 + imgui_widgets.cpp | 4 +--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 65f11a85..c1d5a351 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11216,7 +11216,7 @@ void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high) for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) - if (node->IsRootNode() && !node->IsDockSpace()) + if (node->IsFloatingNode()) DockNodeUpdate(node); } @@ -11702,7 +11702,7 @@ static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, b // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. - if (node->HostWindow == NULL && !node->IsDockSpace() && node->IsRootNode()) + if (node->HostWindow == NULL && node->IsFloatingNode()) { if (node->AuthorityForPos == ImGuiDataAuthority_Auto) node->AuthorityForPos = ImGuiDataAuthority_Window; @@ -12026,7 +12026,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) DockNodeRemoveTabBar(node); // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) - if (node->Windows.Size <= 1 && node->IsRootNode() && node->IsLeafNode() && !node->IsDockSpace() && !g.IO.ConfigDockingTabBarOnSingleWindows) + if (node->Windows.Size <= 1 && node->IsFloatingNode() && node->IsLeafNode() && !g.IO.ConfigDockingTabBarOnSingleWindows) { if (node->Windows.Size == 1) { @@ -13219,6 +13219,7 @@ ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos) // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) //----------------------------------------------------------------------------- +// [Internal] Called via SetNextWindowDockID() void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time @@ -14156,7 +14157,7 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID)) { buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything - if (node->IsDockSpace && node->HostWindow && node->HostWindow->ParentWindow) + if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name); int contains_window = 0; for (int window_n = 0; window_n < ctx->SettingsWindows.Size; window_n++) diff --git a/imgui.h b/imgui.h index 3a74d7c1..6d488ff3 100644 --- a/imgui.h +++ b/imgui.h @@ -1612,7 +1612,7 @@ struct ImGuiWindowClass ImGuiID ParentViewportId; // Hint for the platform back-end. If non-zero, the platform back-end can create a parent<>child relationship between the platform windows. Not conforming back-ends are free to e.g. parent every viewport to the main viewport or not. ImGuiViewportFlags ViewportFlagsOverrideMask; // Viewport flags to override when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. ImGuiViewportFlags ViewportFlagsOverrideValue; // Viewport flags values to override when a window of this class owns a viewport. - bool DockingAllowUnclassed; // true = can be docked/merged with an unclassed window + bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideMask = ViewportFlagsOverrideValue = 0x00; DockingAllowUnclassed = true; } }; diff --git a/imgui_internal.h b/imgui_internal.h index da83467d..bd1f9aad 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -963,6 +963,7 @@ struct ImGuiDockNode ~ImGuiDockNode(); bool IsRootNode() const { return ParentNode == NULL; } bool IsDockSpace() const { return (LocalFlags & ImGuiDockNodeFlags_DockSpace) != 0; } + bool IsFloatingNode() const { return ParentNode == NULL && (LocalFlags & ImGuiDockNodeFlags_DockSpace) == 0; } bool IsCentralNode() const { return (LocalFlags & ImGuiDockNodeFlags_CentralNode) != 0; } bool IsHiddenTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_HiddenTabBar) != 0; } // Hidden tab bar can be shown back by clicking the small triangle bool IsNoTabBar() const { return (LocalFlags & ImGuiDockNodeFlags_NoTabBar) != 0; } // Never show a tab bar diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ffd026c0..cb69dd4b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6979,10 +6979,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, SetItemAllowOverlap(); // Drag and drop a single floating window node moves it - // FIXME-DOCK: In theory we shouldn't test for the ConfigDockingNodifySingleWindows flag here. - // When our single window node and OnlyNodeWithWindows are working properly we may remove this check here. ImGuiDockNode* node = docked_window ? docked_window->DockNode : NULL; - const bool single_floating_window_node = node && node->IsRootNode() && !node->IsDockSpace() && node->Windows.Size == 1 && g.IO.ConfigDockingTabBarOnSingleWindows; + const bool single_floating_window_node = node && node->IsFloatingNode() && (node->Windows.Size == 1); if (held && single_floating_window_node && IsMouseDragging(0, 0.0f)) { // Move From 0e6a096afdc89219e98aeed49d7875a1ead3ba16 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 11:29:22 -0700 Subject: [PATCH 497/566] Docking: Renamed io.ConfigDockingTabBarOnSingleWindows to io.ConfigDockingAlwaysTabBar. (#2109) Added ImGuiWindowClass::DockingAlwaysTabBar to set on individual windows. --- docs/CHANGELOG.txt | 9 ++++--- examples/example_win32_directx11/main.cpp | 2 +- imgui.cpp | 32 +++++++++++++++++------ imgui.h | 5 ++-- imgui_demo.cpp | 4 +-- imgui_internal.h | 6 +++-- 6 files changed, 39 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index fb921de3..7ea1aec5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,15 +38,16 @@ DOCKING FEATURES - Added Docking system: [BETA] (#2109, #351) - Added ImGuiConfigFlags_DockingEnable flag to enable Docking. Set with `io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;`. - - Added DockSpace() API. + - Added DockSpace(), DockSpaceOverViewport() API. - Added ImGuiDockNodeFlags flags for DockSpace(). - - Added SetNextWindowDock(), SetNextWindowClass() API. - - Added GetWindowDockId(), IsWindowDocked() API. + - Added SetNextWindowDockID(), SetNextWindowClass() API. + - Added GetWindowDockID(), IsWindowDocked() API. - Added ImGuiWindowFlags_NoDocking window flag to disable the possibility for a window to be docked. Popup, Menu and Child windows always have the ImGuiWindowFlags_NoDocking flag set. + - Added ImGuiWindowClass to specify advanced docking/viewport related flags via SetNextWindowClass(). - Added io.ConfigDockingNoSplit option. - Added io.ConfigDockingWithShift option. - - Added io.ConfigDockingTabBarOnSingleWindows option. + - Added io.ConfigDockingAlwaysTabBar option. - Added io.ConfigDockingTransparentPayload option. - Style: Added ImGuiCol_DockingPreview, ImGuiCol_DockingEmptyBg colors. - Demo: Added "DockSpace" example app showcasing use of explicit dockspace nodes. diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index e8c1057d..d765ba1b 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -55,7 +55,7 @@ int main(int, char**) //io.ConfigViewportsNoAutoMerge = true; //io.ConfigViewportsNoTaskBarIcon = true; //io.ConfigViewportsNoDefaultParent = true; - //io.ConfigDockingTabBarOnSingleWindows = true; + //io.ConfigDockingAlwaysTabBar = true; //io.ConfigDockingTransparentPayload = true; #if 1 io.ConfigFlags |= ImGuiConfigFlags_DpiEnableScaleFonts; // FIXME-DPI: THIS CURRENTLY DOESN'T WORK AS EXPECTED. DON'T USE IN USER APP! diff --git a/imgui.cpp b/imgui.cpp index c1d5a351..97cb014c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1262,7 +1262,7 @@ ImGuiIO::ImGuiIO() // Docking options (when ImGuiConfigFlags_DockingEnable is set) ConfigDockingNoSplit = false; ConfigDockingWithShift = false; - ConfigDockingTabBarOnSingleWindows = false; + ConfigDockingAlwaysTabBar = false; ConfigDockingTransparentPayload = false; // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) @@ -2731,6 +2731,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) SkipItems = false; Appearing = false; Hidden = false; + FallbackWindow = false; HasCloseButton = false; ResizeBorderHeld = -1; BeginCount = 0; @@ -4034,7 +4035,8 @@ void ImGui::NewFrame() // This fallback is particularly important as it avoid ImGui:: calls from crashing. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); - g.FrameScopePushedImplicitWindow = true; + IM_ASSERT(g.CurrentWindow->FallbackWindow == true); + g.FrameScopePushedFallbackWindow = true; #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiTestEngineHook_PostNewFrame(&g); @@ -4407,7 +4409,7 @@ void ImGui::EndFrame() } // Hide implicit/fallback "Debug" window if it hasn't been used - g.FrameScopePushedImplicitWindow = false; + g.FrameScopePushedFallbackWindow = false; if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed) g.CurrentWindow->Active = false; End(); @@ -5760,7 +5762,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Find or create ImGuiWindow* window = FindWindowByName(name); const bool window_just_created = (window == NULL); - const bool window_is_fallback = (g.CurrentWindowStack.Size == 0); if (window_just_created) { ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. @@ -5776,6 +5777,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const int current_frame = g.FrameCount; const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + window->FallbackWindow = (g.CurrentWindowStack.Size == 0); // Update the Appearing flag bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on @@ -5812,7 +5814,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (first_begin_of_the_frame) { bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL); - bool new_auto_dock_node = !has_dock_node && g.IO.ConfigDockingTabBarOnSingleWindows && !(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) && !window_is_fallback; + bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window); if (has_dock_node || new_auto_dock_node) { BeginDocked(window, p_open); @@ -6556,7 +6558,7 @@ void ImGui::End() { ImGuiContext& g = *GImGui; - if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow) + if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedFallbackWindow) { IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!"); return; // FIXME-ERRORHANDLING @@ -12026,7 +12028,11 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) DockNodeRemoveTabBar(node); // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) - if (node->Windows.Size <= 1 && node->IsFloatingNode() && node->IsLeafNode() && !g.IO.ConfigDockingTabBarOnSingleWindows) + bool want_to_hide_host_window = false; + if (node->Windows.Size <= 1 && node->IsFloatingNode() && node->IsLeafNode()) + if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar)) + want_to_hide_host_window = true; + if (want_to_hide_host_window) { if (node->Windows.Size == 1) { @@ -13749,12 +13755,22 @@ void ImGui::DockBuilderFinish(ImGuiID root_id) // Docking: Begin/End Functions (called from Begin/End) //----------------------------------------------------------------------------- +bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar) + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0) + if (!window->FallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise + return true; + return false; +} + void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) { ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; - const bool auto_dock_node = (g.IO.ConfigDockingTabBarOnSingleWindows) && !(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)); + const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window); if (auto_dock_node) { if (window->DockId == 0) diff --git a/imgui.h b/imgui.h index 6d488ff3..ca623aeb 100644 --- a/imgui.h +++ b/imgui.h @@ -1425,7 +1425,7 @@ struct ImGuiIO // Docking options (when ImGuiConfigFlags_DockingEnable is set) bool ConfigDockingNoSplit; // = false // Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. bool ConfigDockingWithShift; // = false // Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) - bool ConfigDockingTabBarOnSingleWindows; // = false // [BETA] Make every single floating window display within a docking node. + bool ConfigDockingAlwaysTabBar; // = false // [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. bool ConfigDockingTransparentPayload;// = false // [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) @@ -1612,9 +1612,10 @@ struct ImGuiWindowClass ImGuiID ParentViewportId; // Hint for the platform back-end. If non-zero, the platform back-end can create a parent<>child relationship between the platform windows. Not conforming back-ends are free to e.g. parent every viewport to the main viewport or not. ImGuiViewportFlags ViewportFlagsOverrideMask; // Viewport flags to override when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. ImGuiViewportFlags ViewportFlagsOverrideValue; // Viewport flags values to override when a window of this class owns a viewport. + bool DockingAlwaysTabBar; // Set to true to enforce windows of this class always having their own tab (equivalent of setting the global io.ConfigDockingAlwaysTabBar) bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. - ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideMask = ViewportFlagsOverrideValue = 0x00; DockingAllowUnclassed = true; } + ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideMask = ViewportFlagsOverrideValue = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dd25873b..bb09d02d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -368,7 +368,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SameLine(); HelpMarker("Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars."); ImGui::Checkbox("io.ConfigDockingWithShift", &io.ConfigDockingWithShift); ImGui::SameLine(); HelpMarker("Enable docking when holding Shift only (allows to drop in wider space, reduce visual noise)"); - ImGui::Checkbox("io.ConfigDockingTabBarOnSingleWindows", &io.ConfigDockingTabBarOnSingleWindows); + ImGui::Checkbox("io.ConfigDockingAlwaysTabBar", &io.ConfigDockingAlwaysTabBar); ImGui::SameLine(); HelpMarker("Create a docking node and tab-bar on single floating windows."); ImGui::Checkbox("io.ConfigDockingTransparentPayload", &io.ConfigDockingTransparentPayload); ImGui::SameLine(); HelpMarker("Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge."); @@ -3079,7 +3079,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.ConfigViewportsNoDefaultParent) ImGui::Text("io.ConfigViewportsNoDefaultParent"); if (io.ConfigDockingNoSplit) ImGui::Text("io.ConfigDockingNoSplit"); if (io.ConfigDockingWithShift) ImGui::Text("io.ConfigDockingWithShift"); - if (io.ConfigDockingTabBarOnSingleWindows) ImGui::Text("io.ConfigDockingTabBarOnSingleWindows"); + if (io.ConfigDockingAlwaysTabBar) ImGui::Text("io.ConfigDockingAlwaysTabBar"); if (io.ConfigDockingTransparentPayload) ImGui::Text("io.ConfigDockingTransparentPayload"); if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors"); if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); diff --git a/imgui_internal.h b/imgui_internal.h index bd1f9aad..3b3d23de 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -982,7 +982,7 @@ struct ImGuiContext { bool Initialized; bool FrameScopeActive; // Set by NewFrame(), cleared by EndFrame() - bool FrameScopePushedImplicitWindow; // Set by NewFrame(), cleared by EndFrame() + bool FrameScopePushedFallbackWindow; // Set by NewFrame(), cleared by EndFrame() bool FontAtlasOwnedByContext; // Io.Fonts-> is owned by the ImGuiContext and will be destructed along with it. ImGuiIO IO; ImGuiPlatformIO PlatformIO; @@ -1195,7 +1195,7 @@ struct ImGuiContext ImGuiContext(ImFontAtlas* shared_font_atlas) { Initialized = false; - FrameScopeActive = FrameScopePushedImplicitWindow = false; + FrameScopeActive = FrameScopePushedFallbackWindow = false; ConfigFlagsForFrame = ImGuiConfigFlags_None; Font = NULL; FontSize = FontBaseSize = 0.0f; @@ -1449,6 +1449,7 @@ struct IMGUI_API ImGuiWindow bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) bool Appearing; // Set during the frame where the window is appearing (or re-appearing) bool Hidden; // Do not display (== (HiddenFrames*** > 0)) + bool FallbackWindow; bool HasCloseButton; // Set when the window has a close button (p_open != NULL) signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) @@ -1758,6 +1759,7 @@ namespace ImGui IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos); inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } + IMGUI_API bool GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window); IMGUI_API void BeginDocked(ImGuiWindow* window, bool* p_open); IMGUI_API void BeginAsDockableDragDropSource(ImGuiWindow* window); IMGUI_API void BeginAsDockableDragDropTarget(ImGuiWindow* window); From 75136d3bea66ee8621e3548ccde055de7f4778a4 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 11:43:17 -0700 Subject: [PATCH 498/566] Internals: Removed ShowDockingDemo(), moved into Metrics. Metrics: Added more links to browse window->node, node->window, node->node etc. --- imgui.cpp | 314 ++++++++++++++++++++++++----------------------- imgui_internal.h | 1 - 2 files changed, 158 insertions(+), 157 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 97cb014c..7ff5295c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14172,11 +14172,11 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings // [DEBUG] Include comments in the .ini file to ease debugging if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID)) { - buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything + buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name); int contains_window = 0; - for (int window_n = 0; window_n < ctx->SettingsWindows.Size; window_n++) + for (int window_n = 0; window_n < ctx->SettingsWindows.Size; window_n++) // Iterate settings so we can give info about windows that didn't exist during the session. if (ctx->SettingsWindows[window_n].DockId == node_settings->ID) { if (contains_window++ == 0) @@ -14411,6 +14411,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) static bool show_windows_rects = false; static int show_windows_rect_type = WRT_WorkRect; static bool show_drawcmd_clip_rects = true; + static bool show_window_dock_info = false; ImGuiIO& io = ImGui::GetIO(); ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); @@ -14420,6 +14421,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Text("%d active allocations", io.MetricsActiveAllocations); ImGui::Separator(); + // Helper functions to display common structures: + // - NodeDrawList + // - NodeColumns + // - NodeWindow + // - NodeWindows + // - NodeViewport + // - NodeDockNode + // - NodeTabBar struct Funcs { static ImRect GetWindowRect(ImGuiWindow* window, int rect_type) @@ -14519,15 +14528,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } - static void NodeWindows(ImVector& windows, const char* label) - { - if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) - return; - for (int i = 0; i < windows.Size; i++) - Funcs::NodeWindow(windows[i], "Window"); - ImGui::TreePop(); - } - static void NodeWindow(ImGuiWindow* window, const char* label) { if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) @@ -14550,7 +14550,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::BulletText("NavRectRel[0]: "); ImGui::BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y); ImGui::BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1); - ImGui::BulletText("DockId: 0x%04X, DockOrder: %d, %s: 0x%p, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode", window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockIsActive, window->DockTabIsVisible); + ImGui::BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible); + if (window->DockNode || window->DockNodeAsHost) + NodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode"); if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); if (window->RootWindowDockStop != window->RootWindow) NodeWindow(window->RootWindowDockStop, "RootWindowDockStop"); if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow"); @@ -14565,6 +14567,15 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } + static void NodeWindows(ImVector& windows, const char* label) + { + if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) + return; + for (int i = 0; i < windows.Size; i++) + Funcs::NodeWindow(windows[i], "Window"); + ImGui::TreePop(); + } + static void NodeViewport(ImGuiViewportP* viewport) { ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -14584,6 +14595,75 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } } + + static void NodeDockNode(ImGuiDockNode* node, const char* label) + { + ImGuiContext& g = *GImGui; + bool open; + if (node->Windows.Size > 0) + open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); + else + open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); + if (open) + { + IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); + IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node); + ImGui::BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", + node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); + NodeWindow(node->VisibleWindow, "VisibleWindow"); + ImGui::BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabID, node->LastFocusedNodeID); + ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : ""); + if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) + { + ImGui::CheckboxFlags("LocalFlags: NoSplit", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); + ImGui::CheckboxFlags("LocalFlags: NoResize", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("LocalFlags: NoTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar); + ImGui::CheckboxFlags("LocalFlags: HiddenTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); + ImGui::CheckboxFlags("LocalFlags: NoWindowMenuButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton); + ImGui::CheckboxFlags("LocalFlags: NoCloseButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoCloseButton); + ImGui::TreePop(); + } + if (node->ParentNode) + NodeDockNode(node->ParentNode, "ParentNode"); + if (node->ChildNodes[0]) + NodeDockNode(node->ChildNodes[0], "Child[0]"); + if (node->ChildNodes[1]) + NodeDockNode(node->ChildNodes[1], "Child[1]"); + if (node->TabBar) + NodeTabBar(node->TabBar); + ImGui::TreePop(); + } + } + + static void NodeTabBar(ImGuiTabBar* tab_bar) + { + // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. + char buf[256]; + char* p = buf; + const char* buf_end = buf + IM_ARRAYSIZE(buf); + p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", + tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : ""); + if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) + { + p += ImFormatString(p, buf_end - p, " { "); + for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) + p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", tab_bar->Tabs[tab_n].Window->Name); + p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); + } + if (ImGui::TreeNode(tab_bar, "%s", buf)) + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + ImGui::PushID(tab); + if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); + if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine(); + ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, tab->Window ? tab->Window->Name : "N/A"); + ImGui::PopID(); + } + ImGui::TreePop(); + } + } }; // Access private state, we are going to display the draw lists from last frame @@ -14622,9 +14702,60 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } - if (ImGui::TreeNode("Docking & Tab Bars")) + if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size)) + { + for (int n = 0; n < g.TabBars.Data.Size; n++) + Funcs::NodeTabBar(g.TabBars.GetByIndex(n)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Docking")) { - ShowDockingDebug(); + ImGuiDockContext* dc = g.DockContext; + ImGui::Checkbox("Ctrl shows window dock info", &show_window_dock_info); + + if (ImGui::TreeNode("Dock nodes")) + { + if (ImGui::SmallButton("Clear settings")) { DockContextClearNodes(&g, 0, true); } + ImGui::SameLine(); + if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + if (node->IsRootNode()) + Funcs::NodeDockNode(node, "Node"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Settings")) + { + if (ImGui::SmallButton("Refresh")) + SaveIniSettingsToMemory(); + ImGui::SameLine(); + if (ImGui::SmallButton("Save to disk")) + SaveIniSettingsToDisk(g.IO.IniFilename); + ImGui::Separator(); + ImGui::Text("Docked Windows:"); + for (int n = 0; n < g.SettingsWindows.Size; n++) + if (g.SettingsWindows[n].DockId != 0) + ImGui::BulletText("Window '%s' -> DockId %08X", g.SettingsWindows[n].Name, g.SettingsWindows[n].DockId); + ImGui::Separator(); + ImGui::Text("Dock Nodes:"); + for (int n = 0; n < dc->SettingsNodes.Size; n++) + { + ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n]; + const char* selected_tab_name = NULL; + if (settings->SelectedTabID) + { + if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabID)) + selected_tab_name = window->Name; + else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabID)) + selected_tab_name = window_settings->Name; + } + ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentID, settings->SelectedTabID, selected_tab_name ? selected_tab_name : settings->SelectedTabID ? "N/A" : ""); + } + ImGui::TreePop(); + } + ImGui::TreePop(); } @@ -14699,148 +14830,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) } } } - ImGui::End(); -} - -#else - -void ImGui::ShowMetricsWindow(bool*) { } - -#endif - -void ImGui::ShowDockingDebug() -{ - ImGuiContext* ctx = GImGui; - ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; - - struct Funcs - { - static void NodeDockNode(ImGuiDockNode* node, const char* label) - { - ImGuiContext& g = *GImGui; - ImGui::SetNextItemOpen(true, ImGuiCond_Once); - bool open; - if (node->Windows.Size > 0) - open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); - else - open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); - if (open) - { - IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); - IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node); - ImGui::BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", - node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); - ImGui::BulletText("VisibleWindow: 0x%08X %s", node->VisibleWindow ? node->VisibleWindow->ID : 0, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); - ImGui::BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabID, node->LastFocusedNodeID); - ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : ""); - if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) - { - ImGui::CheckboxFlags("LocalFlags: NoSplit", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); - ImGui::CheckboxFlags("LocalFlags: NoResize", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); - ImGui::CheckboxFlags("LocalFlags: NoTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar); - ImGui::CheckboxFlags("LocalFlags: HiddenTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); - ImGui::CheckboxFlags("LocalFlags: NoWindowMenuButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton); - ImGui::CheckboxFlags("LocalFlags: NoCloseButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoCloseButton); - ImGui::TreePop(); - } - if (node->ChildNodes[0]) - NodeDockNode(node->ChildNodes[0], "Child[0]"); - if (node->ChildNodes[1]) - NodeDockNode(node->ChildNodes[1], "Child[1]"); - if (node->TabBar) - NodeTabBar(node->TabBar); - ImGui::TreePop(); - } - } - - static void NodeTabBar(ImGuiTabBar* tab_bar) - { - // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. - char buf[256]; - char* p = buf; - const char* buf_end = buf + IM_ARRAYSIZE(buf); - p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", - tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : ""); - if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) - { - p += ImFormatString(p, buf_end - p, " { "); - for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) - p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", tab_bar->Tabs[tab_n].Window->Name); - p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); - } - if (ImGui::TreeNode(tab_bar, "%s", buf)) - { - for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) - { - const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - ImGui::PushID(tab); - if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); - if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine(); - ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, tab->Window ? tab->Window->Name : "N/A"); - ImGui::PopID(); - } - ImGui::TreePop(); - } - } - }; - - static bool show_window_dock_info = false; - ImGui::Checkbox("Ctrl shows window dock info", &show_window_dock_info); - - if (ImGui::TreeNode("Dock nodes")) - { - if (ImGui::SmallButton("Clear settings")) { DockContextClearNodes(&g, 0, true); } - ImGui::SameLine(); - if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } - for (int n = 0; n < dc->Nodes.Data.Size; n++) - if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) - if (node->IsRootNode()) - Funcs::NodeDockNode(node, "Node"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size)) - { - for (int n = 0; n < g.TabBars.Data.Size; n++) - Funcs::NodeTabBar(g.TabBars.GetByIndex(n)); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Settings")) - { - if (ImGui::SmallButton("Refresh")) - SaveIniSettingsToMemory(); - ImGui::SameLine(); - if (ImGui::SmallButton("Save to disk")) - SaveIniSettingsToDisk(g.IO.IniFilename); - ImGui::Separator(); - ImGui::Text("Docked Windows:"); - for (int n = 0; n < g.SettingsWindows.Size; n++) - if (g.SettingsWindows[n].DockId != 0) - ImGui::BulletText("Window '%s' -> DockId %08X", g.SettingsWindows[n].Name, g.SettingsWindows[n].DockId); - ImGui::Separator(); - ImGui::Text("Dock Nodes:"); - for (int n = 0; n < dc->SettingsNodes.Size; n++) - { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n]; - const char* selected_tab_name = NULL; - if (settings->SelectedTabID) - { - if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabID)) - selected_tab_name = window->Name; - else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabID)) - selected_tab_name = window_settings->Name; - } - ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentID, settings->SelectedTabID, selected_tab_name ? selected_tab_name : settings->SelectedTabID ? "N/A" : ""); - } - ImGui::TreePop(); - } - if (g.IO.KeyCtrl && show_window_dock_info) + if (show_window_dock_info && g.IO.KeyCtrl) { - for (int n = 0; n < dc->Nodes.Data.Size; n++) - if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + for (int n = 0; n < g.DockContext->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)g.DockContext->Nodes.Data[n].val_p) { ImGuiDockNode* root_node = DockNodeGetRootNode(node); if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos)) @@ -14853,14 +14847,22 @@ void ImGui::ShowDockingDebug() p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); int depth = DockNodeGetDepth(node); - overlay_draw_list->AddRect(node->Pos + ImVec2(3,3) * (float)depth, node->Pos + node->Size - ImVec2(3,3) * (float)depth, IM_COL32(200, 100, 100, 255)); - ImVec2 pos = node->Pos + ImVec2(3,3) * (float)depth; + overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255)); + ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth; overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255)); overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf); } } + + ImGui::End(); } +#else + +void ImGui::ShowMetricsWindow(bool*) { } + +#endif + //----------------------------------------------------------------------------- // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. diff --git a/imgui_internal.h b/imgui_internal.h index 3b3d23de..621bdd11 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1764,7 +1764,6 @@ namespace ImGui IMGUI_API void BeginAsDockableDragDropSource(ImGuiWindow* window); IMGUI_API void BeginAsDockableDragDropTarget(ImGuiWindow* window); IMGUI_API void SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond); - IMGUI_API void ShowDockingDebug(); // Docking - Builder function needs to be generally called before the DockSpace() node is submitted. IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id); From 835b50b7737f7f626a0983c6980f4397575b06b4 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 17:27:41 -0700 Subject: [PATCH 499/566] Internals: Nav: Tweak NavUpdatePageUpPageDown() to make it more readable. --- imgui.cpp | 63 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 30 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fdc12c78..f381e1f3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5756,6 +5756,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (render_decorations_in_parent) window->DrawList = parent_window->DrawList; + // Handle title bar, scrollbar, resize grips and resize borders const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size); @@ -8451,42 +8452,44 @@ static void ImGui::NavUpdateMoveResult() static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) { ImGuiContext& g = *GImGui; - if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0) + if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL) + return 0.0f; + if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != 0) + return 0.0f; + + ImGuiWindow* window = g.NavWindow; + bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up)); + bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down)); + if (page_up_held != page_down_held) // If either (not both) are pressed { - ImGuiWindow* window = g.NavWindow; - bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up)); - bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down)); - if (page_up_held != page_down_held) // If either (not both) are pressed + if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll) + { + // Fallback manual-scroll when window has no navigable item + if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) + SetWindowScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); + else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) + SetWindowScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); + } + else { - if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll) + const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; + const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); + float nav_scoring_rect_offset_y = 0.0f; + if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) { - // Fallback manual-scroll when window has no navigable item - if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) - SetWindowScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); - else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) - SetWindowScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); + nav_scoring_rect_offset_y = -page_offset_y; + g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Up; + g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } - else + else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) { - const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; - const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); - float nav_scoring_rect_offset_y = 0.0f; - if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) - { - nav_scoring_rect_offset_y = -page_offset_y; - g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) - g.NavMoveClipDir = ImGuiDir_Up; - g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; - } - else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) - { - nav_scoring_rect_offset_y = +page_offset_y; - g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) - g.NavMoveClipDir = ImGuiDir_Down; - g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; - } - return nav_scoring_rect_offset_y; + nav_scoring_rect_offset_y = +page_offset_y; + g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) + g.NavMoveClipDir = ImGuiDir_Down; + g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } + return nav_scoring_rect_offset_y; } } return 0.0f; From 34cf00566f57b48870192d650cb06e4b6cc88738 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 18:11:06 -0700 Subject: [PATCH 500/566] InputTextMultiline: Fixed vertical scrolling tracking glitch. Fixed Travis-CI banner address. --- docs/CHANGELOG.txt | 5 +++-- docs/README.md | 2 +- imgui_widgets.cpp | 3 +-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3869166f..c20ae7c5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,10 +62,11 @@ Other Changes: worth of asymmetrical/extraneous padding, note that there's another half that conservatively has to offset the right-most column, otherwise it's clipping width won't match the other column). (#125, #2666) - Columns: Improved honoring alignment with various values of ItemSpacing.x and WindowPadding.x. (#125, #2666) -- Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because - of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Columns: Made GetColumnOffset() and GetColumnWidth() behave when there's no column set, consistently with other column functions. (#2683) +- InputTextMultiline: Fixed vertical scrolling tracking glitch. +- Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because + of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button diff --git a/docs/README.md b/docs/README.md index 902b615a..d020ea07 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ dear imgui ===== -[![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui) +[![Build Status](https://api.travis-ci.com/ocornut/imgui.svg?branch=master)](https://travis-ci.com/ocornut/imgui) [![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720) _(This library is free as in freedom, but needs your support to sustain its development. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using dear imgui, please consider reaching out for invoiced financial support. If you are an individual using dear imgui, please consider donating via Patreon or PayPal.)_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 13875ea2..4c65ed9c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3993,9 +3993,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - size.y >= scroll_y) scroll_y = cursor_offset.y - size.y; - draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag + draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; - draw_pos.y = draw_window->DC.CursorPos.y; } state->CursorFollow = false; From dcd03f62a7c1d246cd0638c8657574f1fe0486fa Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 18:24:23 -0700 Subject: [PATCH 501/566] Scrolling: Made it possible for mouse wheel and navigation-triggered scrolling to override a call to SetScrollX()/SetScrollY(), making it possible to use a simpler stateless pattern for auto-scrolling. Demo: Log, Console: Using a simpler stateless pattern for auto-scrolling. --- docs/CHANGELOG.txt | 6 ++++++ imgui.cpp | 38 ++++++++++++++++++++------------------ imgui_demo.cpp | 30 ++++++++++-------------------- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 4 ++-- 5 files changed, 40 insertions(+), 42 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c20ae7c5..da56984a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,11 @@ Other Changes: - InputTextMultiline: Fixed vertical scrolling tracking glitch. - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). +- Scrolling: Made it possible for mouse wheel and navigation-triggered scrolling to override a call to + SetScrollX()/SetScrollY(), making it possible to use a simpler stateless pattern for auto-scrolling: + // (Submit items..) + if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) // Keep scrolling at the bottom if already + ImGui::SetScrollHereY(1.0f); - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button @@ -86,6 +91,7 @@ Other Changes: - ImDrawListSplitter: Fixed memory leak when using low-level split api (was not affecting ImDrawList api, also this type was added in 1.71 and not advertised as a public-facing feature). - Fonts: binary_to_compressed_c.cpp: Display an error message if failing to open/read the input font file. +- Demo: Log, Console: Using a simpler stateless pattern for auto-scrolling. - Backends: DX10/DX11: Backup, clear and restore Geometry Shader is any is bound when calling renderer. - Backends: DX11: Clear Hull Shader, Domain Shader, Compute Shader before rendering. Not backing/restoring them. - Backends: OSX: Disabled default native Mac clipboard copy/paste implementation in core library (added in 1.71), diff --git a/imgui.cpp b/imgui.cpp index f381e1f3..b473f7fa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3506,7 +3506,7 @@ void ImGui::UpdateMouseWheel() { float max_step = window->InnerRect.GetHeight() * 0.67f; float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step)); - SetWindowScrollY(window, window->Scroll.y - wheel_y * scroll_step); + SetScrollY(window, window->Scroll.y - wheel_y * scroll_step); } } @@ -3521,7 +3521,7 @@ void ImGui::UpdateMouseWheel() { float max_step = window->InnerRect.GetWidth() * 0.67f; float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step)); - SetWindowScrollX(window, window->Scroll.x - wheel_x * scroll_step); + SetScrollX(window, window->Scroll.x - wheel_x * scroll_step); } } } @@ -6524,16 +6524,6 @@ ImVec2 ImGui::GetWindowPos() return window->Pos; } -void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x) -{ - window->Scroll.x = new_scroll_x; -} - -void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) -{ - window->Scroll.y = new_scroll_y; -} - void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time @@ -6921,6 +6911,18 @@ void ImGui::SetScrollY(float scroll_y) window->ScrollTargetCenterRatio.y = 0.0f; } +void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x) +{ + window->ScrollTarget.x = new_scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) +{ + window->ScrollTarget.y = new_scroll_y; + window->ScrollTargetCenterRatio.y = 0.0f; +} + void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size @@ -8333,9 +8335,9 @@ static void ImGui::NavUpdate() if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest) { if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) - SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); + SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) - SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); + SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); } // *Normal* Manual scroll with NavScrollXXX keys @@ -8343,12 +8345,12 @@ static void ImGui::NavUpdate() ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); if (scroll_dir.x != 0.0f && window->ScrollbarX) { - SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); + SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); g.NavMoveFromClampedRefRect = true; } if (scroll_dir.y != 0.0f) { - SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); + SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); g.NavMoveFromClampedRefRect = true; } } @@ -8466,9 +8468,9 @@ static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) - SetWindowScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); + SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) - SetWindowScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); + SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); } else { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 53e2bf1c..257524d5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3449,7 +3449,7 @@ struct ExampleAppConsole Commands.push_back("CLEAR"); Commands.push_back("CLASSIFY"); // "classify" is only here to provide an example of "C"+[tab] completing to "CL" and displaying matches. AutoScroll = true; - ScrollToBottom = true; + ScrollToBottom = false; AddLog("Welcome to Dear ImGui!"); } ~ExampleAppConsole() @@ -3470,7 +3470,6 @@ struct ExampleAppConsole for (int i = 0; i < Items.Size; i++) free(Items[i]); Items.clear(); - ScrollToBottom = true; } void AddLog(const char* fmt, ...) IM_FMTARGS(2) @@ -3483,8 +3482,6 @@ struct ExampleAppConsole buf[IM_ARRAYSIZE(buf)-1] = 0; va_end(args); Items.push_back(Strdup(buf)); - if (AutoScroll) - ScrollToBottom = true; } void Draw(const char* title, bool* p_open) @@ -3513,8 +3510,7 @@ struct ExampleAppConsole if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); if (ImGui::SmallButton("Add Dummy Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); - bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::SameLine(); - if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true; + bool copy_to_clipboard = ImGui::SmallButton("Copy"); //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } ImGui::Separator(); @@ -3522,9 +3518,7 @@ struct ExampleAppConsole // Options menu if (ImGui::BeginPopup("Options")) { - if (ImGui::Checkbox("Auto-scroll", &AutoScroll)) - if (AutoScroll) - ScrollToBottom = true; + ImGui::Checkbox("Auto-scroll", &AutoScroll); ImGui::EndPopup(); } @@ -3573,9 +3567,11 @@ struct ExampleAppConsole } if (copy_to_clipboard) ImGui::LogFinish(); - if (ScrollToBottom) + + if (ScrollToBottom || (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())) ImGui::SetScrollHereY(1.0f); ScrollToBottom = false; + ImGui::PopStyleVar(); ImGui::EndChild(); ImGui::Separator(); @@ -3767,13 +3763,11 @@ struct ExampleAppLog ImGuiTextBuffer Buf; ImGuiTextFilter Filter; ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines - bool AutoScroll; - bool ScrollToBottom; + bool AutoScroll; // Keep scrolling if already at the bottom ExampleAppLog() { AutoScroll = true; - ScrollToBottom = false; Clear(); } @@ -3794,8 +3788,6 @@ struct ExampleAppLog for (int new_size = Buf.size(); old_size < new_size; old_size++) if (Buf[old_size] == '\n') LineOffsets.push_back(old_size + 1); - if (AutoScroll) - ScrollToBottom = true; } void Draw(const char* title, bool* p_open = NULL) @@ -3809,9 +3801,7 @@ struct ExampleAppLog // Options menu if (ImGui::BeginPopup("Options")) { - if (ImGui::Checkbox("Auto-scroll", &AutoScroll)) - if (AutoScroll) - ScrollToBottom = true; + ImGui::Checkbox("Auto-scroll", &AutoScroll); ImGui::EndPopup(); } @@ -3876,9 +3866,9 @@ struct ExampleAppLog } ImGui::PopStyleVar(); - if (ScrollToBottom) + if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) ImGui::SetScrollHereY(1.0f); - ScrollToBottom = false; + ImGui::EndChild(); ImGui::End(); } diff --git a/imgui_internal.h b/imgui_internal.h index 366c682c..d557f99c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1460,8 +1460,8 @@ namespace ImGui IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window); IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent); IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); - IMGUI_API void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x); - IMGUI_API void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); + IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x); + IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y); IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4c65ed9c..b883ea02 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3637,8 +3637,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Delete) && !is_readonly) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } From 26f14e056c01649af1f64f73e08c65900a932ad0 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 22 Jul 2019 18:48:39 -0700 Subject: [PATCH 502/566] Scrolling: Made mouse-wheel scrolling lock the underlying window until the mouse is moved again or until a short delay expires (2 seconds). This allow uninterrupted scroll even if child windows are passing under the mouse cursor. (#2604) --- docs/CHANGELOG.txt | 5 ++++- imgui.cpp | 38 ++++++++++++++++++++++++++++++++------ imgui_internal.h | 5 +++++ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index da56984a..f5b3bdb0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,7 +53,6 @@ Other Changes: any more. Forwarding can still be disabled by setting ImGuiWindowFlags_NoInputs. (amend #1502, #1380). - Window: Fixed old SetWindowFontScale() api value from not being inherited by child window. Added comments about the right way to scale your UI (load a font at the right side, rebuild atlas, scale style). -- Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Combo: Hide arrow when there's not enough space even for the square button. - TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). - Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column @@ -67,12 +66,16 @@ Other Changes: - InputTextMultiline: Fixed vertical scrolling tracking glitch. - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). +- Scrolling: Made mouse-wheel scrolling lock the underlying window until the mouse is moved again or + until a short delay expires (2 seconds). This allow uninterrupted scroll even if child windows are + passing under the mouse cursor. (#2604) - Scrolling: Made it possible for mouse wheel and navigation-triggered scrolling to override a call to SetScrollX()/SetScrollY(), making it possible to use a simpler stateless pattern for auto-scrolling: // (Submit items..) if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) // Keep scrolling at the bottom if already ImGui::SetScrollHereY(1.0f); - Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] +- Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. diff --git a/imgui.cpp b/imgui.cpp index b473f7fa..9dc43e0c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1042,6 +1042,7 @@ static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end) static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow(). static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. +static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certaint time, unless mouse moved. //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS @@ -3465,19 +3466,45 @@ static void ImGui::UpdateMouseInputs() } } -void ImGui::UpdateMouseWheel() +static void StartLockWheelingWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; - if (!g.HoveredWindow || g.HoveredWindow->Collapsed) + if (g.WheelingWindow == window) return; + g.WheelingWindow = window; + g.WheelingWindowRefMousePos = g.IO.MousePos; + g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER; +} + +void ImGui::UpdateMouseWheel() +{ + ImGuiContext& g = *GImGui; + + // Reset the locked window if we move the mouse or after the timer elapses + if (g.WheelingWindow != NULL) + { + g.WheelingWindowTimer -= g.IO.DeltaTime; + if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold) + g.WheelingWindowTimer = 0.0f; + if (g.WheelingWindowTimer <= 0.0f) + { + g.WheelingWindow = NULL; + g.WheelingWindowTimer = 0.0f; + } + } + if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f) return; + ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow; + if (!window || window->Collapsed) + return; + // Zoom / Scale window // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) { - ImGuiWindow* window = g.HoveredWindow; + StartLockWheelingWindow(window); const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); const float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; @@ -3493,13 +3520,12 @@ void ImGui::UpdateMouseWheel() // Mouse wheel scrolling // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent - // FIXME: Lock scrolling window while not moving (see #2604) // Vertical Mouse Wheel scrolling const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; if (wheel_y != 0.0f && !g.IO.KeyCtrl) { - ImGuiWindow* window = g.HoveredWindow; + StartLockWheelingWindow(window); while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) window = window->ParentWindow; if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) @@ -3514,7 +3540,7 @@ void ImGui::UpdateMouseWheel() const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; if (wheel_x != 0.0f && !g.IO.KeyCtrl) { - ImGuiWindow* window = g.HoveredWindow; + StartLockWheelingWindow(window); while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) window = window->ParentWindow; if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) diff --git a/imgui_internal.h b/imgui_internal.h index d557f99c..088fbca9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -868,6 +868,9 @@ struct ImGuiContext ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. + ImGuiWindow* WheelingWindow; + ImVec2 WheelingWindowRefMousePos; + float WheelingWindowTimer; // Item/widgets state and tracking information ImGuiID HoveredId; // Hovered widget @@ -1058,6 +1061,8 @@ struct ImGuiContext HoveredWindow = NULL; HoveredRootWindow = NULL; MovingWindow = NULL; + WheelingWindow = NULL; + WheelingWindowTimer = 0.0f; HoveredId = 0; HoveredIdAllowOverlap = false; From 1820aaf44419e7474e46aaa9657b36cf915edb23 Mon Sep 17 00:00:00 2001 From: luk1337 Date: Tue, 23 Jul 2019 18:41:27 +0200 Subject: [PATCH 503/566] imgui_freetype: Initialize FT_MemoryRec_ struct manually (#2686) This fixes gcc warning: missing field 'alloc' initializer [-Wmissing-field-initializers] --- misc/freetype/imgui_freetype.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index d0d2580d..d3f2bf54 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -646,7 +646,8 @@ static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size bool ImGuiFreeType::BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags) { // FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html - FT_MemoryRec_ memory_rec = { 0 }; + FT_MemoryRec_ memory_rec = {}; + memory_rec.user = NULL; memory_rec.alloc = &FreeType_Alloc; memory_rec.free = &FreeType_Free; memory_rec.realloc = &FreeType_Realloc; From 51853292cc0c4d7a01b056266e5dedc066490b61 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jul 2019 09:49:17 -0700 Subject: [PATCH 504/566] ImDrawList: Using ImDrawCornerFlags instead of int in various apis. Demo: Using ImGuiColorEditrFlags instead of int. --- imgui.h | 9 +++++---- imgui_demo.cpp | 2 +- imgui_draw.cpp | 14 +++++++------- imgui_widgets.cpp | 1 + 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index cdfa426d..e14f564e 100644 --- a/imgui.h +++ b/imgui.h @@ -1837,6 +1837,7 @@ struct ImDrawListSplitter enum ImDrawCornerFlags_ { + ImDrawCornerFlags_None = 0, ImDrawCornerFlags_TopLeft = 1 << 0, // 0x1 ImDrawCornerFlags_TopRight = 1 << 1, // 0x2 ImDrawCornerFlags_BotLeft = 1 << 2, // 0x4 @@ -1897,8 +1898,8 @@ struct ImDrawList // Primitives IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4-bits corresponding to which corner to round - IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right (== upper-left + size) + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4-bits corresponding to which corner to round + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); @@ -1910,7 +1911,7 @@ struct ImDrawList IMGUI_API void AddText(const 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 AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = IM_COL32_WHITE); IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All); + IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, bool closed, float thickness); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order. IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); @@ -1924,7 +1925,7 @@ struct ImDrawList IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); - IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); // Advanced IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 257524d5..b7b48a52 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1112,7 +1112,7 @@ static void ShowDemoWindowWidgets() ImGui::Checkbox("With Drag and Drop", &drag_and_drop); ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options."); ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets."); - int misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions); + ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions); ImGui::Text("Color widget:"); ImGui::SameLine(); HelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e7c5e82e..45cf9ecb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -943,7 +943,7 @@ void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImV } } -void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) +void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawCornerFlags rounding_corners) { rounding = ImMin(rounding, ImFabs(b.x - a.x) * ( ((rounding_corners & ImDrawCornerFlags_Top) == ImDrawCornerFlags_Top) || ((rounding_corners & ImDrawCornerFlags_Bot) == ImDrawCornerFlags_Bot) ? 0.5f : 1.0f ) - 1.0f); rounding = ImMin(rounding, ImFabs(b.y - a.y) * ( ((rounding_corners & ImDrawCornerFlags_Left) == ImDrawCornerFlags_Left) || ((rounding_corners & ImDrawCornerFlags_Right) == ImDrawCornerFlags_Right) ? 0.5f : 1.0f ) - 1.0f); @@ -978,24 +978,24 @@ void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thic } // a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. -void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags, float thickness) +void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; if (Flags & ImDrawListFlags_AntiAliasedLines) - PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.50f,0.50f), rounding, rounding_corners_flags); + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.50f,0.50f), rounding, rounding_corners); else - PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.49f,0.49f), rounding, rounding_corners_flags); // Better looking lower-right corner and rounded non-AA shapes. + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.49f,0.49f), rounding, rounding_corners); // Better looking lower-right corner and rounded non-AA shapes. PathStroke(col, true, thickness); } -void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags) +void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners) { if ((col & IM_COL32_A_MASK) == 0) return; if (rounding > 0.0f) { - PathRect(a, b, rounding, rounding_corners_flags); + PathRect(a, b, rounding, rounding_corners); PathFillConvex(col); } else @@ -1164,7 +1164,7 @@ void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, cons PopTextureID(); } -void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners) +void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners) { if ((col & IM_COL32_A_MASK) == 0) return; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b883ea02..9915a24c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1088,6 +1088,7 @@ bool ImGui::RadioButton(const char* label, bool active) return pressed; } +// FIXME: This would work nicely if it was a public template, e.g. 'template RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it.. bool ImGui::RadioButton(const char* label, int* v, int v_button) { const bool pressed = RadioButton(label, *v == v_button); From baae057a035014bbc0500e10616796e420d8b766 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jul 2019 11:50:41 -0700 Subject: [PATCH 505/566] Internals: Merge in minor noise from wip Tables branch to simplify further merging. --- imgui.cpp | 40 ++++++++++++++++++++++++++++++++++------ imgui_internal.h | 19 ++++++++++--------- imgui_widgets.cpp | 14 ++++++++------ 3 files changed, 52 insertions(+), 21 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9dc43e0c..4ecb2897 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3934,6 +3934,11 @@ void ImGui::Shutdown(ImGuiContext* context) g.DrawDataBuilder.ClearFreeMemory(); g.BackgroundDrawList.ClearFreeMemory(); g.ForegroundDrawList.ClearFreeMemory(); + + g.TabBars.Clear(); + g.CurrentTabBarStack.clear(); + g.ShrinkWidthBuffer.clear(); + g.PrivateClipboard.clear(); g.InputTextState.ClearFreeMemory(); @@ -6744,7 +6749,8 @@ void ImGui::SetNextWindowBgAlpha(float alpha) // FIXME: This is in window space (not screen space!). We should try to obsolete all those functions. ImVec2 ImGui::GetContentRegionMax() { - ImGuiWindow* window = GImGui->CurrentWindow; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max - window->Pos; if (window->DC.CurrentColumns) mx.x = window->WorkRect.Max.x - window->Pos.x; @@ -6754,7 +6760,8 @@ ImVec2 ImGui::GetContentRegionMax() // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. ImVec2 ImGui::GetContentRegionMaxAbs() { - ImGuiWindow* window = GImGui->CurrentWindow; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.CurrentColumns) mx.x = window->WorkRect.Max.x; @@ -9650,14 +9657,16 @@ void ImGui::ShowMetricsWindow(bool* p_open) return; } + // State enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Contents, WRT_ContentsRegionRect, WRT_Count }; // Windows Rect Type const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Contents", "ContentsRegionRect" }; - - static bool show_windows_begin_order = false; static bool show_windows_rects = false; static int show_windows_rect_type = WRT_WorkRect; + static bool show_windows_begin_order = false; static bool show_drawcmd_clip_rects = true; + // Basic info + ImGuiContext& g = *GImGui; ImGuiIO& io = ImGui::GetIO(); ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); @@ -9666,6 +9675,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Text("%d active allocations", io.MetricsActiveAllocations); ImGui::Separator(); + // Helper functions to display common structures: + // - NodeDrawList + // - NodeColumns + // - NodeWindow + // - NodeWindows + // - NodeTabBar struct Funcs { static ImRect GetWindowRect(ImGuiWindow* window, int rect_type) @@ -9830,8 +9845,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) } }; - // Access private state, we are going to display the draw lists from last frame - ImGuiContext& g = *GImGui; Funcs::NodeWindows(g.Windows, "Windows"); if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) { @@ -9857,6 +9870,20 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } +#if 0 + if (ImGui::TreeNode("Docking")) + { + ImGui::TreePop(); + } +#endif + +#if 0 + if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.Data.Size)) + { + ImGui::TreePop(); + } +#endif + if (ImGui::TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); @@ -9903,6 +9930,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } + // Tool: Display windows Rectangles and Begin Order if (show_windows_rects || show_windows_begin_order) { for (int n = 0; n < g.Windows.Size; n++) diff --git a/imgui_internal.h b/imgui_internal.h index 088fbca9..d7c37c5f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -358,7 +358,8 @@ enum ImGuiSelectableFlagsPrivate_ ImGuiSelectableFlags_PressedOnClick = 1 << 21, ImGuiSelectableFlags_PressedOnRelease = 1 << 22, ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 23, // FIXME: We may be able to remove this (added in 6251d379 for menus) - ImGuiSelectableFlags_AllowItemOverlap = 1 << 24 + ImGuiSelectableFlags_AllowItemOverlap = 1 << 24, + ImGuiSelectableFlags_DrawHoveredWhenHeld= 1 << 25 // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. }; // Extend ImGuiTreeNodeFlags_ @@ -827,13 +828,13 @@ struct ImGuiShrinkWidthItem float Width; }; -struct ImGuiTabBarRef +struct ImGuiPtrOrIndex { - ImGuiTabBar* Ptr; // Either field can be set, not both. Dock node tab bars are loose while BeginTabBar() ones are in a pool. - int IndexInMainPool; + void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool. + int Index; // Usually index in a main pool. - ImGuiTabBarRef(ImGuiTabBar* ptr) { Ptr = ptr; IndexInMainPool = -1; } - ImGuiTabBarRef(int index_in_main_pool) { Ptr = NULL; IndexInMainPool = index_in_main_pool; } + ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } + ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } }; //----------------------------------------------------------------------------- @@ -986,9 +987,9 @@ struct ImGuiContext unsigned char DragDropPayloadBufLocal[8]; // Local buffer for small payloads // Tab bars - ImPool TabBars; ImGuiTabBar* CurrentTabBar; - ImVector CurrentTabBarStack; + ImPool TabBars; + ImVector CurrentTabBarStack; ImVector ShrinkWidthBuffer; // Widget state @@ -1425,7 +1426,7 @@ struct ImGuiTabBar float ScrollingSpeed; ImGuiTabBarFlags Flags; ImGuiID ReorderRequestTabId; - int ReorderRequestDir; + ImS8 ReorderRequestDir; bool WantLayout; bool VisibleTabWasSubmitted; short LastTabItemIdx; // For BeginTabItem()/EndTabItem() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9915a24c..3c48d247 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5490,6 +5490,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection; // Render + if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld)) + hovered = true; if (hovered || selected) { const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); @@ -6271,18 +6273,18 @@ static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const voi return (int)(a->Offset - b->Offset); } -static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiTabBarRef& ref) +static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref) { ImGuiContext& g = *GImGui; - return ref.Ptr ? ref.Ptr : g.TabBars.GetByIndex(ref.IndexInMainPool); + return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index); } -static ImGuiTabBarRef GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) +static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; if (g.TabBars.Contains(tab_bar)) - return ImGuiTabBarRef(g.TabBars.GetIndex(tab_bar)); - return ImGuiTabBarRef(tab_bar); + return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar)); + return ImGuiPtrOrIndex(tab_bar); } bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) @@ -6637,7 +6639,7 @@ void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* IM_ASSERT(dir == -1 || dir == +1); IM_ASSERT(tab_bar->ReorderRequestTabId == 0); tab_bar->ReorderRequestTabId = tab->ID; - tab_bar->ReorderRequestDir = dir; + tab_bar->ReorderRequestDir = (ImS8)dir; } static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) From 81b24bd728a25753fc31c8a0cfe9e94bd50508f8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jul 2019 13:37:52 -0700 Subject: [PATCH 506/566] Docking: Moving types in imgui.h --- imgui.h | 60 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/imgui.h b/imgui.h index ea15b765..bc155d5d 100644 --- a/imgui.h +++ b/imgui.h @@ -17,7 +17,7 @@ Index of this file: // ImVector<> // ImGuiStyle // ImGuiIO -// Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload, ImGuiWindowClass) +// Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiWindowClass, ImGuiPayload) // Obsolete functions // Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) // Draw List API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) @@ -887,21 +887,6 @@ enum ImGuiTabItemFlags_ ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() }; -// Flags for ImGui::DockSpace(), shared/inherited by child nodes. -// (Some flags can be applied to individual nodes directly) -// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. -enum ImGuiDockNodeFlags_ -{ - ImGuiDockNodeFlags_None = 0, - ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Shared // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. - //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Shared // Disable Central Node (the node which can stay empty) - ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Shared // Disable docking inside the Central Node, which will be always kept empty. - ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // Shared // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. - ImGuiDockNodeFlags_NoSplit = 1 << 4, // Shared/Local // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. - ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing node using the splitter/separators. Useful with programatically setup dockspaces. - ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Shared/Local // Tab bar will automatically hide when there is a single window in the dock node. -}; - // Flags for ImGui::IsWindowFocused() enum ImGuiFocusedFlags_ { @@ -930,6 +915,21 @@ enum ImGuiHoveredFlags_ ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows }; +// Flags for ImGui::DockSpace(), shared/inherited by child nodes. +// (Some flags can be applied to individual nodes directly) +// FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. +enum ImGuiDockNodeFlags_ +{ + ImGuiDockNodeFlags_None = 0, + ImGuiDockNodeFlags_KeepAliveOnly = 1 << 0, // Shared // Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + //ImGuiDockNodeFlags_NoCentralNode = 1 << 1, // Shared // Disable Central Node (the node which can stay empty) + ImGuiDockNodeFlags_NoDockingInCentralNode = 1 << 2, // Shared // Disable docking inside the Central Node, which will be always kept empty. + ImGuiDockNodeFlags_PassthruCentralNode = 1 << 3, // Shared // Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol_WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0f) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + ImGuiDockNodeFlags_NoSplit = 1 << 4, // Shared/Local // Disable splitting the node into smaller nodes. Useful e.g. when embedding dockspaces into a main root one (the root one may have splitting disabled to reduce confusion). Note: when turned off, existing splits will be preserved. + ImGuiDockNodeFlags_NoResize = 1 << 5, // Shared/Local // Disable resizing node using the splitter/separators. Useful with programatically setup dockspaces. + ImGuiDockNodeFlags_AutoHideTabBar = 1 << 6 // Shared/Local // Tab bar will automatically hide when there is a single window in the dock node. +}; + // Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() enum ImGuiDragDropFlags_ { @@ -1582,6 +1582,20 @@ struct ImGuiSizeCallbackData ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. }; +// [BETA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. +// Provide hints to the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) and OS level parent/child relationships. +struct ImGuiWindowClass +{ + ImGuiID ClassId; // User data. 0 = Default class (unclassed) + ImGuiID ParentViewportId; // Hint for the platform back-end. If non-zero, the platform back-end can create a parent<>child relationship between the platform windows. Not conforming back-ends are free to e.g. parent every viewport to the main viewport or not. + ImGuiViewportFlags ViewportFlagsOverrideMask; // Viewport flags to override when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiViewportFlags ViewportFlagsOverrideValue; // Viewport flags values to override when a window of this class owns a viewport. + bool DockingAlwaysTabBar; // Set to true to enforce windows of this class always having their own tab (equivalent of setting the global io.ConfigDockingAlwaysTabBar) + bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. + + ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideMask = ViewportFlagsOverrideValue = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; } +}; + // Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() struct ImGuiPayload { @@ -1604,20 +1618,6 @@ struct ImGuiPayload bool IsDelivery() const { return Delivery; } }; -// [BETA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. -// Provide hints to the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) and OS level parent/child relationships. -struct ImGuiWindowClass -{ - ImGuiID ClassId; // User data. 0 = Default class (unclassed) - ImGuiID ParentViewportId; // Hint for the platform back-end. If non-zero, the platform back-end can create a parent<>child relationship between the platform windows. Not conforming back-ends are free to e.g. parent every viewport to the main viewport or not. - ImGuiViewportFlags ViewportFlagsOverrideMask; // Viewport flags to override when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. - ImGuiViewportFlags ViewportFlagsOverrideValue; // Viewport flags values to override when a window of this class owns a viewport. - bool DockingAlwaysTabBar; // Set to true to enforce windows of this class always having their own tab (equivalent of setting the global io.ConfigDockingAlwaysTabBar) - bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. - - ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideMask = ViewportFlagsOverrideValue = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; } -}; - //----------------------------------------------------------------------------- // Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) // Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. From efc4c0fe9de2fd4c0cd6dde3b92a3a7a0d490138 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jul 2019 21:26:15 -0700 Subject: [PATCH 507/566] Internals: Made IMGUI_DEBUG_LOG redefinable in imconfig.h. Comments. Fix to allow Metrics's NodeWindow() being called with a NULL window. --- imgui.cpp | 8 +++++++- imgui_internal.h | 7 +++++-- imgui_widgets.cpp | 6 +++++- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7db3d6e0..e6cb324c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5143,6 +5143,7 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name) static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); // Create window the first time ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name); @@ -14571,7 +14572,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) static void NodeWindow(ImGuiWindow* window, const char* label) { - if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) + if (window == NULL) + { + ImGui::BulletText("%s: NULL", label); + return; + } + if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window)) return; ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->Viewport, window->DrawList, "DrawList"); diff --git a/imgui_internal.h b/imgui_internal.h index be6a0ca7..ddad75f4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -148,12 +148,15 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_NEWLINE "\n" #endif #define IM_TABSIZE (4) - -#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) #define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1] #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 +// Debug Logging +#ifndef IMGUI_DEBUG_LOG +#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) +#endif + // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall #ifdef _MSC_VER #define IMGUI_CDECL __cdecl diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4d9e9942..91033993 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5947,6 +5947,10 @@ void ImGui::EndMainMenuBar() End(); } +// FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere.. +// Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer. +// Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary. +// Then later the same system could be used for multiple menu-bars, scrollbars, side-bars. bool ImGui::BeginMenuBar() { ImGuiWindow* window = GetCurrentWindow(); @@ -5956,7 +5960,7 @@ bool ImGui::BeginMenuBar() return false; IM_ASSERT(!window->DC.MenuBarAppending); - BeginGroup(); // Backup position on layer 0 + BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore PushID("##menubar"); // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. From 969278fc0b4c1744f7223a90d4279569db690086 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jul 2019 21:29:43 -0700 Subject: [PATCH 508/566] Docking: Fixed dragging/resizing from OS decoration not marking settings as dirty. Internals: Added IMGUI_DEBUG_LOG_DOCKING, IMGUI_DEBUG_LOG_VIEWPORT macros to easily enable/disable a bunch of logging code. --- imgui.cpp | 54 +++++++++++++++++++++++++++++++++++++----------- imgui_internal.h | 4 ++++ 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e6cb324c..e4be3dc0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6108,7 +6108,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Synchronize window --> viewport in most situations // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM if (window->Viewport->PlatformRequestMove) + { window->Pos = window->Viewport->Pos; + MarkIniSettingsDirty(window); + } else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0) { viewport_rect_changed = true; @@ -6116,7 +6119,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } if (window->Viewport->PlatformRequestResize) + { window->Size = window->SizeFull = window->Viewport->Size; + MarkIniSettingsDirty(window); + } else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0) { viewport_rect_changed = true; @@ -6453,7 +6459,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { window->Viewport->PlatformRequestClose = false; g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. - //IMGUI_DEBUG_LOG("Window '%s' PlatformRequestClose\n", window->Name); + IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' PlatformRequestClose\n", window->Name); *p_open = false; } } @@ -10259,7 +10265,7 @@ void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* view if (g.CurrentViewport == viewport) return; g.CurrentViewport = viewport; - //IMGUI_DEBUG_LOG("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); + //IMGUI_DEBUG_LOG_VIEWPORT("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); // Notify platform layer of viewport changes // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI @@ -10414,7 +10420,7 @@ static void ImGui::UpdateViewportsNewFrame() g.Viewports.erase(g.Viewports.Data + n); // Destroy - //IMGUI_DEBUG_LOG("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + IMGUI_DEBUG_LOG_VIEWPORT("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here. IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false); IM_DELETE(viewport); @@ -10585,7 +10591,7 @@ ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const viewport->Flags = flags; UpdateViewportPlatformMonitor(viewport); g.Viewports.push_back(viewport); - //IMGUI_DEBUG_LOG("Add Viewport %08X (%s)\n", id, window->Name); + IMGUI_DEBUG_LOG_VIEWPORT("Add Viewport %08X (%s)\n", id, window->Name); // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame @@ -10709,7 +10715,7 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) { // Steal/transfer ownership - //IMGUI_DEBUG_LOG("[%05d] Window '%s' steal Viewport %08X from Window '%s'\n", g.FrameCount, window->Name, window->Viewport->ID, window->Viewport->Window->Name); + IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name); window->Viewport->Window = window; window->Viewport->ID = window->ID; window->Viewport->LastNameHash = 0; @@ -10773,7 +10779,7 @@ void ImGui::UpdatePlatformWindows() bool is_new_platform_window = (viewport->PlatformWindowCreated == false); if (is_new_platform_window) { - //IMGUI_DEBUG_LOG("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); + IMGUI_DEBUG_LOG_VIEWPORT("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); g.PlatformIO.Platform_CreateWindow(viewport); if (g.PlatformIO.Renderer_CreateWindow != NULL) g.PlatformIO.Renderer_CreateWindow(viewport); @@ -11187,7 +11193,7 @@ void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear // This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch void ImGui::DockContextRebuild(ImGuiContext* ctx) { - //IMGUI_DEBUG_LOG("[docking] full rebuild\n"); + IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); ImGuiDockContext* dc = ctx->DockContext; SaveIniSettingsToMemory(); ImGuiID root_id = 0; // Rebuild all @@ -11284,6 +11290,7 @@ static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id) id = DockContextGenNodeID(ctx); else IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL); + IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id); ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id); ctx->DockContext->Nodes.SetVoidPtr(node->ID, node); return node; @@ -11294,7 +11301,7 @@ static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiContext& g = *ctx; ImGuiDockContext* dc = ctx->DockContext; - //printf("[%05d] RemoveNode 0x%04X\n", node->ID); + IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID); IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node); IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL); IM_ASSERT(node->Windows.Size == 0); @@ -11380,6 +11387,7 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) remove |= (data_root->CountChildWindows == 0); if (remove) { + IMGUI_DEBUG_LOG_DOCKING("DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID); DockSettingsRemoveNodeReferences(&settings->ID, 1); settings->ID = 0; } @@ -11488,6 +11496,10 @@ void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) ImGuiWindow* payload_window = req->DockPayload; // Optional ImGuiWindow* target_window = req->DockTargetWindow; ImGuiDockNode* node = req->DockTargetNode; + if (payload_window) + IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window ? payload_window->Name : "NULL", req->DockSplitDir); + else + IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir); // Decide which Tab will be selected at the end of the operation ImGuiID next_selected_id = 0; @@ -11726,6 +11738,7 @@ static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, b DockNodeRemoveWindow(window->DockNode, window, 0); } IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); + IMGUI_DEBUG_LOG_DOCKING("DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name); node->Windows.push_back(window); node->WantHiddenTabBarUpdate = true; @@ -11783,6 +11796,7 @@ static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window //IM_ASSERT(window->RootWindow == node->HostWindow); //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin() IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID); + IMGUI_DEBUG_LOG_DOCKING("DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name); window->DockNode = NULL; window->DockIsActive = window->DockTabWantClose = false; @@ -12454,12 +12468,18 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w int tabs_unsorted_start = tab_bar->Tabs.Size; for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--) { + // FIXME-DOCKING: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted; tabs_unsorted_start = tab_n; } - //printf("[%05d] Sorting %d new appearing tabs\n", g.FrameCount, tab_bar->Tabs.Size - tabs_unsorted_start); + if (tab_bar->Tabs.Size > tabs_unsorted_start) + { + IMGUI_DEBUG_LOG_DOCKING("In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : ""); + for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++) + IMGUI_DEBUG_LOG_DOCKING(" - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder); if (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder); + } // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabID) != NULL) @@ -12985,6 +13005,7 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG IM_ASSERT(parent_node->TabBar == NULL); IM_ASSERT(parent_node->Windows.Size == 0); } + IMGUI_DEBUG_LOG_DOCKING("DockNodeTreeMerge 0x%08X & 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID); ImVec2 backup_last_explicit_size = parent_node->SizeRef; DockNodeMoveChildNodes(parent_node, merge_lead_child); @@ -13316,9 +13337,12 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla ImGuiDockNode* node = DockContextFindNodeByID(ctx, id); if (!node) { + IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X created\n", id); node = DockContextAddNode(ctx, id); node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; } + if (window_class && window_class->ClassId != node->WindowClass.ClassId) + IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId); node->SharedFlags = flags; node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); @@ -13352,6 +13376,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla SetNextWindowSize(node->Size); g.NextWindowData.PosUndock = false; + // FIXME-DOCKING: Why do we need a child window to host a dockspace, could we host it in the existing window? ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost; window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; @@ -13611,6 +13636,7 @@ ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_r { ImGuiContext* ctx = GImGui; IM_ASSERT(split_dir != ImGuiDir_None); + IMGUI_DEBUG_LOG_DOCKING("DockBuilderSplitNode node 0x%08X, split_dir %d\n", id, split_dir); ImGuiDockNode* node = DockContextFindNodeByID(ctx, id); if (node == NULL) @@ -13661,7 +13687,7 @@ static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID ds dst_node->ChildNodes[child_n]->ParentNode = dst_node; } - //IMGUI_DEBUG_LOG("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0); + IMGUI_DEBUG_LOG_DOCKING("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0); return dst_node; } @@ -13753,13 +13779,14 @@ void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_docks if (dst_dock_id != 0) { // Docked windows gets redocked into the new node hierarchy. - //IMGUI_DEBUG_LOG("Remap window '%s' %08X -> %08X\n", dst_window_name, src_dock_id, dst_dock_id); + IMGUI_DEBUG_LOG_DOCKING("Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id); DockBuilderDockWindow(dst_window_name, dst_dock_id); } else { // Floating windows gets their settings transferred (regardless of whether the new window already exist or not) // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? + IMGUI_DEBUG_LOG_DOCKING("Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name); DockBuilderCopyWindowSettings(src_window_name, dst_window_name); } } @@ -13778,7 +13805,7 @@ void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_docks continue; // Docked windows gets redocked into the new node hierarchy. - //IMGUI_DEBUG_LOG("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id); + IMGUI_DEBUG_LOG_DOCKING("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id); DockBuilderDockWindow(window->Name, dst_dock_id); } } @@ -14047,6 +14074,7 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id) { ImGuiContext& g = *GImGui; + IMGUI_DEBUG_LOG_DOCKING("DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id); for (int window_n = 0; window_n < g.Windows.Size; window_n++) { ImGuiWindow* window = g.Windows[window_n]; @@ -14586,6 +14614,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); + ImGui::BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId); ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y); ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); @@ -14897,6 +14926,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) char* p = buf; ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); int depth = DockNodeGetDepth(node); diff --git a/imgui_internal.h b/imgui_internal.h index ddad75f4..951f83a8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -156,6 +156,10 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #ifndef IMGUI_DEBUG_LOG #define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) #endif +#define IMGUI_DEBUG_LOG_VIEWPORT(...) ((void)0) // Disable log +#define IMGUI_DEBUG_LOG_DOCKING(...) ((void)0) // Disable log +//#define IMGUI_DEBUG_LOG_VIEWPORT IMGUI_DEBUG_LOG // Enable log +//#define IMGUI_DEBUG_LOG_DOCKING IMGUI_DEBUG_LOG // Enable log // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall #ifdef _MSC_VER From 824e8c53b43aa1bd0ed799ad563f7fa01cde4484 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jul 2019 21:26:15 -0700 Subject: [PATCH 509/566] Internals: Added IMGUI_DEBUG_INI_SETTINGS. Made IMGUI_DEBUG_LOG redefinable in imconfig.h. Comments. Fix to allow Metrics's NodeWindow() being called with a NULL window. --- imgui.cpp | 15 +++++++++++++-- imgui_internal.h | 7 +++++-- imgui_widgets.cpp | 6 +++++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4ecb2897..c1b78907 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -998,6 +998,7 @@ CODE // Debug options #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window +#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file // Visual Studio warnings #ifdef _MSC_VER @@ -4795,6 +4796,7 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name) static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; + //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); // Create window the first time ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name); @@ -9265,8 +9267,12 @@ ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) ImGuiContext& g = *GImGui; g.SettingsWindows.push_back(ImGuiWindowSettings()); ImGuiWindowSettings* settings = &g.SettingsWindows.back(); - if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() +#if !IMGUI_DEBUG_INI_SETTINGS + // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier. + if (const char* p = strstr(name, "###")) name = p; +#endif settings->Name = ImStrdup(name); settings->ID = ImHashStr(name); return settings; @@ -9791,7 +9797,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) static void NodeWindow(ImGuiWindow* window, const char* label) { - if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) + if (window == NULL) + { + ImGui::BulletText("%s: NULL", label); + return; + } + if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window)) return; ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->DrawList, "DrawList"); diff --git a/imgui_internal.h b/imgui_internal.h index d7c37c5f..dd2b8927 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -141,12 +141,15 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_NEWLINE "\n" #endif #define IM_TABSIZE (4) - -#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) #define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1] #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 +// Debug Logging +#ifndef IMGUI_DEBUG_LOG +#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) +#endif + // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall #ifdef _MSC_VER #define IMGUI_CDECL __cdecl diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3c48d247..5717f8e2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5935,6 +5935,10 @@ void ImGui::EndMainMenuBar() End(); } +// FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere.. +// Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer. +// Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary. +// Then later the same system could be used for multiple menu-bars, scrollbars, side-bars. bool ImGui::BeginMenuBar() { ImGuiWindow* window = GetCurrentWindow(); @@ -5944,7 +5948,7 @@ bool ImGui::BeginMenuBar() return false; IM_ASSERT(!window->DC.MenuBarAppending); - BeginGroup(); // Backup position on layer 0 + BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore PushID("##menubar"); // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. From 7c183dc6a15f9440536ace71bbb71f9f98454359 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 24 Jul 2019 11:18:13 -0700 Subject: [PATCH 510/566] Docking: Explicitly inhibit constraint when docked for now (#2690, #2109) Added asserts to catch issues. --- imgui.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 55ac8de1..4c2b8f58 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5852,6 +5852,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { BeginDocked(window, p_open); flags = window->Flags; + + // Docking currently override constraints + g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; } } @@ -13050,6 +13053,7 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si { // During the regular dock node update we write to all nodes. // 'only_write_to_marked_nodes' is only set when turning a node visible mid-frame and we need its size right-away. + IM_ASSERT(size.x > 0.0f && size.y > 0.0f); const bool write_to_node = (only_write_to_marked_nodes == false) || (node->MarkedForPosSizeWrite); if (write_to_node) { @@ -13082,6 +13086,7 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si child_0->WantLockSizeOnce = false; child_0_size[axis] = child_0->SizeRef[axis] = child_0->Size[axis]; child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } else if (child_1->WantLockSizeOnce) @@ -13089,6 +13094,7 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si child_1->WantLockSizeOnce = false; child_1_size[axis] = child_1->SizeRef[axis] = child_1->Size[axis]; child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node @@ -13373,6 +13379,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) if (size.y <= 0.0f) size.y = ImMax(content_avail.y + size.y, 4.0f); + IM_ASSERT(size.x > 0.0f && size.y > 0.0f); node->Pos = window->DC.CursorPos; node->Size = node->SizeRef = size; @@ -13493,6 +13500,7 @@ void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id); if (node == NULL) return; + IM_ASSERT(size.x > 0.0f && size.y > 0.0f); node->Size = node->SizeRef = size; node->AuthorityForSize = ImGuiDataAuthority_DockNode; } From e5b905481dd2d7c341befa99505487f8f86a62fd Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 24 Jul 2019 13:37:17 -0700 Subject: [PATCH 511/566] Viewport: Refactored ViewportFlagsOverrideMask+ViewportFlagsOverrideValue into ViewportFlagsOverrideSet+ViewportFlagsOverrideClear which appears easier to grasp. (#1542) (cherry picked from commit 9437630872e7ca19065bee78fcafaab54a0d5bf2) --- imgui.cpp | 9 ++++++--- imgui.h | 6 +++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4c2b8f58..3c051ee9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6162,8 +6162,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID; else window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; - if (window->WindowClass.ViewportFlagsOverrideMask) - viewport_flags = (viewport_flags & ~window->WindowClass.ViewportFlagsOverrideMask) | (window->WindowClass.ViewportFlagsOverrideValue & window->WindowClass.ViewportFlagsOverrideMask); + if (window->WindowClass.ViewportFlagsOverrideSet) + viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet; + if (window->WindowClass.ViewportFlagsOverrideClear) + viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear; // We also tell the back-end that clearing the platform window won't be necessary, as our window is filling the viewport and we have disabled BgAlpha viewport_flags |= ImGuiViewportFlags_NoRendererClear; @@ -7437,6 +7439,7 @@ void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond) void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class) { ImGuiContext& g = *GImGui; + IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass; g.NextWindowData.WindowClass = *window_class; } @@ -10291,7 +10294,7 @@ static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) { // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own. ImGuiContext& g = *GImGui; - if (g.IO.ConfigViewportsNoAutoMerge || ((window->WindowClass.ViewportFlagsOverrideValue & window->WindowClass.ViewportFlagsOverrideMask) & ImGuiViewportFlags_NoAutoMerge)) + if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge)) if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) if (!window->DockIsActive) if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0) diff --git a/imgui.h b/imgui.h index bc155d5d..50b98294 100644 --- a/imgui.h +++ b/imgui.h @@ -1588,12 +1588,12 @@ struct ImGuiWindowClass { ImGuiID ClassId; // User data. 0 = Default class (unclassed) ImGuiID ParentViewportId; // Hint for the platform back-end. If non-zero, the platform back-end can create a parent<>child relationship between the platform windows. Not conforming back-ends are free to e.g. parent every viewport to the main viewport or not. - ImGuiViewportFlags ViewportFlagsOverrideMask; // Viewport flags to override when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. - ImGuiViewportFlags ViewportFlagsOverrideValue; // Viewport flags values to override when a window of this class owns a viewport. + ImGuiViewportFlags ViewportFlagsOverrideSet; // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ImGuiViewportFlags ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. bool DockingAlwaysTabBar; // Set to true to enforce windows of this class always having their own tab (equivalent of setting the global io.ConfigDockingAlwaysTabBar) bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. - ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideMask = ViewportFlagsOverrideValue = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; } + ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideSet = ViewportFlagsOverrideClear = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; } }; // Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() From d057550209d794461744a91c812bf8e9e264f32f Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 24 Jul 2019 09:48:34 -0700 Subject: [PATCH 512/566] Fixed Clang 8.0 warning "empty expression statement has no effect; remove unnecessary ';' to silence this" warning [-Wextra-semi-stmt] + Comment --- imgui.cpp | 2 +- imgui.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c1b78907..0a2a53ee 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8171,7 +8171,7 @@ static void ImGui::NavUpdate() // Update Keyboard->Nav inputs mapping if (nav_keyboard_active) { - #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } + #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0) NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate ); NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input ); NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel ); diff --git a/imgui.h b/imgui.h index e14f564e..0b5ad558 100644 --- a/imgui.h +++ b/imgui.h @@ -327,7 +327,7 @@ namespace ImGui IMGUI_API void PushItemWidth(float item_width); // set width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side). 0.0f = default to ~2/3 of windows width, IMGUI_API void PopItemWidth(); IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) - IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets From 7a26a49f080426bd09c2034a01a57eeb81f46a21 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 26 Jul 2019 12:08:29 -0700 Subject: [PATCH 513/566] Internal: Added IsMouseDragPastThreshold(). Tweaks. Todo. Demo: Showing how to use the format parameter of Slider/Drag functions to display the name of an enum value instead of the underlying integer value --- docs/CHANGELOG.txt | 2 ++ docs/TODO.txt | 2 ++ imgui.cpp | 17 ++++++++++++++--- imgui_demo.cpp | 17 ++++++++++++++--- imgui_internal.h | 1 + 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f5b3bdb0..540e1e58 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -95,6 +95,8 @@ Other Changes: also this type was added in 1.71 and not advertised as a public-facing feature). - Fonts: binary_to_compressed_c.cpp: Display an error message if failing to open/read the input font file. - Demo: Log, Console: Using a simpler stateless pattern for auto-scrolling. +- Demo: Widgets: Showing how to use the format parameter of Slider/Drag functions to display the name + of an enum value instead of the underlying integer value. - Backends: DX10/DX11: Backup, clear and restore Geometry Shader is any is bound when calling renderer. - Backends: DX11: Clear Hull Shader, Domain Shader, Compute Shader before rendering. Not backing/restoring them. - Backends: OSX: Disabled default native Mac clipboard copy/paste implementation in core library (added in 1.71), diff --git a/docs/TODO.txt b/docs/TODO.txt index d0f2e84e..f289ebab 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -89,6 +89,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input text: decorrelate layout from inputs - e.g. what's the easiest way to implement a nice IP/Mac address input editor? - input text: global callback system so user can plug in an expression evaluator easily. (#1691) - input text: force scroll to end or scroll to a given line/contents (so user can implement a log or a search feature) + - input text: a way to preview completion (e.g. disabled text completing from the cursor) - input text: a side bar that could e.g. preview where errors are. probably left to the user to draw but we'd need to give them the info there. - input text: a way for the user to provide syntax coloring. - input text: Shift+TAB with ImGuiInputTextFlags_AllowTabInput could eat preceding blanks, up to tab_count. @@ -122,6 +123,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - columns: option to alternate background colors on odd/even scanlines. - columns: allow columns to recurse. - columns: allow a same columns set to be interrupted by e.g. CollapsingHeader and resume with columns in sync when moving them. + - columns: sizing is lossy when columns width is very small (default width may turn negative etc.) - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) - columns: flag to add horizontal separator above/below? - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) diff --git a/imgui.cpp b/imgui.cpp index 0a2a53ee..27c90033 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4433,17 +4433,25 @@ bool ImGui::IsMouseDoubleClicked(int button) return g.IO.MouseDoubleClicked[button]; } -bool ImGui::IsMouseDragging(int button, float lock_threshold) +// [Internal] This doesn't test if the button is presed +bool ImGui::IsMouseDragPastThreshold(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); - if (!g.IO.MouseDown[button]) - return false; if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; } +bool ImGui::IsMouseDragging(int button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; + return IsMouseDragPastThreshold(button, lock_threshold); +} + ImVec2 ImGui::GetMousePos() { return GImGui->IO.MousePos; @@ -9719,6 +9727,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (!node_open) return; + if (window && !window->WasActive) + ImGui::Text("(Note: owning Window is inactive: DrawList is not being rendered!)"); + int elem_offset = 0; for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b7b48a52..570d18db 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -539,8 +539,19 @@ static void ShowDemoWindowWidgets() static float f1=0.123f, f2=0.0f; ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); ImGui::SliderFloat("slider float (curve)", &f2, -10.0f, 10.0f, "%.4f", 2.0f); + static float angle = 0.0f; ImGui::SliderAngle("slider angle", &angle); + + // Using the format string to display a name instead of an integer. + // Here we completely omit '%d' from the format string, so it'll only display a name. + // This technique can also be used with DragInt(). + enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT }; + const char* element_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; + static int current_element = Element_Fire; + const char* current_element_name = (current_element >= 0 && current_element < Element_COUNT) ? element_names[current_element] : "Unknown"; + ImGui::SliderInt("slider enum", ¤t_element, 0, Element_COUNT - 1, current_element_name); + ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); } { @@ -1782,9 +1793,9 @@ static void ShowDemoWindowLayout() ImGui::Text("SetNextItemWidth/PushItemWidth(-1)"); ImGui::SameLine(); HelpMarker("Align to right edge"); ImGui::PushItemWidth(-1); - ImGui::DragFloat("float##5a", &f); - ImGui::DragFloat("float##5b", &f); - ImGui::DragFloat("float##5c", &f); + ImGui::DragFloat("##float5a", &f); + ImGui::DragFloat("##float5b", &f); + ImGui::DragFloat("##float5c", &f); ImGui::PopItemWidth(); ImGui::TreePop(); diff --git a/imgui_internal.h b/imgui_internal.h index dd2b8927..522914d3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1556,6 +1556,7 @@ namespace ImGui IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel); // Inputs + inline bool IsMouseDragPastThreshold(int button, float lock_threshold = -1.0f); inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { const int key_index = GImGui->IO.KeyMap[key]; return (key_index >= 0) ? IsKeyPressed(key_index, repeat) : false; } inline bool IsNavInputDown(ImGuiNavInput n) { return GImGui->IO.NavInputs[n] > 0.0f; } inline bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode) { return GetNavInputAmount(n, mode) > 0.0f; } From ecb9b1e2eba5becc38019b5c9f75fba711cd881b Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 27 Jul 2019 17:06:17 -0700 Subject: [PATCH 514/566] Version 1.72 --- docs/CHANGELOG.txt | 33 +++++++++++++++++---------------- docs/README.md | 23 ++++++++++++----------- examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 10 files changed, 39 insertions(+), 37 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 540e1e58..a9fcc258 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -30,7 +30,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.72 (In Progress) + VERSION 1.72 (Released 2019-07-27) ----------------------------------------------------------------------- Breaking Changes: @@ -45,37 +45,38 @@ Breaking Changes: Kept redirection function (will obsolete). (#581, #324) Other Changes: -- Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). -- Window: Mouse wheel scrolling while hovering a child window is automatically forwarded to parent window + comments about the right way to scale your UI (load a font at the right side, rebuild atlas, scale style). +- Scrolling: Made mouse-wheel scrolling lock the underlying window until the mouse is moved again or + until a short delay expires (~2 seconds). This allow uninterrupted scroll even if child windows are + passing under the mouse cursor. (#2604) +- Scrolling: Made it possible for mouse wheel and navigation-triggered scrolling to override a call to + SetScrollX()/SetScrollY(), making it possible to use a simpler stateless pattern for auto-scrolling: + // (Submit items..) + if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) // If scrolling at the already at the bottom.. + ImGui::SetScrollHereY(1.0f); // ..make last item fully visible +- Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] +- Scrolling: Mouse wheel scrolling while hovering a child window is automatically forwarded to parent window if ScrollMax is zero on the scrolling axis. - Also still case if ImGuiWindowFlags_NoScrollWithMouse is set (not new), but previously the forwarding + Also still the case if ImGuiWindowFlags_NoScrollWithMouse is set (not new), but previously the forwarding would be disabled if ImGuiWindowFlags_NoScrollbar was set on the child window, which is not the case any more. Forwarding can still be disabled by setting ImGuiWindowFlags_NoInputs. (amend #1502, #1380). +- Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). - Window: Fixed old SetWindowFontScale() api value from not being inherited by child window. Added - comments about the right way to scale your UI (load a font at the right side, rebuild atlas, scale style). +- Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Combo: Hide arrow when there's not enough space even for the square button. +- InputText: Testing for newly added ImGuiKey_KeyPadEnter key. (#2677, #2005) [@amc522] - TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). - Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column would wrongly use a WindowPadding.x instead of ItemSpacing.x like it always did. (#125, #2666) - Columns: Made the right-most edge reaches up to the clipping rectangle (removing half of WindowPadding.x worth of asymmetrical/extraneous padding, note that there's another half that conservatively has to offset - the right-most column, otherwise it's clipping width won't match the other column). (#125, #2666) + the right-most column, otherwise it's clipping width won't match the other columns). (#125, #2666) - Columns: Improved honoring alignment with various values of ItemSpacing.x and WindowPadding.x. (#125, #2666) - Columns: Made GetColumnOffset() and GetColumnWidth() behave when there's no column set, consistently with other column functions. (#2683) - InputTextMultiline: Fixed vertical scrolling tracking glitch. - Word-wrapping: Fixed overzealous word-wrapping when glyph edge lands exactly on the limit. Because of this, auto-fitting exactly unwrapped text would make it wrap. (fixes initial 1.15 commit, 78645a7d). -- Scrolling: Made mouse-wheel scrolling lock the underlying window until the mouse is moved again or - until a short delay expires (2 seconds). This allow uninterrupted scroll even if child windows are - passing under the mouse cursor. (#2604) -- Scrolling: Made it possible for mouse wheel and navigation-triggered scrolling to override a call to - SetScrollX()/SetScrollY(), making it possible to use a simpler stateless pattern for auto-scrolling: - // (Submit items..) - if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) // Keep scrolling at the bottom if already - ImGui::SetScrollHereY(1.0f); -- Scrolling: Added SetScrollHereX(), SetScrollFromPosX() for completeness. (#1580) [@kevreco] -- Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. diff --git a/docs/README.md b/docs/README.md index d020ea07..5a706354 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3,7 +3,10 @@ dear imgui [![Build Status](https://api.travis-ci.com/ocornut/imgui.svg?branch=master)](https://travis-ci.com/ocornut/imgui) [![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720) -_(This library is free as in freedom, but needs your support to sustain its development. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using dear imgui, please consider reaching out for invoiced financial support. If you are an individual using dear imgui, please consider donating via Patreon or PayPal.)_ +_(This library is available under a free and permissive licence, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using dear imgui, please consider reaching out. If you are an individual using dear imgui, please consider supporting the project via Patreon or PayPal.)_ + +Businesses: support continued development via invoiced technical support & maintenance contracts: +
  _E-mail: omarcornut at gmail dot com_ Individuals/hobbyists: support continued maintenance and development via the monthly Patreon:
  [![Patreon](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/patreon_01.png)](http://www.patreon.com/imgui) @@ -11,9 +14,6 @@ Individuals/hobbyists: support continued maintenance and development via the mon Individuals/hobbyists: support continued maintenance and development via PayPal:
  [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S) -Businesses: support continued maintenance and development via support contracts or sponsoring: -
  _E-mail: omarcornut at gmail dot com_ - Dear ImGui is a bloat-free graphical user interface library for C++. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies). Dear ImGui is designed to enable fast iterations and to empower programmers to create content creation tools and visualization / debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and lacks certain features normally found in more high-level libraries. @@ -290,7 +290,10 @@ Support dear imgui **How can I help financing further development of Dear ImGui?** -Your contributions are keeping this project alive. The library is free as in freedom, but continued maintenance and development are a full-time endeavor. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using dear imgui, please consider reaching out for financial support. If you are an individual using dear imgui, please consider donating via Patreon or PayPal. Thank you! +Your contributions are keeping this project alive. The library is available under a free and permissive licence, but continued maintenance and development are a full-time endeavor and I would like to grow the team. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using dear imgui, please consider reaching out for invoiced technical support and maintenance contracts. If you are an individual using dear imgui, please consider supporting the project via Patreon or PayPal. Thank you! + +Businesses: support continued development via invoiced technical support & maintenance contracts: +
  _E-mail: omarcornut at gmail dot com_ Individuals/hobbyists: support continued maintenance and development via the monthly Patreon:
  [![Patreon](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/patreon_01.png)](http://www.patreon.com/imgui) @@ -298,22 +301,20 @@ Individuals/hobbyists: support continued maintenance and development via the mon Individuals/hobbyists: support continued maintenance and development via PayPal:
  [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S) -Businesses: support continued maintenance and development via support contracts or sponsoring: -
  _E-mail: omarcornut at gmail dot com_ - Ongoing dear imgui development is financially supported by users and private sponsors, recently: **Platinum-chocolate sponsors** -- **Blizzard Entertainment**. +- Blizzard Entertainment +- Google **Double-chocolate sponsors** - Media Molecule, Mobigame, Aras Pranckevičius, Greggman, DotEmu, Nadeo, Supercell, Runner, Aiden Koss, Kylotonn. **Salty caramel supporters** -- Remedy Entertainment, Recognition Robotics, ikrima, Geoffrey Evans, Mercury Labs, Singularity Demo Group, Lionel Landwerlin, Ron Gilbert, Brandon Townsend, Nikhil Deshpande, Cort Stratton, drudru, Harfang 3D, Jeff Roberts, Rainway inc, Ondra Voves, Mesh Consultants, Unit 2 Games, Neil Bickford. +- Remedy Entertainment, Recognition Robotics, ikrima, Geoffrey Evans, Mercury Labs, Singularity Demo Group, Lionel Landwerlin, Ron Gilbert, Brandon Townsend, Morten Skaaning, Nikhil Deshpande, Cort Stratton, drudru, Harfang 3D, Jeff Roberts, Rainway inc, Ondra Voves, Mesh Consultants, Unit 2 Games, Neil Bickford. **Caramel supporters** -- Jerome Lanquetot, Daniel Collin, Ctrl Alt Ninja, Neil Henning, Neil Blakey-Milner, Aleksei, NeiloGD, Eric, Game Atelier, Vincent Hamm, Colin Riley, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, Josh Faust, Martin Donlon, Codecat, Doug McNabb, Emmanuel Julien, Guillaume Chereau, Jeffrey Slutter, Jeremiah Deckard, r-lyeh, Nekith, Joshua Fisher, Malte Hoffmann, Mustafa Karaalioglu, Merlyn Morgan-Graham, Per Vognsen, Fabian Giesen, Jan Staubach, Matt Hargett, John Shearer, Jesse Chounard, kingcoopa, Jonas Bernemann, Johan Andersson, Michael Labbe, Tomasz Golebiowski, Louis Schnellbach, Jimmy Andrews, Bojan Endrovski, Robin Berg Pettersen, Rachel Crawford, Andrew Johnson, Sean Hunter, Jordan Mellow, Nefarius Software Solutions, Laura Wieme, Robert Nix, Mick Honey, Steven Kah Hien Wong, Bartosz Bielecki, Oscar Penas, A M, Liam Moynihan, Artometa, Mark Lee, Dimitri Diakopoulos, Pete Goodwin, Johnathan Roatch, nyu lea, Oswald Hurlem, Semyon Smelyanskiy, Le Bach, Jeong MyeongSoo, Chris Matthews, Astrofra. +- Jerome Lanquetot, Daniel Collin, Ctrl Alt Ninja, Neil Henning, Neil Blakey-Milner, Aleksei, NeiloGD, Eric, Game Atelier, Vincent Hamm, Colin Riley, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, Josh Faust, Martin Donlon, Codecat, Doug McNabb, Emmanuel Julien, Guillaume Chereau, Jeffrey Slutter, Jeremiah Deckard, r-lyeh, Nekith, Joshua Fisher, Malte Hoffmann, Mustafa Karaalioglu, Merlyn Morgan-Graham, Per Vognsen, Fabian Giesen, Jan Staubach, Matt Hargett, John Shearer, Jesse Chounard, kingcoopa, Jonas Bernemann, Johan Andersson, Michael Labbe, Tomasz Golebiowski, Louis Schnellbach, Jimmy Andrews, Bojan Endrovski, Robin Berg Pettersen, Rachel Crawford, Andrew Johnson, Sean Hunter, Jordan Mellow, Nefarius Software Solutions, Laura Wieme, Robert Nix, Mick Honey, Steven Kah Hien Wong, Bartosz Bielecki, Oscar Penas, A M, Liam Moynihan, Artometa, Mark Lee, Dimitri Diakopoulos, Pete Goodwin, Johnathan Roatch, nyu lea, Oswald Hurlem, Semyon Smelyanskiy, Le Bach, Jeong MyeongSoo, Chris Matthews, Astrofra, Frederik De Bleser, Anticrisis. And all other past and present supporters; THANK YOU! (Please contact me if you would like to be added or removed from this list) diff --git a/examples/README.txt b/examples/README.txt index 5028583b..ded7d12a 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.72 WIP + dear imgui, v1.72 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 27c90033..ce9e1c1e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 WIP +// dear imgui, v1.72 // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index 0b5ad558..23efa5d6 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.72 WIP +// dear imgui, v1.72 // (headers) // See imgui.cpp file for documentation. @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.72 WIP" -#define IMGUI_VERSION_NUM 17102 +#define IMGUI_VERSION "1.72" +#define IMGUI_VERSION_NUM 17200 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 570d18db..af8b422b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 WIP +// dear imgui, v1.72 // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 45cf9ecb..a03f5855 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 WIP +// dear imgui, v1.72 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 522914d3..eef74b0f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.72 WIP +// dear imgui, v1.72 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5717f8e2..f06dec60 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 WIP +// dear imgui, v1.72 // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index cf953cf6..a17e9f15 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.72 WIP +dear imgui, v1.72 (Font Readme) --------------------------------------- From 949a9fa2cbab18f6d15bf84d3fad438ddcc502ec Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Mon, 29 Jul 2019 15:52:30 -0700 Subject: [PATCH 515/566] Vulkan: Fix crash when viewports are disabled and memory leak on shutdown. (#2698) --- examples/imgui_impl_vulkan.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 74d111ea..b9026e92 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -850,8 +850,17 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend void ImGui_ImplVulkan_Shutdown() { - ImGui_ImplVulkan_ShutdownPlatformInterface(); + // First destroy objects in all viewports ImGui_ImplVulkan_DestroyDeviceObjects(); + + // Manually delete main viewport render data in-case we haven't initialized for viewports + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + if (ImGuiViewportDataVulkan* data = (ImGuiViewportDataVulkan*)main_viewport->RendererUserData) + IM_DELETE(data); + main_viewport->RendererUserData = NULL; + + // Clean up windows + ImGui_ImplVulkan_ShutdownPlatformInterface(); } void ImGui_ImplVulkan_NewFrame() From 9183e7c4267aadfb3d7a28e96092b40a590cf9fc Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jul 2019 15:54:32 -0700 Subject: [PATCH 516/566] Version 1.73 WIP --- docs/CHANGELOG.txt | 5 +++++ examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 9 files changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a9fcc258..58d2ff63 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -29,6 +29,11 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.73 (In Progress) +----------------------------------------------------------------------- + + ----------------------------------------------------------------------- VERSION 1.72 (Released 2019-07-27) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index ded7d12a..7e46c843 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.72 + dear imgui, v1.73 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index ce9e1c1e..8cbfa129 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 +// dear imgui, v1.73 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index 23efa5d6..ed7712f1 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.72 +// dear imgui, v1.73 WIP // (headers) // See imgui.cpp file for documentation. @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.72" -#define IMGUI_VERSION_NUM 17200 +#define IMGUI_VERSION "1.73 WIP" +#define IMGUI_VERSION_NUM 17201 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index af8b422b..65c0355d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 +// dear imgui, v1.73 WIP // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a03f5855..3e5ca061 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 +// dear imgui, v1.73 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index eef74b0f..fdade58b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.72 +// dear imgui, v1.73 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f06dec60..add9d7cd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72 +// dear imgui, v1.73 WIP // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index a17e9f15..b8790af6 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.72 +dear imgui, v1.73 WIP (Font Readme) --------------------------------------- From cb2de62bb169c033d42959d9d9a09b3a23056c3f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jul 2019 15:40:07 -0700 Subject: [PATCH 517/566] Docking: Renaming, comments. --- imgui.cpp | 52 ++++++++++++++++++++++++------------------------ imgui_internal.h | 4 ++-- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 376ded2e..36f32238 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11073,15 +11073,15 @@ struct ImGuiDockPreviewData struct ImGuiDockNodeSettings { ImGuiID ID; - ImGuiID ParentID; - ImGuiID SelectedTabID; + ImGuiID ParentNodeID; + ImGuiID SelectedWindowID; signed char SplitAxis; char Depth; ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_) ImVec2ih Pos; ImVec2ih Size; ImVec2ih SizeRef; - ImGuiDockNodeSettings() { ID = ParentID = SelectedTabID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } + ImGuiDockNodeSettings() { ID = ParentNodeID = SelectedWindowID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } }; struct ImGuiDockContext @@ -11374,10 +11374,10 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++) { ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; - ImGuiDockContextPruneNodeData* parent_data = settings->ParentID ? pool.GetByKey(settings->ParentID) : 0; + ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeID ? pool.GetByKey(settings->ParentNodeID) : 0; pool.GetOrAddByKey(settings->ID)->RootID = parent_data ? parent_data->RootID : settings->ID; - if (settings->ParentID) - pool.GetOrAddByKey(settings->ParentID)->CountChildNodes++; + if (settings->ParentNodeID) + pool.GetOrAddByKey(settings->ParentNodeID)->CountChildNodes++; } // Count reference to dock ids from window settings @@ -11400,8 +11400,8 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) ImGuiDockContextPruneNodeData* data_root = (data->RootID == settings->ID) ? data : pool.GetByKey(data->RootID); bool remove = false; - remove |= (data->CountWindows == 1 && settings->ParentID == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window - remove |= (data->CountWindows == 0 && settings->ParentID == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window + remove |= (data->CountWindows == 1 && settings->ParentNodeID == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window + remove |= (data->CountWindows == 0 && settings->ParentNodeID == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window remove |= (data_root->CountChildWindows == 0); if (remove) { @@ -11421,7 +11421,7 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc if (settings->ID == 0) continue; ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID); - node->ParentNode = settings->ParentID ? DockContextFindNodeByID(ctx, settings->ParentID) : NULL; + node->ParentNode = settings->ParentNodeID ? DockContextFindNodeByID(ctx, settings->ParentNodeID) : NULL; node->Pos = ImVec2(settings->Pos.x, settings->Pos.y); node->Size = ImVec2(settings->Size.x, settings->Size.y); node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y); @@ -11430,7 +11430,7 @@ static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDoc node->ParentNode->ChildNodes[0] = node; else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL) node->ParentNode->ChildNodes[1] = node; - node->SelectedTabID = settings->SelectedTabID; + node->SelectedTabID = settings->SelectedWindowID; node->SplitAxis = settings->SplitAxis; node->LocalFlags |= (settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_); @@ -14164,9 +14164,9 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); } else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; } else return; - if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return; - if (sscanf(line, " Parent=0x%08X%n", &node.ParentID, &r) == 1) { line += r; if (node.ParentID == 0) return; } - if (node.ParentID == 0) + if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return; + if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeID, &r) == 1) { line += r; if (node.ParentNodeID == 0) return; } + if (node.ParentNodeID == 0) { if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return; if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return; @@ -14182,10 +14182,10 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; } if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; } if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; } - if (sscanf(line, " SelectedTab=0x%08X%n", &node.SelectedTabID,&r) == 1) { line += r; } + if (sscanf(line, " Selected=0x%08X%n", &node.SelectedWindowID,&r) == 1) { line += r; } ImGuiDockContext* dc = ctx->DockContext; - if (node.ParentID != 0) - if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentID)) + if (node.ParentNodeID != 0) + if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeID)) node.Depth = parent_settings->Depth + 1; dc->SettingsNodes.push_back(node); } @@ -14195,8 +14195,8 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo ImGuiDockNodeSettings node_settings; IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3))); node_settings.ID = node->ID; - node_settings.ParentID = node->ParentNode ? node->ParentNode->ID : 0; - node_settings.SelectedTabID = node->SelectedTabID; + node_settings.ParentNodeID = node->ParentNode ? node->ParentNode->ID : 0; + node_settings.SelectedWindowID = node->SelectedTabID; node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None; node_settings.Depth = (char)depth; node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_); @@ -14238,8 +14238,8 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n]; buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file buf->appendf(" ID=0x%08X", node_settings->ID); - if (node_settings->ParentID) - buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentID, node_settings->SizeRef.x, node_settings->SizeRef.y); + if (node_settings->ParentNodeID) + buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeID, node_settings->SizeRef.x, node_settings->SizeRef.y); else buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); if (node_settings->SplitAxis != ImGuiAxis_None) @@ -14256,8 +14256,8 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings buf->appendf(" NoWindowMenuButton=1"); if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton) buf->appendf(" NoCloseButton=1"); - if (node_settings->SelectedTabID) - buf->appendf(" SelectedTab=0x%08X", node_settings->SelectedTabID); + if (node_settings->SelectedWindowID) + buf->appendf(" Selected=0x%08X", node_settings->SelectedWindowID); #if IMGUI_DEBUG_INI_SETTINGS // [DEBUG] Include comments in the .ini file to ease debugging @@ -14844,14 +14844,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) { ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n]; const char* selected_tab_name = NULL; - if (settings->SelectedTabID) + if (settings->SelectedWindowID) { - if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabID)) + if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowID)) selected_tab_name = window->Name; - else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabID)) + else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowID)) selected_tab_name = window_settings->Name; } - ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentID, settings->SelectedTabID, selected_tab_name ? selected_tab_name : settings->SelectedTabID ? "N/A" : ""); + ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeID, settings->SelectedWindowID, selected_tab_name ? selected_tab_name : settings->SelectedWindowID ? "N/A" : ""); } ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index bd6a2539..2699a37b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -950,8 +950,8 @@ struct ImGuiDockNode int LastFrameActive; // Last frame number the node was updated. int LastFrameFocused; // Last frame number the node was focused. ImGuiID LastFocusedNodeID; // [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. - ImGuiID SelectedTabID; // [Tab node only] Which of our tab is selected. - ImGuiID WantCloseTabID; // [Tab node only] Set when closing a specific tab. + ImGuiID SelectedTabID; // [Leaf node only] Which of our tab/window is selected. + ImGuiID WantCloseTabID; // [Leaf node only] Set when closing a specific tab/window. ImGuiDataAuthority AuthorityForPos :3; ImGuiDataAuthority AuthorityForSize :3; ImGuiDataAuthority AuthorityForViewport :3; From 07c52a25ffaf1f7e8ee69386bd9c343030da153e Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jul 2019 15:40:51 -0700 Subject: [PATCH 518/566] Docking: Recording dockspace parent window so pruning doesn't zealously lose the location of nodes. (#2109) --- imgui.cpp | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 36f32238..5f0bbe69 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11074,6 +11074,7 @@ struct ImGuiDockNodeSettings { ImGuiID ID; ImGuiID ParentNodeID; + ImGuiID ParentWindowID; ImGuiID SelectedWindowID; signed char SplitAxis; char Depth; @@ -11081,7 +11082,7 @@ struct ImGuiDockNodeSettings ImVec2ih Pos; ImVec2ih Size; ImVec2ih SizeRef; - ImGuiDockNodeSettings() { ID = ParentNodeID = SelectedWindowID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } + ImGuiDockNodeSettings() { ID = ParentNodeID = ParentWindowID = SelectedWindowID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } }; struct ImGuiDockContext @@ -11380,6 +11381,18 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) pool.GetOrAddByKey(settings->ParentNodeID)->CountChildNodes++; } + // Count reference to dock ids from dockspaces + // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() + for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++) + { + ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; + if (settings->ParentWindowID != 0) + if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowID)) + if (window_settings->DockId) + if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId)) + data->CountChildNodes++; + } + // Count reference to dock ids from window settings for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++) if (ImGuiID dock_id = g.SettingsWindows[settings_n].DockId) @@ -14166,6 +14179,7 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings else return; if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return; if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeID, &r) == 1) { line += r; if (node.ParentNodeID == 0) return; } + if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowID, &r) ==1) { line += r; if (node.ParentWindowID == 0) return; } if (node.ParentNodeID == 0) { if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return; @@ -14196,6 +14210,7 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3))); node_settings.ID = node->ID; node_settings.ParentNodeID = node->ParentNode ? node->ParentNode->ID : 0; + node_settings.ParentWindowID = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0; node_settings.SelectedWindowID = node->SelectedTabID; node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None; node_settings.Depth = (char)depth; @@ -14239,9 +14254,15 @@ static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettings buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file buf->appendf(" ID=0x%08X", node_settings->ID); if (node_settings->ParentNodeID) + { buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeID, node_settings->SizeRef.x, node_settings->SizeRef.y); + } else + { + if (node_settings->ParentWindowID) + buf->appendf(" Window=0x%08X", node_settings->ParentWindowID); buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); + } if (node_settings->SplitAxis != ImGuiAxis_None) buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y'); if (node_settings->Flags & ImGuiDockNodeFlags_NoResize) From 85ad8e0e2e4c928d69883dfa7f42bd368adf4ec0 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jul 2019 14:26:02 -0700 Subject: [PATCH 519/566] Nav: Fixed an issue with NavFlattened window flag where widgets not entirely fitting in child window (often selectable because of their extruded bits) would be not considered to navigate toward the child window. (#787) This creates a little bit of tension because g.NavDisableHighlight tends to makes the reference point not always visible. Amend c665c15a7d5942037852027cec88de9ccc2494ac --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 8cbfa129..ef50ee5b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7761,7 +7761,7 @@ static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) if (window->ParentWindow == g.NavWindow) { IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened); - if (!window->ClipRect.Contains(cand)) + if (!window->ClipRect.Overlaps(cand)) return false; cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window } From 494d804735a47e1a0f453590b4337948f462558f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jul 2019 15:02:40 -0700 Subject: [PATCH 520/566] Internal: Added ImGuiInputTextState::ClearText() helper. --- imgui_internal.h | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index fdade58b..43a450f8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -630,22 +630,23 @@ struct IMGUI_API ImGuiInputTextState float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection - - // Temporarily set when active - ImGuiInputTextFlags UserFlags; - ImGuiInputTextCallback UserCallback; - void* UserCallbackData; + ImGuiInputTextFlags UserFlags; // Temporarily set while we call user's callback + ImGuiInputTextCallback UserCallback; // " + void* UserCallbackData; // " ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } + void ClearText() { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); } void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); } + int GetUndoAvailCount() const { return Stb.undostate.undo_point; } + int GetRedoAvailCount() const { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; } + void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation + + // Cursor & Selection void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } bool HasSelection() const { return Stb.select_start != Stb.select_end; } void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } - int GetUndoAvailCount() const { return Stb.undostate.undo_point; } - int GetRedoAvailCount() const { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; } - void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation }; // Windows data saved in imgui.ini file From 5ef7445d922fd9fb5c59bedf2dada2926a4100e0 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jul 2019 16:48:15 -0700 Subject: [PATCH 521/566] Internal: Avoid using GImGui multiple times in same function. --- imgui.cpp | 42 ++++++++++++++++++++++++++---------------- imgui_widgets.cpp | 2 +- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ef50ee5b..0c24e497 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3171,13 +3171,15 @@ void ImGui::MemFree(void* ptr) const char* ImGui::GetClipboardText() { - return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; + ImGuiContext& g = *GImGui; + return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { - if (GImGui->IO.SetClipboardTextFn) - GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); + ImGuiContext& g = *GImGui; + if (g.IO.SetClipboardTextFn) + g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text); } const char* ImGui::GetVersion() @@ -4331,15 +4333,18 @@ bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool c int ImGui::GetKeyIndex(ImGuiKey imgui_key) { IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); - return GImGui->IO.KeyMap[imgui_key]; + ImGuiContext& g = *GImGui; + return g.IO.KeyMap[imgui_key]; } // Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]! bool ImGui::IsKeyDown(int user_key_index) { - if (user_key_index < 0) return false; - IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); - return GImGui->IO.KeysDown[user_key_index]; + if (user_key_index < 0) + return false; + ImGuiContext& g = *GImGui; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + return g.IO.KeysDown[user_key_index]; } int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate) @@ -4948,7 +4953,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s float target_x = window->ScrollTarget.x; if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x) target_x = 0.0f; - else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + GImGui->Style.ItemSpacing.x) + else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x) target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f; scroll.x = target_x - cr_x * window->InnerRect.GetWidth(); } @@ -6139,7 +6144,7 @@ void ImGui::PushMultiItemsWidths(int components, float w_full) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - const ImGuiStyle& style = GImGui->Style; + const ImGuiStyle& style = g.Style; const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); window->DC.ItemWidthStack.push_back(w_item_last); @@ -6969,7 +6974,8 @@ void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); window->ScrollTargetCenterRatio.x = center_x_ratio; @@ -6978,7 +6984,8 @@ void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); window->ScrollTargetCenterRatio.y = center_y_ratio; @@ -6987,19 +6994,21 @@ void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. void ImGui::SetScrollHereX(float center_x_ratio) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space float last_item_width = window->DC.LastItemRect.GetWidth(); - target_x += (last_item_width * center_x_ratio) + (GImGui->Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. + target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. SetScrollFromPosX(target_x, center_x_ratio); } // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. void ImGui::SetScrollHereY(float center_y_ratio) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space - target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. + target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. SetScrollFromPosY(target_y, center_y_ratio); } @@ -9640,7 +9649,8 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { // Notify OS Input Method Editor of text input position - if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) + ImGuiIO& io = ImGui::GetIO(); + if (HWND hwnd = (HWND)io.ImeWindowHandle) if (HIMC himc = ::ImmGetContext(hwnd)) { COMPOSITIONFORM cf; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index add9d7cd..07e8d2e3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3123,7 +3123,7 @@ namespace ImStb static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->TextW[idx]; } -static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *GImGui; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) From 1b1e53928843e4c2fe645dba39bcd0f7a333318f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jul 2019 18:21:44 -0700 Subject: [PATCH 522/566] Internal: Moved NavScrollToBringItemIntoView() declaration to imgui_internal.h. Fixed spacing missing in 494d804. Fixed changelog wreck from 1.72. --- docs/CHANGELOG.txt | 2 +- imgui.cpp | 3 +-- imgui_demo.cpp | 14 +++++++------- imgui_internal.h | 15 ++++++++------- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 58d2ff63..c5652c96 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,7 +50,6 @@ Breaking Changes: Kept redirection function (will obsolete). (#581, #324) Other Changes: - comments about the right way to scale your UI (load a font at the right side, rebuild atlas, scale style). - Scrolling: Made mouse-wheel scrolling lock the underlying window until the mouse is moved again or until a short delay expires (~2 seconds). This allow uninterrupted scroll even if child windows are passing under the mouse cursor. (#2604) @@ -67,6 +66,7 @@ Other Changes: any more. Forwarding can still be disabled by setting ImGuiWindowFlags_NoInputs. (amend #1502, #1380). - Window: Fixed InnerClipRect right-most coordinates using wrong padding setting (introduced in 1.71). - Window: Fixed old SetWindowFontScale() api value from not being inherited by child window. Added + comments about the right way to scale your UI (load a font at the right side, rebuild atlas, scale style). - Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Combo: Hide arrow when there's not enough space even for the square button. - InputText: Testing for newly added ImGuiKey_KeyPadEnter key. (#2677, #2005) [@amc522] diff --git a/imgui.cpp b/imgui.cpp index 0c24e497..085aa0a0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8139,8 +8139,7 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput } // Scroll to keep newly navigated item fully into view -// NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated. -static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) +void ImGui::NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) { ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 65c0355d..7fb29ec7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2064,23 +2064,23 @@ static void ShowDemoWindowLayout() // Vertical scroll functions HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position."); - static bool track = true; static int track_item = 50; + static bool enable_track = true; static float scroll_to_off_px = 0.0f; static float scroll_to_pos_px = 200.0f; - ImGui::Checkbox("Track", &track); + ImGui::Checkbox("Track", &enable_track); ImGui::PushItemWidth(100); - ImGui::SameLine(140); track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); + ImGui::SameLine(140); enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); bool scroll_to_off = ImGui::Button("Scroll Offset"); ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, 9999, "+%.0f px"); bool scroll_to_pos = ImGui::Button("Scroll To Pos"); ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, 0, 9999, "X/Y = %.0f px"); - ImGui::PopItemWidth(); + if (scroll_to_off || scroll_to_pos) - track = false; + enable_track = false; ImGuiStyle& style = ImGui::GetStyle(); float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; @@ -2101,7 +2101,7 @@ static void ShowDemoWindowLayout() ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f); for (int item = 0; item < 100; item++) { - if (track && item == track_item) + if (enable_track && item == track_item) { ImGui::TextColored(ImVec4(1,1,0,1), "Item %d", item); ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom @@ -2133,7 +2133,7 @@ static void ShowDemoWindowLayout() ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f); for (int item = 0; item < 100; item++) { - if (track && item == track_item) + if (enable_track && item == track_item) { ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item); ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right diff --git a/imgui_internal.h b/imgui_internal.h index 43a450f8..1cc8e990 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -634,19 +634,19 @@ struct IMGUI_API ImGuiInputTextState ImGuiInputTextCallback UserCallback; // " void* UserCallbackData; // " - ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } + ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } void ClearText() { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); } - void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); } + void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); } int GetUndoAvailCount() const { return Stb.undostate.undo_point; } int GetRedoAvailCount() const { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; } void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation // Cursor & Selection - void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking - void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } - bool HasSelection() const { return Stb.select_start != Stb.select_end; } - void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } - void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } + void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking + void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } + bool HasSelection() const { return Stb.select_start != Stb.select_end; } + void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } + void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } }; // Windows data saved in imgui.ini file @@ -1549,6 +1549,7 @@ namespace ImGui IMGUI_API void NavMoveRequestCancel(); IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags); IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); + IMGUI_API void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect); IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode); IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f); IMGUI_API int CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate); From 3548fb80134cdf90565241d0930db38ba1d7fcf7 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jul 2019 20:04:02 -0700 Subject: [PATCH 523/566] Internal refactor: moved all Scroll related functions in a same spot. --- imgui.cpp | 322 ++++++++++++++++++++++++----------------------- imgui_internal.h | 8 +- 2 files changed, 169 insertions(+), 161 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 085aa0a0..316a71ee 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -72,6 +72,7 @@ CODE // [SECTION] ImGuiListClipper // [SECTION] RENDER HELPERS // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) +// [SECTION] SCROLLING // [SECTION] TOOLTIPS // [SECTION] POPUPS // [SECTION] KEYBOARD/GAMEPAD NAVIGATION @@ -4943,40 +4944,6 @@ ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents)); } -static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) -{ - ImGuiContext& g = *GImGui; - ImVec2 scroll = window->Scroll; - if (window->ScrollTarget.x < FLT_MAX) - { - float cr_x = window->ScrollTargetCenterRatio.x; - float target_x = window->ScrollTarget.x; - if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x) - target_x = 0.0f; - else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x) - target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f; - scroll.x = target_x - cr_x * window->InnerRect.GetWidth(); - } - if (window->ScrollTarget.y < FLT_MAX) - { - // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. - float cr_y = window->ScrollTargetCenterRatio.y; - float target_y = window->ScrollTarget.y; - if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) - target_y = 0.0f; - if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y) - target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f; - scroll.y = target_y - cr_y * window->InnerRect.GetHeight(); - } - scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); - if (!window->Collapsed && !window->SkipItems) - { - scroll.x = ImMin(scroll.x, window->ScrollMax.x); - scroll.y = ImMin(scroll.y, window->ScrollMax.y); - } - return scroll; -} - static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags) { if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) @@ -6921,97 +6888,6 @@ void ImGui::SetCursorScreenPos(const ImVec2& pos) window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } -float ImGui::GetScrollX() -{ - ImGuiWindow* window = GImGui->CurrentWindow; - return window->Scroll.x; -} - -float ImGui::GetScrollY() -{ - ImGuiWindow* window = GImGui->CurrentWindow; - return window->Scroll.y; -} - -float ImGui::GetScrollMaxX() -{ - ImGuiWindow* window = GImGui->CurrentWindow; - return window->ScrollMax.x; -} - -float ImGui::GetScrollMaxY() -{ - ImGuiWindow* window = GImGui->CurrentWindow; - return window->ScrollMax.y; -} - -void ImGui::SetScrollX(float scroll_x) -{ - ImGuiWindow* window = GetCurrentWindow(); - window->ScrollTarget.x = scroll_x; - window->ScrollTargetCenterRatio.x = 0.0f; -} - -void ImGui::SetScrollY(float scroll_y) -{ - ImGuiWindow* window = GetCurrentWindow(); - window->ScrollTarget.y = scroll_y; - window->ScrollTargetCenterRatio.y = 0.0f; -} - -void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x) -{ - window->ScrollTarget.x = new_scroll_x; - window->ScrollTargetCenterRatio.x = 0.0f; -} - -void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) -{ - window->ScrollTarget.y = new_scroll_y; - window->ScrollTargetCenterRatio.y = 0.0f; -} - -void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) -{ - // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); - window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); - window->ScrollTargetCenterRatio.x = center_x_ratio; -} - -void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) -{ - // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); - window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); - window->ScrollTargetCenterRatio.y = center_y_ratio; -} - -// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. -void ImGui::SetScrollHereX(float center_x_ratio) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space - float last_item_width = window->DC.LastItemRect.GetWidth(); - target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. - SetScrollFromPosX(target_x, center_x_ratio); -} - -// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. -void ImGui::SetScrollHereY(float center_y_ratio) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space - target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. - SetScrollFromPosY(target_y, center_y_ratio); -} - void ImGui::ActivateItem(ImGuiID id) { ImGuiContext& g = *GImGui; @@ -7248,6 +7124,167 @@ void ImGui::Unindent(float indent_w) window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; } + +//----------------------------------------------------------------------------- +// [SECTION] SCROLLING +//----------------------------------------------------------------------------- + +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) +{ + ImGuiContext& g = *GImGui; + ImVec2 scroll = window->Scroll; + if (window->ScrollTarget.x < FLT_MAX) + { + float cr_x = window->ScrollTargetCenterRatio.x; + float target_x = window->ScrollTarget.x; + if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x) + target_x = 0.0f; + else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x) + target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f; + scroll.x = target_x - cr_x * window->InnerRect.GetWidth(); + } + if (window->ScrollTarget.y < FLT_MAX) + { + // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. + float cr_y = window->ScrollTargetCenterRatio.y; + float target_y = window->ScrollTarget.y; + if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) + target_y = 0.0f; + if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y) + target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f; + scroll.y = target_y - cr_y * window->InnerRect.GetHeight(); + } + scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); + if (!window->Collapsed && !window->SkipItems) + { + scroll.x = ImMin(scroll.x, window->ScrollMax.x); + scroll.y = ImMin(scroll.y, window->ScrollMax.y); + } + return scroll; +} + +// Scroll to keep newly navigated item fully into view +void ImGui::ScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) +{ + ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); + //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] + if (window_rect.Contains(item_rect)) + return; + + ImGuiContext& g = *GImGui; + if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) + { + window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x; + window->ScrollTargetCenterRatio.x = 0.0f; + } + else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) + { + window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x; + window->ScrollTargetCenterRatio.x = 1.0f; + } + if (item_rect.Min.y < window_rect.Min.y) + { + window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y; + window->ScrollTargetCenterRatio.y = 0.0f; + } + else if (item_rect.Max.y >= window_rect.Max.y) + { + window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y; + window->ScrollTargetCenterRatio.y = 1.0f; + } +} + +float ImGui::GetScrollX() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Scroll.x; +} + +float ImGui::GetScrollY() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ScrollMax.x; +} + +float ImGui::GetScrollMaxY() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->ScrollMax.y; +} + +void ImGui::SetScrollX(float scroll_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.y = scroll_y; + window->ScrollTargetCenterRatio.y = 0.0f; +} + +void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x) +{ + window->ScrollTarget.x = new_scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) +{ + window->ScrollTarget.y = new_scroll_y; + window->ScrollTargetCenterRatio.y = 0.0f; +} + +void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); + window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); + window->ScrollTargetCenterRatio.x = center_x_ratio; +} + +void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); + window->ScrollTargetCenterRatio.y = center_y_ratio; +} + +// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. +void ImGui::SetScrollHereX(float center_x_ratio) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space + float last_item_width = window->DC.LastItemRect.GetWidth(); + target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. + SetScrollFromPosX(target_x, center_x_ratio); +} + +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHereY(float center_y_ratio) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space + target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. + SetScrollFromPosY(target_y, center_y_ratio); +} + //----------------------------------------------------------------------------- // [SECTION] TOOLTIPS //----------------------------------------------------------------------------- @@ -8138,37 +8175,6 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput return delta; } -// Scroll to keep newly navigated item fully into view -void ImGui::NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) -{ - ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); - //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] - if (window_rect.Contains(item_rect)) - return; - - ImGuiContext& g = *GImGui; - if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) - { - window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x; - window->ScrollTargetCenterRatio.x = 0.0f; - } - else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) - { - window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x; - window->ScrollTargetCenterRatio.x = 1.0f; - } - if (item_rect.Min.y < window_rect.Min.y) - { - window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y; - window->ScrollTargetCenterRatio.y = 0.0f; - } - else if (item_rect.Max.y >= window_rect.Max.y) - { - window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y; - window->ScrollTargetCenterRatio.y = 1.0f; - } -} - static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; @@ -8478,7 +8484,7 @@ static void ImGui::NavUpdateMoveResult() if (g.NavLayer == 0) { ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); - NavScrollToBringItemIntoView(result->Window, rect_abs); + ScrollToBringItemIntoView(result->Window, rect_abs); // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate() ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false); @@ -8487,7 +8493,7 @@ static void ImGui::NavUpdateMoveResult() // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy). if (result->Window->Flags & ImGuiWindowFlags_ChildWindow) - NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); + ScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); } ClearActiveID(); diff --git a/imgui_internal.h b/imgui_internal.h index 1cc8e990..8c0d7410 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1470,8 +1470,6 @@ namespace ImGui IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window); IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent); IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); - IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x); - IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y); IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); @@ -1498,6 +1496,11 @@ namespace ImGui IMGUI_API ImGuiWindowSettings* FindOrCreateWindowSettings(const char* name); IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); + // Scrolling + IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x); + IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y); + IMGUI_API void ScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect); + // Basic Accessors inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } @@ -1549,7 +1552,6 @@ namespace ImGui IMGUI_API void NavMoveRequestCancel(); IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags); IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); - IMGUI_API void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect); IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode); IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f); IMGUI_API int CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate); From 4cfaf7d89c16c8c2fd58110633a0315efb1a17f1 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 31 Jul 2019 10:26:10 -0700 Subject: [PATCH 524/566] Scrolling, Nav: Fixed programmatic scroll leading to a slightly incorrect scroll offset when the window has decorations or a menu-bar (broken in 1.71). This was mostly noticeable when a keyboard/gamepad movement led to scrolling the view, or using e.g. SetScrollHereY() function. Fix/amend a0994d74. --- docs/CHANGELOG.txt | 6 +++++ imgui.cpp | 56 +++++++++++++++++++++++----------------------- imgui_demo.cpp | 19 +++++++++++++--- imgui_internal.h | 4 +++- 4 files changed, 53 insertions(+), 32 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c5652c96..78d67db3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -33,6 +33,12 @@ HOW TO UPDATE? VERSION 1.73 (In Progress) ----------------------------------------------------------------------- +Other Changes: + +- Scrolling, Nav: Fixed programmatic scroll leading to a slightly incorrect scroll offset when + the window has decorations or a menu-bar (broken in 1.71). This was mostly noticeable when + a keyboard/gamepad movement led to scrolling the view, or using e.g. SetScrollHereY() function. + ----------------------------------------------------------------------- VERSION 1.72 (Released 2019-07-27) diff --git a/imgui.cpp b/imgui.cpp index 316a71ee..71c76095 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5692,7 +5692,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Inner rectangle // Not affected by window border size. Used by: // - InnerClipRect - // - NavScrollToBringItemIntoView() + // - ScrollToBringRectIntoView() // - NavUpdatePageUpPageDown() // - Scrollbar() window->InnerRect.Min.x = window->Pos.x; @@ -7141,18 +7141,19 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s target_x = 0.0f; else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x) target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f; - scroll.x = target_x - cr_x * window->InnerRect.GetWidth(); + scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x); } if (window->ScrollTarget.y < FLT_MAX) { // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. + float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); float cr_y = window->ScrollTargetCenterRatio.y; float target_y = window->ScrollTarget.y; if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) target_y = 0.0f; if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y) target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f; - scroll.y = target_y - cr_y * window->InnerRect.GetHeight(); + scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height); } scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) @@ -7164,7 +7165,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s } // Scroll to keep newly navigated item fully into view -void ImGui::ScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) +void ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect) { ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] @@ -7173,25 +7174,13 @@ void ImGui::ScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_re ImGuiContext& g = *GImGui; if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) - { - window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x; - window->ScrollTargetCenterRatio.x = 0.0f; - } + SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f); else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) - { - window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x; - window->ScrollTargetCenterRatio.x = 1.0f; - } + SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f); if (item_rect.Min.y < window_rect.Min.y) - { - window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y; - window->ScrollTargetCenterRatio.y = 0.0f; - } + SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f); else if (item_rect.Max.y >= window_rect.Max.y) - { - window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y; - window->ScrollTargetCenterRatio.y = 1.0f; - } + SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f); } float ImGui::GetScrollX() @@ -7244,26 +7233,37 @@ void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) window->ScrollTargetCenterRatio.y = 0.0f; } -void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) + +void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); window->ScrollTargetCenterRatio.x = center_x_ratio; } -void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) +void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); + local_y -= decoration_up_height; window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); window->ScrollTargetCenterRatio.y = center_y_ratio; } +void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) +{ + ImGuiContext& g = *GImGui; + SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio); +} + +void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) +{ + ImGuiContext& g = *GImGui; + SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio); +} + // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. void ImGui::SetScrollHereX(float center_x_ratio) { @@ -8484,7 +8484,7 @@ static void ImGui::NavUpdateMoveResult() if (g.NavLayer == 0) { ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); - ScrollToBringItemIntoView(result->Window, rect_abs); + ScrollToBringRectIntoView(result->Window, rect_abs); // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate() ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false); @@ -8493,7 +8493,7 @@ static void ImGui::NavUpdateMoveResult() // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy). if (result->Window->Flags & ImGuiWindowFlags_ChildWindow) - ScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); + ScrollToBringRectIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); } ClearActiveID(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7fb29ec7..5a4259fd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2066,8 +2066,14 @@ static void ShowDemoWindowLayout() static int track_item = 50; static bool enable_track = true; + static bool enable_extra_decorations = false; static float scroll_to_off_px = 0.0f; static float scroll_to_pos_px = 200.0f; + + ImGui::Checkbox("Decoration", &enable_extra_decorations); + ImGui::SameLine(); + HelpMarker("We expose this for testing because scrolling sometimes had issues with window decoration such as menu-bars."); + ImGui::Checkbox("Track", &enable_track); ImGui::PushItemWidth(100); ImGui::SameLine(140); enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d"); @@ -2076,7 +2082,7 @@ static void ShowDemoWindowLayout() ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, 9999, "+%.0f px"); bool scroll_to_pos = ImGui::Button("Scroll To Pos"); - ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, 0, 9999, "X/Y = %.0f px"); + ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, 9999, "X/Y = %.0f px"); ImGui::PopItemWidth(); if (scroll_to_off || scroll_to_pos) @@ -2094,7 +2100,13 @@ static void ShowDemoWindowLayout() const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" }; ImGui::TextUnformatted(names[i]); - ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, ImGuiWindowFlags_None); + ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, child_flags); + if (ImGui::BeginMenuBar()) + { + ImGui::TextUnformatted("abc"); + ImGui::EndMenuBar(); + } if (scroll_to_off) ImGui::SetScrollY(scroll_to_off_px); if (scroll_to_pos) @@ -2126,7 +2138,8 @@ static void ShowDemoWindowLayout() for (int i = 0; i < 5; i++) { float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f; - ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(-100, child_height), true, ImGuiWindowFlags_HorizontalScrollbar); + ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0); + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(-100, child_height), true, child_flags); if (scroll_to_off) ImGui::SetScrollX(scroll_to_off_px); if (scroll_to_pos) diff --git a/imgui_internal.h b/imgui_internal.h index 8c0d7410..6a672edc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1499,7 +1499,9 @@ namespace ImGui // Scrolling IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x); IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y); - IMGUI_API void ScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect); + IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio = 0.5f); + IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio = 0.5f); + IMGUI_API void ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect); // Basic Accessors inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } From 27079e68c2c045a53991c6546b4693f275229d17 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 31 Jul 2019 10:36:40 -0700 Subject: [PATCH 525/566] Nav: Made hovering non-MenuItem Selectable not re-assign the source item for keyboard navigation. --- docs/CHANGELOG.txt | 6 +++++- imgui_internal.h | 3 ++- imgui_widgets.cpp | 11 ++++++++--- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 78d67db3..3c5904b5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,9 +35,13 @@ HOW TO UPDATE? Other Changes: -- Scrolling, Nav: Fixed programmatic scroll leading to a slightly incorrect scroll offset when +- Nav, Scrolling: Fixed programmatic scroll leading to a slightly incorrect scroll offset when the window has decorations or a menu-bar (broken in 1.71). This was mostly noticeable when a keyboard/gamepad movement led to scrolling the view, or using e.g. SetScrollHereY() function. +- Nav: Made hovering non-MenuItem Selectable not re-assign the source item for keyboard navigation. +- Nav: Fixed an issue with NavFlattened window flag (beta) where widgets not entirely fitting + in child window (often selectables because of their protruding sides) would be not considered + as entry points to to navigate toward the child window. (#787) ----------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index 6a672edc..23bf45f3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -362,7 +362,8 @@ enum ImGuiSelectableFlagsPrivate_ ImGuiSelectableFlags_PressedOnRelease = 1 << 22, ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 23, // FIXME: We may be able to remove this (added in 6251d379 for menus) ImGuiSelectableFlags_AllowItemOverlap = 1 << 24, - ImGuiSelectableFlags_DrawHoveredWhenHeld= 1 << 25 // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. + ImGuiSelectableFlags_DrawHoveredWhenHeld= 1 << 25, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. + ImGuiSelectableFlags_SetNavIdOnHover = 1 << 26 }; // Extend ImGuiTreeNodeFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 07e8d2e3..84f2ea47 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5472,13 +5472,16 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const bool was_selected = selected; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); - // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets) - if (pressed || hovered) + + // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard + if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover))) + { if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent) { g.NavDisableHighlight = true; SetNavID(id, window->DC.NavLayerCurrent); } + } if (pressed) MarkItemEdited(id); @@ -6178,7 +6181,9 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, boo ImVec2 pos = window->DC.CursorPos; ImVec2 label_size = CalcTextSize(label, NULL, true); - ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | (enabled ? 0 : ImGuiSelectableFlags_Disabled); + // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73), + // but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only. + ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | ImGuiSelectableFlags_SetNavIdOnHover | (enabled ? 0 : ImGuiSelectableFlags_Disabled); bool pressed; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { From 6a0d0dab5a9f0b9518a2bc9bb456a69895ae0962 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 31 Jul 2019 10:42:32 -0700 Subject: [PATCH 526/566] Version 1.72b (patch for nav) --- docs/CHANGELOG.txt | 2 +- examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3c5904b5..52fbafb6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -30,7 +30,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.73 (In Progress) + VERSION 1.72b (Released 2019-07-31) ----------------------------------------------------------------------- Other Changes: diff --git a/examples/README.txt b/examples/README.txt index 7e46c843..d7245f18 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.73 WIP + dear imgui, v1.72b ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 71c76095..6e6da3b1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.73 WIP +// dear imgui, v1.72b // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index ed7712f1..b7d25947 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.73 WIP +// dear imgui, v1.72b // (headers) // See imgui.cpp file for documentation. @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.73 WIP" -#define IMGUI_VERSION_NUM 17201 +#define IMGUI_VERSION "1.72b" +#define IMGUI_VERSION_NUM 17202 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5a4259fd..89e0f302 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.73 WIP +// dear imgui, v1.72b // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3e5ca061..45f997b1 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.73 WIP +// dear imgui, v1.72b // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 23bf45f3..77328281 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.73 WIP +// dear imgui, v1.72b // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 84f2ea47..ba58bce0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.73 WIP +// dear imgui, v1.72b // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index b8790af6..92be3238 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.73 WIP +dear imgui, v1.72b (Font Readme) --------------------------------------- From 9bd7846f0782deaeee6c0817d1f9cea102558061 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 31 Jul 2019 18:37:55 -0700 Subject: [PATCH 527/566] Internal: Made ScrollToBringRectIntoView() handle recursing back to scroll parent window, so the function can be called elsewhere (instead of 1 deep recursion done in NavUpdateMoveResult(). --- imgui.cpp | 48 +++++++++++++++++++++++++++--------------------- imgui_internal.h | 2 +- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6e6da3b1..4f55e4a9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7165,22 +7165,33 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s } // Scroll to keep newly navigated item fully into view -void ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect) +ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect) { + ImGuiContext& g = *GImGui; ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] - if (window_rect.Contains(item_rect)) - return; - ImGuiContext& g = *GImGui; - if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) - SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f); - else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) - SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f); - if (item_rect.Min.y < window_rect.Min.y) - SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f); - else if (item_rect.Max.y >= window_rect.Max.y) - SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f); + ImVec2 delta_scroll; + if (!window_rect.Contains(item_rect)) + { + if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) + SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f); + else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) + SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f); + if (item_rect.Min.y < window_rect.Min.y) + SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f); + else if (item_rect.Max.y >= window_rect.Max.y) + SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f); + + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false); + delta_scroll = next_scroll - window->Scroll; + } + + // Also scroll parent window to keep us into view if necessary + if (window->Flags & ImGuiWindowFlags_ChildWindow) + delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll)); + + return delta_scroll; } float ImGui::GetScrollX() @@ -8484,16 +8495,11 @@ static void ImGui::NavUpdateMoveResult() if (g.NavLayer == 0) { ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); - ScrollToBringRectIntoView(result->Window, rect_abs); - - // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate() - ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false); - ImVec2 delta_scroll = result->Window->Scroll - next_scroll; - result->RectRel.Translate(delta_scroll); + ImVec2 delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs); - // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy). - if (result->Window->Flags & ImGuiWindowFlags_ChildWindow) - ScrollToBringRectIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); + // Offset our result position so mouse position can be applied immediately after in NavUpdate() + result->RectRel.TranslateX(-delta_scroll.x); + result->RectRel.TranslateY(-delta_scroll.y); } ClearActiveID(); diff --git a/imgui_internal.h b/imgui_internal.h index 77328281..4a038d12 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1502,7 +1502,7 @@ namespace ImGui IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y); IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio = 0.5f); IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio = 0.5f); - IMGUI_API void ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect); + IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect); // Basic Accessors inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } From 967073ba3d2deaf7ef67a01a3bf9f252a491fcac Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 31 Jul 2019 20:08:06 -0700 Subject: [PATCH 528/566] Viewport: Handle case where host window gets moved and resized simultaneous (toggling maximized state). There's no perfect solution there, than using io.ConfigViewportsNoAutoMerge = false. (#1542) --- imgui.cpp | 52 ++++++++++++++++++++++++++++++++---------------- imgui_internal.h | 6 ++++-- 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0a7e60b3..efba7301 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3472,7 +3472,7 @@ void ImGui::UpdateMouseMovingWindowNewFrame() { // Try to merge the window back into the main viewport. // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports) - if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport); // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button. @@ -3821,10 +3821,10 @@ void ImGui::NewFrame() NewFrameSanityChecks(); // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. - const ImGuiColumnsFlags prev_config_flags = g.ConfigFlagsForFrame; - if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (prev_config_flags & ImGuiConfigFlags_DockingEnable) == 0) + g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame; + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0) IM_ASSERT(0 && "Please DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); - if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (prev_config_flags & ImGuiConfigFlags_ViewportsEnable) == 0) + if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0) IM_ASSERT(0 && "Please ViewportEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); // Perform simple checks: multi-viewport and platform windows support @@ -3863,6 +3863,7 @@ void ImGui::NewFrame() IM_ASSERT(mon.DpiScale != 0.0f); } } + g.ConfigFlagsCurrFrame = g.IO.ConfigFlags; // Load settings on first frame (if not explicitly loaded manually before) if (!g.SettingsLoaded) @@ -3892,7 +3893,6 @@ void ImGui::NewFrame() g.FrameCount += 1; g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; - g.ConfigFlagsForFrame = g.IO.ConfigFlags; UpdateViewportsNewFrame(); @@ -10317,7 +10317,7 @@ static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own. ImGuiContext& g = *GImGui; if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge)) - if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) if (!window->DockIsActive) if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0) return true; @@ -10362,6 +10362,26 @@ static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window) return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); } +// Translate imgui windows when a Host Viewport has been moved +// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) +void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows)); + + // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently + // translate imgui windows from OS-window-local to absolute coordinates or vice-versa. + // 2) If it's not going to fit into the new size, keep it at same absolute position. + // One problem with this is that most Win32 applications doesn't update their render while dragging, + // and so the window will appear to teleport when releasing the mouse. + const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable); + ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size); + ImVec2 delta_pos = new_pos - old_pos; + for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT + if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect()))) + TranslateWindow(g.Windows[window_n], delta_pos); +} + // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) { @@ -10403,7 +10423,7 @@ static void ImGui::UpdateViewportsNewFrame() IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) - if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + if ((g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) { for (int n = 0; n < g.Viewports.Size; n++) { @@ -10426,7 +10446,7 @@ static void ImGui::UpdateViewportsNewFrame() IM_ASSERT(main_viewport->Window == NULL); ImVec2 main_viewport_platform_pos = ImVec2(0.0f, 0.0f); ImVec2 main_viewport_platform_size = g.IO.DisplaySize; - if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) + if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) main_viewport_platform_pos = (main_viewport->Flags & ImGuiViewportFlags_Minimized) ? main_viewport->Pos : g.PlatformIO.Platform_GetWindowPos(main_viewport); AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_platform_pos, main_viewport_platform_size, ImGuiViewportFlags_CanHostOtherWindows); @@ -10461,7 +10481,7 @@ static void ImGui::UpdateViewportsNewFrame() } const bool platform_funcs_available = viewport->PlatformWindowCreated; - if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + if ((g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) { // Update Position and Size (from Platform Window to ImGui) if requested. // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. @@ -10482,11 +10502,9 @@ static void ImGui::UpdateViewportsNewFrame() // Translate imgui windows when a Host Viewport has been moved // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) - ImVec2 viewport_delta = viewport->Pos - viewport->LastPos; - if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta.x != 0.0f || viewport_delta.y != 0.0f)) - for (int window_n = 0; window_n < g.Windows.Size; window_n++) - if (g.Windows[window_n]->Viewport == viewport || (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) == 0) - TranslateWindow(g.Windows[window_n], viewport_delta); + const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos; + if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f)) + TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos); // Update DPI scale float new_dpi_scale; @@ -10513,7 +10531,7 @@ static void ImGui::UpdateViewportsNewFrame() viewport->DpiScale = new_dpi_scale; } - if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) { g.MouseViewport = main_viewport; return; @@ -10657,7 +10675,7 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) // Restore main viewport if multi-viewport is not supported by the back-end ImGuiViewportP* main_viewport = g.Viewports[0]; - if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) { SetWindowViewport(window, main_viewport); return; @@ -10783,7 +10801,7 @@ void ImGui::UpdatePlatformWindows() IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?"); IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount); g.FrameCountPlatformEnded = g.FrameCount; - if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)) + if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) return; // Create/resize/destroy platform windows to match each active viewport. diff --git a/imgui_internal.h b/imgui_internal.h index d370fe0d..a13e3633 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -997,7 +997,8 @@ struct ImGuiContext ImGuiIO IO; ImGuiPlatformIO PlatformIO; ImGuiStyle Style; - ImGuiConfigFlags ConfigFlagsForFrame; // = g.IO.ConfigFlags at the time of NewFrame() + ImGuiConfigFlags ConfigFlagsCurrFrame; // = g.IO.ConfigFlags at the time of NewFrame() + ImGuiConfigFlags ConfigFlagsLastFrame; ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. @@ -1209,7 +1210,7 @@ struct ImGuiContext { Initialized = false; FrameScopeActive = FrameScopePushedFallbackWindow = false; - ConfigFlagsForFrame = ImGuiConfigFlags_None; + ConfigFlagsCurrFrame = ImGuiConfigFlags_None; Font = NULL; FontSize = FontBaseSize = 0.0f; FontAtlasOwnedByContext = shared_font_atlas ? false : true; @@ -1683,6 +1684,7 @@ namespace ImGui IMGUI_API void UpdateMouseMovingWindowEndFrame(); // Viewports + IMGUI_API void TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos); IMGUI_API void ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale); IMGUI_API void DestroyPlatformWindow(ImGuiViewportP* viewport); IMGUI_API void ShowViewportThumbnails(); From f624455d7bb59ff5d2056c822e645073c323c6d8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 1 Aug 2019 10:57:13 -0700 Subject: [PATCH 529/566] Version 1.73 WIP --- docs/CHANGELOG.txt | 6 ++++++ examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- misc/fonts/README.txt | 2 +- 9 files changed, 16 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 52fbafb6..43ec4234 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -29,6 +29,12 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.73 WIP (In Progress) +----------------------------------------------------------------------- + +Other Changes: + ----------------------------------------------------------------------- VERSION 1.72b (Released 2019-07-31) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index d7245f18..7e46c843 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.72b + dear imgui, v1.73 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 4f55e4a9..fc1a46bd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72b +// dear imgui, v1.73 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. diff --git a/imgui.h b/imgui.h index b7d25947..f5810519 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.72b +// dear imgui, v1.73 WIP // (headers) // See imgui.cpp file for documentation. @@ -46,8 +46,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.72b" -#define IMGUI_VERSION_NUM 17202 +#define IMGUI_VERSION "1.73 WIP" +#define IMGUI_VERSION_NUM 17203 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 89e0f302..5a4259fd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72b +// dear imgui, v1.73 WIP // (demo code) // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 45f997b1..3e5ca061 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72b +// dear imgui, v1.73 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 4a038d12..cac70f04 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.72b +// dear imgui, v1.73 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ba58bce0..84f2ea47 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.72b +// dear imgui, v1.73 WIP // (widgets code) /* diff --git a/misc/fonts/README.txt b/misc/fonts/README.txt index 92be3238..b8790af6 100644 --- a/misc/fonts/README.txt +++ b/misc/fonts/README.txt @@ -1,4 +1,4 @@ -dear imgui, v1.72b +dear imgui, v1.73 WIP (Font Readme) --------------------------------------- From 6cf4743f1755408fd094a75cf1d7a6e5a2ae803e Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 1 Aug 2019 10:58:41 -0700 Subject: [PATCH 530/566] Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). --- docs/CHANGELOG.txt | 3 +++ examples/imgui_impl_dx11.cpp | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 43ec4234..7c251b31 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -34,6 +34,9 @@ HOW TO UPDATE? ----------------------------------------------------------------------- Other Changes: +- Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, + would generally make the debug layer complain (Added in 1.72). + ----------------------------------------------------------------------- VERSION 1.72b (Released 2019-07-31) diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 89b88dea..197bbe02 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -11,6 +11,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled). // 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore. // 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. @@ -208,7 +209,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); ctx->PSGetShaderResources(0, 1, &old.PSShaderResource); ctx->PSGetSamplers(0, 1, &old.PSSampler); - old.PSInstancesCount = old.VSInstancesCount = 256; + old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256; ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount); ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount); ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); From 62143dff64c8cfb960248b84cf6c4566ffc5a743 Mon Sep 17 00:00:00 2001 From: Vilya Harvey Date: Wed, 31 Jul 2019 19:50:50 +0100 Subject: [PATCH 531/566] Backends: Vulkan: Added support for specifying multisample count. (#2705, #2706) --- docs/CHANGELOG.txt | 3 +++ examples/imgui_impl_vulkan.cpp | 6 +++++- examples/imgui_impl_vulkan.h | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7c251b31..acc7bef6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,9 @@ HOW TO UPDATE? Other Changes: - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). +- Backends: Vulkan: Added support for specifying multisample count. + Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values + to use, default is non-multisampled as before. (#2705, #2706) [@vilya] ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index b55cb190..9d977f00 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2019-08-01: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. // 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). @@ -721,7 +722,10 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() VkPipelineMultisampleStateCreateInfo ms_info = {}; ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + if (v->MSAASamples != 0) + ms_info.rasterizationSamples = v->MSAASamples; + else + ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState color_attachment[1] = {}; color_attachment[0].blendEnable = VK_TRUE; diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 80356b96..f2bf9293 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -37,6 +37,7 @@ struct ImGui_ImplVulkan_InitInfo VkDescriptorPool DescriptorPool; uint32_t MinImageCount; // >= 2 uint32_t ImageCount; // >= MinImageCount + VkSampleCountFlagBits MSAASamples; // >= VK_SAMPLE_COUNT_1_BIT const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); }; From 3aa9aae0be474dfd77281a2aca1f3a69542b9b44 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 1 Aug 2019 15:50:05 -0700 Subject: [PATCH 532/566] Docking: Fix a crash that could occur with a malformed ini file (DockNode Parent value pointing to a missing node) --- imgui.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index efba7301..eaecd43b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11426,13 +11426,14 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) } // Count reference to dock ids from window settings + // We guard against the possibility of an invalid .ini file (RootID may point to a missing node) for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++) if (ImGuiID dock_id = g.SettingsWindows[settings_n].DockId) if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id)) { - ImGuiDockContextPruneNodeData* data_root = (data->RootID == dock_id) ? data : pool.GetByKey(data->RootID); data->CountWindows++; - data_root->CountChildWindows++; + if (ImGuiDockContextPruneNodeData* data_root = (data->RootID == dock_id) ? data : pool.GetByKey(data->RootID)) + data_root->CountChildWindows++; } // Prune From 451c756b016ba331106ec2a4d30fc48bf7c34f6e Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 1 Aug 2019 16:23:54 -0700 Subject: [PATCH 533/566] Docking: Modals don't need to set ImGuiViewportFlags_NoFocusOnClick. This also mitigate the common described by #2445, which becomes particularly bad with unfocused modal. (#1542) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index eaecd43b..cd077313 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6131,7 +6131,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere. - if (is_short_lived_floating_window) + if (is_short_lived_floating_window && (flags & ImGuiWindowFlags_Modal) == 0) viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick; // We can overwrite viewport flags using ImGuiWindowClass (advanced users) From 2e756d5b477486ff93c08d302d5bd39f5d0d6d87 Mon Sep 17 00:00:00 2001 From: Matthias Moulin Date: Mon, 12 Aug 2019 22:31:49 +0200 Subject: [PATCH 534/566] Explicit narrowing cast from size_t to UINT (#2726) Clang: `non-constant-expression cannot be narrowed from type 'size_t' (aka 'unsigned long long') to 'UINT' (aka 'unsigned int') in initializer list [-Wc++11-narrowing]` --- examples/imgui_impl_dx12.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index b40e9282..3161d183 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -502,9 +502,9 @@ bool ImGui_ImplDX12_CreateDeviceObjects() // Create the input layout static D3D12_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; psoDesc.InputLayout = { local_layout, 3 }; } From 7d2cfa6ff11a40a44fd1dc504ae7403937f16535 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 15 Aug 2019 14:49:18 +0200 Subject: [PATCH 535/566] Create FUNDING.yml --- .github/FUNDING.yml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..96b413db --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms +#github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: imgui From 88bf056a9ffb0f92452174acf709345fcec35c54 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 15 Aug 2019 14:51:38 +0200 Subject: [PATCH 536/566] Removing Funding file (unnecessary as we'll switch services) --- .github/FUNDING.yml | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index 96b413db..00000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,3 +0,0 @@ -# These are supported funding model platforms -#github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] -patreon: imgui From 9fce2789183d223440592b2ab8c66d495d5e9b80 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 15 Aug 2019 19:03:07 +0200 Subject: [PATCH 537/566] ColorPicker: Made rendering aware of global style alpha of the picker can be faded out. (#2711) Note that some elements won't accurately fade down with the same intensity, and the color wheel when enabled will have small overlap glitches with (style.Alpha < 1.0). --- docs/CHANGELOG.txt | 7 +++-- imgui.cpp | 2 +- imgui_widgets.cpp | 65 +++++++++++++++++++++++++--------------------- 3 files changed, 42 insertions(+), 32 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index acc7bef6..2daadc5e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -34,10 +34,13 @@ HOW TO UPDATE? ----------------------------------------------------------------------- Other Changes: +- ColorPicker: Made rendering aware of global style alpha of the picker can be faded out. (#2711) + Note that some elements won't accurately fade down with the same intensity, and the color wheel + when enabled will have small overlap glitches with (style.Alpha < 1.0). - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). -- Backends: Vulkan: Added support for specifying multisample count. - Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values +- Backends: Vulkan: Added support for specifying multisample count. + Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. (#2705, #2706) [@vilya] diff --git a/imgui.cpp b/imgui.cpp index fc1a46bd..809df9bb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4439,7 +4439,7 @@ bool ImGui::IsMouseDoubleClicked(int button) return g.IO.MouseDoubleClicked[button]; } -// [Internal] This doesn't test if the button is presed +// [Internal] This doesn't test if the button is pressed bool ImGui::IsMouseDragPastThreshold(int button, float lock_threshold) { ImGuiContext& g = *GImGui; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 84f2ea47..212d6a3e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4402,17 +4402,19 @@ void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU } // Helper for ColorPicker4() -static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w) +static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float 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_BLACK); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE); - 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_BLACK); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE); + 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)); } // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. // (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.) // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) +// FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0) bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) { ImGuiContext& g = *GImGui; @@ -4662,17 +4664,22 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl } } - ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); + const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha); + const ImU32 col_black = IM_COL32(0,0,0,style_alpha8); + const ImU32 col_white = IM_COL32(255,255,255,style_alpha8); + const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8); + const ImU32 col_hues[6 + 1] = { IM_COL32(255,0,0,style_alpha8), IM_COL32(255,255,0,style_alpha8), IM_COL32(0,255,0,style_alpha8), IM_COL32(0,255,255,style_alpha8), IM_COL32(0,0,255,style_alpha8), IM_COL32(255,0,255,style_alpha8), IM_COL32(255,0,0,style_alpha8) }; + + ImVec4 hue_color_f(1, 1, 1, style.Alpha); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f); - ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, 1.0f)); + ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!! - const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) }; ImVec2 sv_cursor_pos; if (flags & ImGuiColorEditFlags_PickerHueWheel) { // Render Hue Wheel - const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out). + const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out). const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12); for (int n = 0; n < 6; n++) { @@ -4680,13 +4687,13 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps; const int vert_start_idx = draw_list->VtxBuffer.Size; draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc); - draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness); + draw_list->PathStroke(col_white, false, wheel_thickness); const int vert_end_idx = draw_list->VtxBuffer.Size; // Paint colors over existing vertices ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner); ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner); - ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]); + ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n+1]); } // Render Cursor + preview on Hue Wheel @@ -4696,8 +4703,8 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f; int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32); draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments); - draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments); - draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, col_midgrey, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments); // Render SV triangle (rotated according to hue) ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle); @@ -4707,46 +4714,46 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl draw_list->PrimReserve(6, 6); draw_list->PrimVtx(tra, uv_white, hue_color32); draw_list->PrimVtx(trb, uv_white, hue_color32); - draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE); - draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS); - draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK); - draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS); - draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f); + draw_list->PrimVtx(trc, uv_white, col_white); + draw_list->PrimVtx(tra, uv_white, 0); + draw_list->PrimVtx(trb, uv_white, col_white); + draw_list->PrimVtx(trc, uv_white, 0); + draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f); sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V)); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { // Render SV Square - draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE); - draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK); - RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f); + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white); + draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black); + RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f); sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2); // Render Hue Bar for (int i = 0; i < 6; ++i) - draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]); + draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), col_hues[i], col_hues[i], col_hues[i + 1], col_hues[i + 1]); float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f); RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f); - RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha); } // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f; - draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12); - draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12); - draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12); + draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, 12); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, col_midgrey, 12); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, 12); // Render alpha bar if (alpha_bar) { float alpha = ImSaturate(col[3]); ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size); - RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f)); - draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK); + RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f)); + draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, user_col32_striped_of_alpha, user_col32_striped_of_alpha, user_col32_striped_of_alpha & ~IM_COL32_A_MASK, user_col32_striped_of_alpha & ~IM_COL32_A_MASK); float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f); RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f); - RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); + RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha); } EndGroup(); From 5d87ee8d82cbf0c24ab766edca3f424288a2857a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 16 Aug 2019 15:29:58 +0200 Subject: [PATCH 538/566] Internals: Added function index for Viewport and Docking. Renamed a few functions. --- imgui.cpp | 138 +++++++++++++++++++++++++++++++++++++++++++---- imgui_internal.h | 5 +- 2 files changed, 132 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cd077313..a87899b5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10262,6 +10262,29 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl //----------------------------------------------------------------------------- // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- +// - GetMainViewport() +// - FindViewportByID() +// - FindViewportByPlatformHandle() +// - SetCurrentViewport() [Internal] +// - SetWindowViewport() [Internal] +// - GetWindowAlwaysWantOwnViewport() [Internal] +// - UpdateTryMergeWindowIntoHostViewport() [Internal] +// - UpdateTryMergeWindowIntoHostViewports() [Internal] +// - TranslateWindowsInViewport() [Internal] +// - ScaleWindowsInViewport() [Internal] +// - FindHoveredViewportFromPlatformWindowStack() [Internal] +// - UpdateViewportsNewFrame() [Internal] +// - UpdateViewportsEndFrame() [Internal] +// - AddUpdateViewport() [Internal] +// - UpdateSelectWindowViewport() [Internal] +// - UpdatePlatformWindows() +// - RenderPlatformWindowsDefault() +// - FindPlatformMonitorForPos() [Internal] +// - FindPlatformMonitorForRect() [Internal] +// - UpdateViewportPlatformMonitor() [Internal] +// - DestroyPlatformWindow() [Internal] +// - DestroyPlatformWindows() +//----------------------------------------------------------------------------- ImGuiViewport* ImGui::GetMainViewport() { @@ -10401,7 +10424,7 @@ void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) // If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves. // A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. // B) It requires Platform_GetWindowFocus to be implemented by back-end. -static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 mouse_platform_pos) +static ImGuiViewportP* FindHoveredViewportFromPlatformWindowStack(const ImVec2 mouse_platform_pos) { ImGuiContext& g = *GImGui; ImGuiViewportP* best_candidate = NULL; @@ -10416,7 +10439,7 @@ static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 m } // Update viewports and monitor infos -// Note that this is runing even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. +// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. static void ImGui::UpdateViewportsNewFrame() { ImGuiContext& g = *GImGui; @@ -10547,7 +10570,7 @@ static void ImGui::UpdateViewportsNewFrame() { // Back-end failed at honoring its contract if it returned a viewport with the _NoInputs flag. IM_ASSERT(0); - viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos); + viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); } } else @@ -10555,7 +10578,7 @@ static void ImGui::UpdateViewportsNewFrame() // If the back-end doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search: // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. // B) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO) - viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos); + viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); } if (viewport_hovered != NULL) g.MouseLastHoveredViewport = viewport_hovered; @@ -11043,15 +11066,21 @@ void ImGui::DestroyPlatformWindows() // Docking: ImGuiDockContext Docking/Undocking functions // Docking: ImGuiDockNode // Docking: ImGuiDockNode Tree manipulation functions -// Docking: Public Functions (SetWindowDock, DockSpace) +// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) // Docking: Builder Functions -// Docking: Begin/End Functions (called from Begin/End) +// Docking: Begin/End Support Functions (called from Begin/End) // Docking: Settings //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Docking: Internal Types //----------------------------------------------------------------------------- +// - ImGuiDockRequestType +// - ImGuiDockRequest +// - ImGuiDockPreviewData +// - ImGuiDockNodeSettings +// - ImGuiDockContext +//----------------------------------------------------------------------------- static float IMGUI_DOCK_SPLITTER_SIZE = 2.0f; @@ -11198,6 +11227,22 @@ namespace ImGui // we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). // This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. //----------------------------------------------------------------------------- +// - DockContextInitialize() +// - DockContextShutdown() +// - DockContextOnLoadSettings() +// - DockContextClearNodes() +// - DockContextRebuildNodes() +// - DockContextUpdateUndocking() +// - DockContextUpdateDocking() +// - DockContextFindNodeByID() +// - DockContextGenNodeID() +// - DockContextAddNode() +// - DockContextRemoveNode() +// - ImGuiDockContextPruneNodeData +// - DockContextPruneUnusedSettingsNodes() +// - DockContextBuildNodesFromSettings() +// - DockContextBuildAddWindowsToNodes() +//----------------------------------------------------------------------------- void ImGui::DockContextInitialize(ImGuiContext* ctx) { @@ -11242,7 +11287,7 @@ void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear } // This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch -void ImGui::DockContextRebuild(ImGuiContext* ctx) +void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) { IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); ImGuiDockContext* dc = ctx->DockContext; @@ -11282,7 +11327,7 @@ void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx) #endif if (dc->WantFullRebuild) { - DockContextRebuild(ctx); + DockContextRebuildNodes(ctx); dc->WantFullRebuild = false; } @@ -11510,6 +11555,15 @@ void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id //----------------------------------------------------------------------------- // Docking: ImGuiDockContext Docking/Undocking functions //----------------------------------------------------------------------------- +// - DockContextQueueDock() +// - DockContextQueueUndockWindow() +// - DockContextQueueUndockNode() +// - DockContextQueueNotifyRemovedNode() +// - DockContextProcessDock() +// - DockContextProcessUndockWindow() +// - DockContextProcessUndockNode() +// - DockContextCalcDropPosForDocking() +//----------------------------------------------------------------------------- void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer) { @@ -11753,6 +11807,31 @@ bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* //----------------------------------------------------------------------------- // Docking: ImGuiDockNode //----------------------------------------------------------------------------- +// - DockNodeGetTabOrder() +// - DockNodeAddWindow() +// - DockNodeRemoveWindow() +// - DockNodeMoveChildNodes() +// - DockNodeMoveWindows() +// - DockNodeApplyPosSizeToWindows() +// - DockNodeHideHostWindow() +// - ImGuiDockNodeFindInfoResults +// - DockNodeFindInfo() +// - DockNodeUpdateVisibleFlagAndInactiveChilds() +// - DockNodeUpdateVisibleFlag() +// - DockNodeStartMouseMovingWindow() +// - DockNodeUpdate() +// - DockNodeUpdateWindowMenu() +// - DockNodeUpdateTabBar() +// - DockNodeAddTabBar() +// - DockNodeRemoveTabBar() +// - DockNodeIsDropAllowedOne() +// - DockNodeIsDropAllowed() +// - DockNodeCalcTabBarLayout() +// - DockNodeCalcSplitRects() +// - DockNodeCalcDropRectsAndTestMousePos() +// - DockNodePreviewDockCalc() +// - DockNodePreviewDockRender() +//----------------------------------------------------------------------------- ImGuiDockNode::ImGuiDockNode(ImGuiID id) { @@ -13017,6 +13096,14 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock //----------------------------------------------------------------------------- // Docking: ImGuiDockNode Tree manipulation functions //----------------------------------------------------------------------------- +// - DockNodeTreeSplit() +// - DockNodeTreeMerge() +// - DockNodeTreeUpdatePosSize() +// - DockNodeTreeUpdateSplitterFindTouchingNode() +// - DockNodeTreeUpdateSplitter() +// - DockNodeTreeFindFallbackLeafNode() +// - DockNodeTreeFindNodeByPos() +//----------------------------------------------------------------------------- void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node) { @@ -13352,6 +13439,10 @@ ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos) //----------------------------------------------------------------------------- // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) //----------------------------------------------------------------------------- +// - SetWindowDock() [Internal] +// - DockSpace() +// - DockSpaceOverViewport() +//----------------------------------------------------------------------------- // [Internal] Called via SetNextWindowDockID() void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond) @@ -13511,8 +13602,24 @@ ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags // Docking: Builder Functions //----------------------------------------------------------------------------- // Very early end-user API to manipulate dock nodes. +// Only available in imgui_internal.h. Expect this API to change/break! // It is expected that those functions are all called _before_ the dockspace node submission. //----------------------------------------------------------------------------- +// - DockBuilderDockWindow() +// - DockBuilderGetNode() +// - DockBuilderSetNodePos() +// - DockBuilderSetNodeSize() +// - DockBuilderAddNode() +// - DockBuilderRemoveNode() +// - DockBuilderRemoveNodeChildNodes() +// - DockBuilderRemoveNodeDockedWindows() +// - DockBuilderSplitNode() +// - DockBuilderCopyNodeRec() +// - DockBuilderCopyNode() +// - DockBuilderCopyWindowSettings() +// - DockBuilderCopyDockSpace() +// - DockBuilderFinish() +//----------------------------------------------------------------------------- void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id) { @@ -13888,7 +13995,12 @@ void ImGui::DockBuilderFinish(ImGuiID root_id) } //----------------------------------------------------------------------------- -// Docking: Begin/End Functions (called from Begin/End) +// Docking: Begin/End Support Functions (called from Begin/End) +//----------------------------------------------------------------------------- +// - GetWindowAlwaysWantOwnTabBar() +// - BeginDocked() +// - BeginAsDockableDragDropSource() +// - BeginAsDockableDragDropTarget() //----------------------------------------------------------------------------- bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window) @@ -14139,6 +14251,14 @@ void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window) //----------------------------------------------------------------------------- // Docking: Settings //----------------------------------------------------------------------------- +// - DockSettingsRenameNodeReferences() +// - DockSettingsRemoveNodeReferences() +// - DockSettingsFindNodeSettings() +// - DockSettingsHandler_ReadOpen() +// - DockSettingsHandler_ReadLine() +// - DockSettingsHandler_DockNodeToSettings() +// - DockSettingsHandler_WriteAll() +//----------------------------------------------------------------------------- static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id) { diff --git a/imgui_internal.h b/imgui_internal.h index a13e3633..0f6366aa 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1774,7 +1774,7 @@ namespace ImGui IMGUI_API void DockContextInitialize(ImGuiContext* ctx); IMGUI_API void DockContextShutdown(ImGuiContext* ctx); IMGUI_API void DockContextOnLoadSettings(ImGuiContext* ctx); - IMGUI_API void DockContextRebuild(ImGuiContext* ctx); + IMGUI_API void DockContextRebuildNodes(ImGuiContext* ctx); IMGUI_API void DockContextUpdateUndocking(ImGuiContext* ctx); IMGUI_API void DockContextUpdateDocking(ImGuiContext* ctx); IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); @@ -1789,8 +1789,9 @@ namespace ImGui IMGUI_API void SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond); // Docking - Builder function needs to be generally called before the DockSpace() node is submitted. + // Important: do not hold on ImGuiDockNode* pointers. They may be invalidated by any split/merge/remove operation and every frame. IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id); - IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id); // Warning: DO NOT HOLD ON ImGuiDockNode* pointer, will be invalided by any split/merge/remove operation. + IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id); inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; } IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags = 0); // Use (flags == ImGuiDockNodeFlags_DockSpace) to create a dockspace, otherwise it'll create a floating node. IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows From 76ccbb899dfa744208d3f808ab77824e89f23f5a Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 19 Aug 2019 11:21:33 +0200 Subject: [PATCH 539/566] Viewport: Fix modal/popup window being stuck in unowned hidden viewport associated to fallback window without stealing it back. (#1542) Viewport: Fix modal reference viewport when opened outside of another window. + Comments --- imgui.cpp | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a87899b5..67f5376f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4519,9 +4519,9 @@ void ImGui::Render() if (g.FrameCountEnded != g.FrameCount) EndFrame(); g.FrameCountRendered = g.FrameCount; - - // Gather ImDrawList to render (for each active window) g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0; + + // Add background ImDrawList (for each active viewport) for (int n = 0; n != g.Viewports.Size; n++) { ImGuiViewportP* viewport = g.Viewports[n]; @@ -4530,9 +4530,10 @@ void ImGui::Render() AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport)); } + // Add ImDrawList to render (for each active window) ImGuiWindow* windows_to_render_top_most[2]; windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; - windows_to_render_top_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL; + windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingList : NULL); for (int n = 0; n != g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; @@ -4553,8 +4554,11 @@ void ImGui::Render() { ImGuiViewportP* viewport = g.Viewports[n]; viewport->DrawDataBuilder.FlattenIntoSingleLayer(); + + // Add foreground ImDrawList (for each active viewport) if (viewport->DrawLists[1] != NULL) AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport)); + SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]); g.IO.MetricsRenderVertices += viewport->DrawData->TotalVtxCount; g.IO.MetricsRenderIndices += viewport->DrawData->TotalIdxCount; @@ -8298,7 +8302,10 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla // Center modal windows by default // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) - SetNextWindowPos(window->Viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + { + ImGuiViewportP* viewport = window->WasActive ? window->Viewport : (ImGuiViewportP*)GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport? + SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + } flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking; const bool is_open = Begin(name, p_open, flags); @@ -10342,8 +10349,9 @@ static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge)) if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) if (!window->DockIsActive) - if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0) - return true; + if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0) + if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0) + return true; return false; } @@ -10715,7 +10723,7 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0) { // By default inherit from parent window - if (window->Viewport == NULL && window->ParentWindow) + if (window->Viewport == NULL && window->ParentWindow && !window->ParentWindow->FallbackWindow) window->Viewport = window->ParentWindow->Viewport; // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file From 7abd41bd5fa75df0c013a71c6d8bb91c855e05cc Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 19 Aug 2019 20:38:17 +0200 Subject: [PATCH 540/566] TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2daadc5e..8b4659e2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,7 @@ Other Changes: - ColorPicker: Made rendering aware of global style alpha of the picker can be faded out. (#2711) Note that some elements won't accurately fade down with the same intensity, and the color wheel when enabled will have small overlap glitches with (style.Alpha < 1.0). +- TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). - Backends: Vulkan: Added support for specifying multisample count. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 212d6a3e..3e4f08a9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6638,7 +6638,7 @@ static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f); float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; - if (tab_bar->ScrollingTarget > tab_x1) + if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= tab_bar->BarRect.GetWidth())) { tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f); tab_bar->ScrollingTarget = tab_x1; From a33cedda142f6e96a9bd2d665290830362671566 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 19 Aug 2019 21:48:03 +0200 Subject: [PATCH 541/566] Internals: Renaming window size calc functions. --- imgui.cpp | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 809df9bb..36121398 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4857,7 +4857,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl return window; } -static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) +static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) { ImGuiContext& g = *GImGui; if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) @@ -4889,7 +4889,7 @@ static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) return new_size; } -static ImVec2 CalcContentSize(ImGuiWindow* window) +static ImVec2 CalcWindowContentSize(ImGuiWindow* window) { if (window->Collapsed) if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) @@ -4903,7 +4903,7 @@ static ImVec2 CalcContentSize(ImGuiWindow* window) return sz; } -static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) +static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; @@ -4927,7 +4927,7 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) // When the window cannot fit all contents (either because of constraints, either because screen is too small), // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. - ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit); + ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit); bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar); bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar); if (will_have_scrollbar_x) @@ -4940,8 +4940,10 @@ static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) { - ImVec2 size_contents = CalcContentSize(window); - return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents)); + ImVec2 size_contents = CalcWindowContentSize(window); + ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents); + ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit); + return size_final; } static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags) @@ -4958,7 +4960,7 @@ static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& co ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right ImVec2 size_expected = pos_max - pos_min; - ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected); + ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected); *out_pos = pos_min; if (corner_norm.x == 0.0f) out_pos->x -= (size_constrained.x - size_expected.x); @@ -5039,7 +5041,7 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0) { // Manual auto-fit when double-clicking - size_target = CalcSizeAfterConstraint(window, size_auto_fit); + size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit); ret_auto_fit = true; ClearActiveID(); } @@ -5094,7 +5096,7 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck. - size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta); + size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta); } } @@ -5481,7 +5483,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS // Update contents size from last frame for auto-fitting (or use explicit size) - window->ContentSize = CalcContentSize(window); + window->ContentSize = CalcWindowContentSize(window); if (window->HiddenFramesCanSkipItems > 0) window->HiddenFramesCanSkipItems--; if (window->HiddenFramesCannotSkipItems > 0) @@ -5545,7 +5547,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // SIZE // Calculate auto-fit size, handle automatic resize - const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->ContentSize); + const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize); bool use_current_size_for_scrollbar_x = window_just_created; bool use_current_size_for_scrollbar_y = window_just_created; if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) @@ -5581,7 +5583,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) } // Apply minimum/maximum window size constraints and final size - window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull); + window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull); window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; // Decoration size From 72090b646f00b53bb9e0adc0bff7b8d37388d1bf Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 22 Aug 2019 11:34:17 +0200 Subject: [PATCH 542/566] Fixed incorrect assignment of IsFallbackWindow which would tag dock node host windows created in NewFrame() as such, messing with popup viewport inheritance. --- imgui.cpp | 12 ++++++------ imgui_internal.h | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a2ba3d8d..e02578b8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2733,7 +2733,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) SkipItems = false; Appearing = false; Hidden = false; - FallbackWindow = false; + IsFallbackWindow = false; HasCloseButton = false; ResizeBorderHeld = -1; BeginCount = 0; @@ -4062,10 +4062,10 @@ void ImGui::NewFrame() // Create implicit/fallback window - which we will only render it if the user has added something to it. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. // This fallback is particularly important as it avoid ImGui:: calls from crashing. + g.FrameScopePushedFallbackWindow = true; SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); - IM_ASSERT(g.CurrentWindow->FallbackWindow == true); - g.FrameScopePushedFallbackWindow = true; + IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiTestEngineHook_PostNewFrame(&g); @@ -5796,7 +5796,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const int current_frame = g.FrameCount; const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); - window->FallbackWindow = (g.CurrentWindowStack.Size == 0); + window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.FrameScopePushedFallbackWindow); // Update the Appearing flag bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on @@ -10731,7 +10731,7 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0) { // By default inherit from parent window - if (window->Viewport == NULL && window->ParentWindow && !window->ParentWindow->FallbackWindow) + if (window->Viewport == NULL && window->ParentWindow && !window->ParentWindow->IsFallbackWindow) window->Viewport = window->ParentWindow->Viewport; // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file @@ -14024,7 +14024,7 @@ bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window) ImGuiContext& g = *GImGui; if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar) if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0) - if (!window->FallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise + if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise return true; return false; } diff --git a/imgui_internal.h b/imgui_internal.h index 91bab1da..ea1709ff 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1465,7 +1465,7 @@ struct IMGUI_API ImGuiWindow bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) bool Appearing; // Set during the frame where the window is appearing (or re-appearing) bool Hidden; // Do not display (== (HiddenFrames*** > 0)) - bool FallbackWindow; + bool IsFallbackWindow; bool HasCloseButton; // Set when the window has a close button (p_open != NULL) signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) From a856c670c17fe70d61e519bf74ccb2559915a2ff Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 21 Aug 2019 23:05:46 +0200 Subject: [PATCH 543/566] TabBar: fixed single-tab not shrinking their width down. + minor typo fixes (#2738) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_opengl2.cpp | 2 +- imgui.cpp | 2 +- imgui_widgets.cpp | 8 ++++++-- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8b4659e2..63033042 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,6 +38,7 @@ Other Changes: Note that some elements won't accurately fade down with the same intensity, and the color wheel when enabled will have small overlap glitches with (style.Alpha < 1.0). - TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. +- TabBar: fixed single-tab not shrinking their width down. - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). - Backends: Vulkan: Added support for specifying multisample count. diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index 95720ff3..fbe278c7 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -24,7 +24,7 @@ // 2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications. // 2018-06-08: Misc: Extracted imgui_impl_opengl2.cpp/.h away from the old combined GLFW/SDL+OpenGL2 examples. // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. -// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplGlfwGL2_RenderDrawData() in the .h file so you can call it yourself. +// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplOpenGL2_RenderDrawData() in the .h file so you can call it yourself. // 2017-09-01: OpenGL: Save and restore current polygon mode. // 2016-09-10: OpenGL: Uploading font texture as RGBA32 to increase compatibility with users shaders (not ideal). // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. diff --git a/imgui.cpp b/imgui.cpp index 36121398..374efe2a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -638,7 +638,7 @@ CODE - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: - OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp) + OpenGL: ImTextureID = GLuint (see ImGui_ImplOpenGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp) DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp) DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp) DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3e4f08a9..89e6ca0b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1361,8 +1361,12 @@ static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) // Shrink excess width from a set of item, by removing width from the larger items first. void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess) { - if (count > 1) - ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); + if (count == 1) + { + items[0].Width -= width_excess; + return; + } + ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); int count_same_width = 1; while (width_excess > 0.0f && count_same_width < count) { From c4b0bf718ad69a1c24da6ad5f95e58458d1ff28d Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 22 Aug 2019 11:40:37 +0200 Subject: [PATCH 544/566] More typos in comments (#2738) --- imgui.cpp | 2 +- imgui_demo.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 374efe2a..6be7fdc9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -638,7 +638,7 @@ CODE - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: - OpenGL: ImTextureID = GLuint (see ImGui_ImplOpenGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp) + OpenGL: ImTextureID = GLuint (see ImGui_ImplOpenGL3_RenderDrawData() function in imgui_impl_opengl3.cpp) DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp) DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp) DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5a4259fd..0264debc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -759,7 +759,7 @@ static void ShowDemoWindowWidgets() // Here we are grabbing the font texture because that's the only one we have access to inside the demo code. // Remember that ImTextureID is just storage for whatever you want it to be, it is essentially a value that will be passed to the render function inside the ImDrawCmd structure. // If you use one of the default imgui_impl_XXXX.cpp renderer, they all have comments at the top of their file to specify what they expect to be stored in ImTextureID. - // (for example, the imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. The imgui_impl_glfw_gl3.cpp renderer expect a GLuint OpenGL texture identifier etc.) + // (for example, the imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer. The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier etc.) // If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers to ImGui::Image(), and gather width/height through your own functions, etc. // Using ShowMetricsWindow() as a "debugger" to inspect the draw data that are being passed to your render will help you debug issues if you are confused about this. // Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). From d8f9f6ba2abb6cfc00f704b887264ac9472cf9f7 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 22 Aug 2019 13:50:55 +0200 Subject: [PATCH 545/566] Viewport: Fixed issue where resize grip would display hovered (before of extruded hit rectangle) while mouse is still off the OS bounds so click would miss it and focus the OS window behind expected one. (#1542) --- imgui.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e02578b8..3c6c5a66 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5398,6 +5398,15 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au ImVec2 pos_target(FLT_MAX, FLT_MAX); ImVec2 size_target(FLT_MAX, FLT_MAX); + // Clip mouse interaction rectangles within the viewport (in practice the narrowing is going to happen most of the time). + // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits. + // This is however not the case with current back-ends under Win32, but a custom borderless window implementation would benefit from it. + // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. + // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). + ImRect clip_viewport_rect(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX); + if (!(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) + clip_viewport_rect = window->Viewport->GetRect(); + // Resize grips and borders are on layer 1 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); @@ -5413,6 +5422,7 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size); if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x); if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y); + resize_rect.ClipWith(clip_viewport_rect); bool hovered, held; ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); @@ -5440,8 +5450,9 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au { bool hovered, held; ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); + border_rect.ClipWith(clip_viewport_rect); ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren); - //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); + //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held) { g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; @@ -5461,6 +5472,10 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au } PopID(); + // Resize nav layer + window->DC.NavLayerCurrent = ImGuiNavLayer_Main; + window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); + // Navigation resize (keyboard/gamepad) if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window) { @@ -5493,10 +5508,6 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au MarkIniSettingsDirty(window); } - // Resize nav layer - window->DC.NavLayerCurrent = ImGuiNavLayer_Main; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); - window->Size = window->SizeFull; return ret_auto_fit; } From 27431dcc6b8101ddcdbcdb3777765cb9e8f50013 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 20 Aug 2019 19:24:23 +0200 Subject: [PATCH 546/566] Docking: fix BeginDocked() path that creates node so that SetNextWindowDockID() doesn't immediately discard the node..(#2109) Amend 515ecbddc270f3129642e9f1ab8d95e3778a0b95, not sure at this point if the (auto_dock_node) flag was needed at all. Comments. Exposed DockContextGenNodeID() in imgui_internal.h --- imgui.cpp | 18 ++++++++++-------- imgui_internal.h | 3 ++- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3c6c5a66..09688b12 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3823,9 +3823,9 @@ void ImGui::NewFrame() // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame; if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0) - IM_ASSERT(0 && "Please DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0) - IM_ASSERT(0 && "Please ViewportEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); + IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); // Perform simple checks: multi-viewport and platform windows support if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) @@ -11190,7 +11190,6 @@ namespace ImGui { // ImGuiDockContext static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id); - static ImGuiID DockContextGenNodeID(ImGuiContext* ctx); static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node); static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node); static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req); @@ -11396,7 +11395,7 @@ static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID return (ImGuiDockNode*)ctx->DockContext->Nodes.GetVoidPtr(id); } -static ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx) +ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx) { // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) // FIXME-OPT FIXME-DOCKING: This is suboptimal, even if the node count is small enough not to be a worry. We should poke in ctx->Nodes to find a suitable ID faster. @@ -11413,6 +11412,8 @@ static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id) id = DockContextGenNodeID(ctx); else IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL); + + // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id); ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id); ctx->DockContext->Nodes.SetVoidPtr(node->ID, node); @@ -11917,8 +11918,8 @@ static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, b window->DockIsActive = (node->Windows.Size > 1); window->DockTabWantClose = false; - // If 2+ windows appeared on the same frame, creating a new DockNode+TabBar from the second window, - // then we need to hide the first one after the fact otherwise it would be visible as a standalone window for one frame. + // If more than 2 windows appeared on the same frame, we'll create a new hosting DockNode from the point of the second window submission. + // Then we need to hide the first window (after its been output) otherwise it would be visible as a standalone window for one frame. if (node->HostWindow == NULL && node->Windows.Size == 2 && node->Windows[0]->WasActive == false) { node->Windows[0]->Hidden = true; @@ -12464,6 +12465,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindow != host_window)) BeginAsDockableDragDropTarget(host_window); + // We update this after DockNodeUpdateTabBar() node->LastFrameActive = g.FrameCount; // Recurse into children @@ -14087,8 +14089,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) { node = DockContextAddNode(ctx, window->DockId); node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; - if (auto_dock_node) - node->LastFrameAlive = g.FrameCount; + node->LastFrameAlive = g.FrameCount; } // If the node just turned visible, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, @@ -14913,6 +14914,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node); ImGui::BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); + NodeWindow(node->HostWindow, "HostWindow"); NodeWindow(node->VisibleWindow, "VisibleWindow"); ImGui::BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabID, node->LastFocusedNodeID); ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : ""); diff --git a/imgui_internal.h b/imgui_internal.h index ea1709ff..effdda28 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1606,7 +1606,7 @@ struct ImGuiTabBar { ImVector Tabs; ImGuiID ID; // Zero for tab-bars used by docking - ImGuiID SelectedTabId; // Selected tab + ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview) int CurrFrameVisible; @@ -1777,6 +1777,7 @@ namespace ImGui IMGUI_API void DockContextRebuildNodes(ImGuiContext* ctx); IMGUI_API void DockContextUpdateUndocking(ImGuiContext* ctx); IMGUI_API void DockContextUpdateDocking(ImGuiContext* ctx); + IMGUI_API ImGuiID DockContextGenNodeID(ImGuiContext* ctx); IMGUI_API void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer); IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); From 10a202422a8e03d2871946c5d4131e145f987f30 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 20 Aug 2019 19:24:37 +0200 Subject: [PATCH 547/566] Docking: Extracted some of BeginDocked() into a DockContextBindNodeToWindow() function. Moved one of the undocking blurb to favor fast path. (Commit intended to have no functional side effects) --- imgui.cpp | 107 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 62 insertions(+), 45 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 09688b12..eb4682e0 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11197,6 +11197,7 @@ namespace ImGui static void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx); static ImGuiDockNode* DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id); + static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window); static void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_refs); // Use root_id==0 to clear all static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count); static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all @@ -11208,6 +11209,7 @@ namespace ImGui static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node); static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id); static void DockNodeHideHostWindow(ImGuiDockNode* node); + static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id); static void DockNodeUpdate(ImGuiDockNode* node); static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node); static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window); @@ -11261,6 +11263,7 @@ namespace ImGui // - DockContextUpdateUndocking() // - DockContextUpdateDocking() // - DockContextFindNodeByID() +// - DockContextBindNodeToWindow() // - DockContextGenNodeID() // - DockContextAddNode() // - DockContextRemoveNode() @@ -11800,7 +11803,7 @@ void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) } else { - // Otherwise delete the previous node by merging the other sibling back into the parent node. + // Otherwise extract our node and merging our sibling back into the parent node. IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1; node->ParentNode->ChildNodes[index_in_parent] = NULL; @@ -12295,6 +12298,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); + // Bind or create host window ImGuiWindow* host_window = NULL; bool beginned_into_host_window = false; if (node->IsDockSpace()) @@ -14042,6 +14046,51 @@ bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window) return false; } +static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window) +{ + ImGuiContext& g = *ctx; + ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId); + IM_ASSERT(window->DockNode == NULL); + + // We should not be docking into a split node (SetWindowDock should avoid this) + if (node && node->IsSplitNode()) + { + DockContextProcessUndockWindow(ctx, window); + return NULL; + } + + // Create node + if (node == NULL) + { + node = DockContextAddNode(ctx, window->DockId); + node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; + node->LastFrameAlive = g.FrameCount; + } + + // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, + // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). + // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. + // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. + if (!node->IsVisible) + { + ImGuiDockNode* ancestor_node = node; + while (!ancestor_node->IsVisible) + { + ancestor_node->IsVisible = true; + ancestor_node->MarkedForPosSizeWrite = true; + if (ancestor_node->ParentNode) + ancestor_node = ancestor_node->ParentNode; + } + IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f); + DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, true); + } + + // Add window to node + DockNodeAddWindow(node, window, true); + IM_ASSERT(node == window->DockNode); + return node; +} + void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) { ImGuiContext* ctx = GImGui; @@ -14075,44 +14124,9 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) IM_ASSERT(window->DockId == node->ID); if (window->DockId != 0 && node == NULL) { - node = DockContextFindNodeByID(ctx, window->DockId); - - // We should not be docking into a split node (SetWindowDock should avoid this) - if (node && node->IsSplitNode()) - { - DockContextProcessUndockWindow(ctx, window); - return; - } - - // Create node + node = DockContextBindNodeToWindow(ctx, window); if (node == NULL) - { - node = DockContextAddNode(ctx, window->DockId); - node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; - node->LastFrameAlive = g.FrameCount; - } - - // If the node just turned visible, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, - // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). - // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. - // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. - if (!node->IsVisible) - { - ImGuiDockNode* ancestor_node = node; - while (!ancestor_node->IsVisible) - { - ancestor_node->IsVisible = true; - ancestor_node->MarkedForPosSizeWrite = true; - if (ancestor_node->ParentNode) - ancestor_node = ancestor_node->ParentNode; - } - IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f); - DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, true); - } - - // Add window to node - DockNodeAddWindow(node, window, true); - IM_ASSERT(node == window->DockNode); + return; } #if 0 @@ -14142,23 +14156,26 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) return; } - // Undock if we are submitted earlier than the host window - if (node->HostWindow && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext) - { - DockContextProcessUndockWindow(ctx, window); - return; - } - + // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, + // and never create neither a host window neither a tab bar. // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test) if (node->HostWindow == NULL) { window->DockTabIsVisible = false; return; } + IM_ASSERT(node->HostWindow); IM_ASSERT(node->IsLeafNode()); IM_ASSERT(node->Size.x > 0.0f && node->Size.y > 0.0f); + // Undock if we are submitted earlier than the host window + if (window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext) + { + DockContextProcessUndockWindow(ctx, window); + return; + } + // Position window SetNextWindowPos(node->Pos); SetNextWindowSize(node->Size); From 3fb5cf3541c745b1a655f78ae593e665d4c4b6eb Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 22 Aug 2019 16:55:42 +0200 Subject: [PATCH 548/566] Using offsetof() when available in C++11. Avoids Clang sanitizer complaining about old-style macros. (#94) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 2 +- imgui.h | 6 +++++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 63033042..e5dfa657 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,7 @@ Other Changes: when enabled will have small overlap glitches with (style.Alpha < 1.0). - TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. - TabBar: fixed single-tab not shrinking their width down. +- Using offsetof() when available in C++11. Avoids Clang sanitizer complaining about old-style macros. (#94) - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). - Backends: Vulkan: Added support for specifying multisample count. diff --git a/imgui.cpp b/imgui.cpp index 6be7fdc9..b4b4bc34 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -176,7 +176,7 @@ CODE - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" - phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render(). + phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render(). - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code. - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder. diff --git a/imgui.h b/imgui.h index f5810519..abb42a78 100644 --- a/imgui.h +++ b/imgui.h @@ -73,8 +73,12 @@ Index of this file: #define IM_FMTLIST(FMT) #endif #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) // Size of a static C-style array. Don't use on pointers! -#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++. #define IM_UNUSED(_VAR) ((void)_VAR) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#if (__cplusplus >= 201100) +#define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11 +#else +#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Old style macro. +#endif // Warnings #if defined(__clang__) From c4ff1b3578ea0bcac93a25b16d5e3e4cb32f0a9a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 22 Aug 2019 17:43:57 +0200 Subject: [PATCH 549/566] ImDrawList: clarified the name of many parameters so reading the code is a little easier. (#2740) --- docs/CHANGELOG.txt | 1 + imgui.h | 36 ++++++++------- imgui_demo.cpp | 4 +- imgui_draw.cpp | 108 +++++++++++++++++++++++---------------------- 4 files changed, 79 insertions(+), 70 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e5dfa657..ede7464d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,7 @@ Other Changes: when enabled will have small overlap glitches with (style.Alpha < 1.0). - TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. - TabBar: fixed single-tab not shrinking their width down. +- ImDrawList: clarified the name of many parameters so reading the code is a little easier. (#2740) - Using offsetof() when available in C++11. Avoids Clang sanitizer complaining about old-style macros. (#94) - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). diff --git a/imgui.h b/imgui.h index abb42a78..63a8eec8 100644 --- a/imgui.h +++ b/imgui.h @@ -1901,33 +1901,39 @@ struct ImDrawList inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } // Primitives - IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4-bits corresponding to which corner to round - IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); // a: upper-left, b: lower-right (== upper-left + size) - IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); - IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); - IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); - IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. + IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right (== upper-left + size), rounding_corners_flags: 4-bits corresponding to which corner to round + IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); // 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 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 = 12, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 12); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(const 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 AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = IM_COL32_WHITE); - IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, bool closed, float thickness); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order. IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); + // Image primitives + // - Read FAQ to understand what ImTextureID is. + // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. + // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, 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(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() 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; } // Note: Anti-aliased filling requires points to be in clockwise order. inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); _Path.Size = 0; } - IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); - IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 10); + 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 PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawCornerFlags rounding_corners = ImDrawCornerFlags_All); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0264debc..790cb63c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4391,9 +4391,9 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImVec2 window_size = ImGui::GetWindowSize(); ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); if (draw_bg) - ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 32, 10+4); + ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 48, 10+4); if (draw_fg) - ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 32, 10); + ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 48, 10); ImGui::EndTabItem(); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3e5ca061..3eb1067e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -860,26 +860,26 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun } } -void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12) +void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12) { if (radius == 0.0f || a_min_of_12 > a_max_of_12) { - _Path.push_back(centre); + _Path.push_back(center); return; } _Path.reserve(_Path.Size + (a_max_of_12 - a_min_of_12 + 1)); for (int a = a_min_of_12; a <= a_max_of_12; a++) { const ImVec2& c = _Data->CircleVtx12[a % IM_ARRAYSIZE(_Data->CircleVtx12)]; - _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); + _Path.push_back(ImVec2(center.x + c.x * radius, center.y + c.y * radius)); } } -void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments) +void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) { if (radius == 0.0f) { - _Path.push_back(centre); + _Path.push_back(center); return; } @@ -889,7 +889,7 @@ void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float a_min, floa for (int i = 0; i <= num_segments; i++) { const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min); - _Path.push_back(ImVec2(centre.x + ImCos(a) * radius, centre.y + ImSin(a) * radius)); + _Path.push_back(ImVec2(center.x + ImCos(a) * radius, center.y + ImSin(a) * radius)); } } @@ -968,44 +968,46 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } } -void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) +void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - PathLineTo(a + ImVec2(0.5f,0.5f)); - PathLineTo(b + ImVec2(0.5f,0.5f)); + PathLineTo(p1 + ImVec2(0.5f, 0.5f)); + PathLineTo(p2 + ImVec2(0.5f, 0.5f)); PathStroke(col, false, thickness); } -// a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. -void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners, float thickness) +// 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, ImDrawCornerFlags rounding_corners, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; if (Flags & ImDrawListFlags_AntiAliasedLines) - PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.50f,0.50f), rounding, rounding_corners); + PathRect(p_min + ImVec2(0.50f,0.50f), p_max - ImVec2(0.50f,0.50f), rounding, rounding_corners); else - PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.49f,0.49f), rounding, rounding_corners); // Better looking lower-right corner and rounded non-AA shapes. + PathRect(p_min + ImVec2(0.50f,0.50f), p_max - ImVec2(0.49f,0.49f), rounding, rounding_corners); // Better looking lower-right corner and rounded non-AA shapes. PathStroke(col, true, thickness); } -void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners) +void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners) { if ((col & IM_COL32_A_MASK) == 0) return; if (rounding > 0.0f) { - PathRect(a, b, rounding, rounding_corners); + PathRect(p_min, p_max, rounding, rounding_corners); PathFillConvex(col); } else { PrimReserve(6, 4); - PrimRect(a, b, col); + PrimRect(p_min, p_max, col); } } -void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +// p_min = upper-left, p_max = lower-right +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) return; @@ -1014,77 +1016,77 @@ void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 PrimReserve(6, 4); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); - PrimWriteVtx(a, uv, col_upr_left); - PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); - PrimWriteVtx(c, uv, col_bot_right); - PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); + PrimWriteVtx(p_min, uv, col_upr_left); + PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right); + PrimWriteVtx(p_max, uv, col_bot_right); + PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left); } -void ImDrawList::AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness) +void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - PathLineTo(a); - PathLineTo(b); - PathLineTo(c); - PathLineTo(d); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); PathStroke(col, true, thickness); } -void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) +void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; - PathLineTo(a); - PathLineTo(b); - PathLineTo(c); - PathLineTo(d); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); PathFillConvex(col); } -void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) +void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - PathLineTo(a); - PathLineTo(b); - PathLineTo(c); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); PathStroke(col, true, thickness); } -void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) +void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; - PathLineTo(a); - PathLineTo(b); - PathLineTo(c); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); PathFillConvex(col); } -void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) +void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) { if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) 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(centre, radius-0.5f, 0.0f, a_max, num_segments - 1); + 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); PathStroke(col, true, thickness); } -void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) +void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) { if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) 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(centre, radius, 0.0f, a_max, num_segments - 1); + 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); } @@ -1132,7 +1134,7 @@ void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, c AddText(NULL, 0.0f, pos, col, text_begin, text_end); } -void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col) +void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -1142,13 +1144,13 @@ void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const Im PushTextureID(user_texture_id); PrimReserve(6, 4); - PrimRectUV(a, b, uv_a, uv_b, col); + PrimRectUV(p_min, p_max, uv_min, uv_max, col); if (push_texture_id) PopTextureID(); } -void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col) { if ((col & IM_COL32_A_MASK) == 0) return; @@ -1158,20 +1160,20 @@ void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, cons PushTextureID(user_texture_id); PrimReserve(6, 4); - PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); + PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col); if (push_texture_id) PopTextureID(); } -void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners) +void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawCornerFlags rounding_corners) { if ((col & IM_COL32_A_MASK) == 0) return; if (rounding <= 0.0f || (rounding_corners & ImDrawCornerFlags_All) == 0) { - AddImage(user_texture_id, a, b, uv_a, uv_b, col); + AddImage(user_texture_id, p_min, p_max, uv_min, uv_max, col); return; } @@ -1180,10 +1182,10 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, c PushTextureID(user_texture_id); int vert_start_idx = VtxBuffer.Size; - PathRect(a, b, rounding, rounding_corners); + PathRect(p_min, p_max, rounding, rounding_corners); PathFillConvex(col); int vert_end_idx = VtxBuffer.Size; - ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, a, b, uv_a, uv_b, true); + ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); if (push_texture_id) PopTextureID(); From cb538fadfe3d24ec2b8c30a97103e44055db811c Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 23 Aug 2019 11:08:30 +0200 Subject: [PATCH 550/566] Internals: Storing settings using ImVec2ih to match what we are doing with dock node. + removed ImMax from reading Size value (done in Begin) + removed seemingly unnecessary FLT_MAX compare in SettingsHandlerWindow_WriteAll. About: Added backquote to text copied into clipboard so it doesn't mess up with github formatting when pasted. --- imgui.cpp | 25 +++++++++++-------------- imgui_demo.cpp | 6 ++++++ imgui_internal.h | 14 +++++++++++--- 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b4b4bc34..fbe7a29e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4827,10 +4827,10 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl // Retrieve settings from .ini file window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); - window->Pos = ImFloor(settings->Pos); + window->Pos = ImVec2(settings->Pos.x, settings->Pos.y); window->Collapsed = settings->Collapsed; - if (ImLengthSqr(settings->Size) > 0.00001f) - size = ImFloor(settings->Size); + if (settings->Size.x > 0 && settings->Size.y > 0) + size = ImVec2(settings->Size.x, settings->Size.y); } window->Size = window->SizeFull = ImFloor(size); window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values @@ -9447,14 +9447,13 @@ static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler* return (void*)settings; } -static void SettingsHandlerWindow_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void* entry, const char* line) +static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) { - ImGuiContext& g = *ctx; ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; - float x, y; + int x, y; int i; - if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); - else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); + if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) settings->Pos = ImVec2ih((short)x, (short)y); + else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) settings->Size = ImVec2ih((short)x, (short)y); else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } @@ -9476,8 +9475,8 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); } IM_ASSERT(settings->ID == window->ID); - settings->Pos = window->Pos; - settings->Size = window->SizeFull; + settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y); + settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y); settings->Collapsed = window->Collapsed; } @@ -9486,11 +9485,9 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl for (int i = 0; i != g.SettingsWindows.Size; i++) { const ImGuiWindowSettings* settings = &g.SettingsWindows[i]; - if (settings->Pos.x == FLT_MAX) - continue; buf->appendf("[%s][%s]\n", handler->TypeName, settings->Name); - buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); - buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y); + buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); buf->appendf("Collapsed=%d\n", settings->Collapsed); buf->appendf("\n"); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 790cb63c..b2b7a7e4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2961,7 +2961,10 @@ void ImGui::ShowAboutWindow(bool* p_open) bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); ImGui::BeginChildFrame(ImGui::GetID("cfginfos"), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18), ImGuiWindowFlags_NoMove); if (copy_to_clipboard) + { ImGui::LogToClipboard(); + ImGui::LogText("```\n"); // Back quotes will make the text appears without formatting when pasting to GitHub + } ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); ImGui::Separator(); @@ -3052,7 +3055,10 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::Text("style.ItemInnerSpacing: %.2f,%.2f", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y); if (copy_to_clipboard) + { + ImGui::LogText("\n```\n"); ImGui::LogFinish(); + } ImGui::EndChildFrame(); } ImGui::End(); diff --git a/imgui_internal.h b/imgui_internal.h index cac70f04..a936f69e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -528,6 +528,14 @@ struct ImVec1 ImVec1(float _x) { x = _x; } }; +// 2D vector (half-size integer) +struct ImVec2ih +{ + short x, y; + ImVec2ih() { x = y = 0; } + ImVec2ih(short _x, short _y) { x = _x; y = _y; } +}; + // 2D axis aligned bounding-box // NB: we can't rely on ImVec2 math operators being available here struct IMGUI_API ImRect @@ -655,11 +663,11 @@ struct ImGuiWindowSettings { char* Name; ImGuiID ID; - ImVec2 Pos; - ImVec2 Size; + ImVec2ih Pos; + ImVec2ih Size; bool Collapsed; - ImGuiWindowSettings() { Name = NULL; ID = 0; Pos = Size = ImVec2(0,0); Collapsed = false; } + ImGuiWindowSettings() { Name = NULL; ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = false; } }; struct ImGuiSettingsHandler From 483534b525063a242d63f4481e55c88cf0c5eba9 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 23 Aug 2019 12:31:14 +0200 Subject: [PATCH 551/566] Internals: Using simpler ImVec2ih construct + fixed misnamed member. --- imgui.cpp | 28 ++++++++++++++-------------- imgui_internal.h | 11 ++++++----- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6faec2bb..7e3977e4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5182,7 +5182,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl if (settings->ViewportId) { window->ViewportId = settings->ViewportId; - window->ViewportPos = ImVec2(settings->ViewportPosh.x, settings->ViewportPosh.y); + window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y); } else { @@ -7304,8 +7304,8 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) { IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters - window->HitTestHoleSize = ImVec2ih((short)size.x, (short)size.y); - window->HitTestHoleOffset = ImVec2ih((short)(pos.x - window->Pos.x), (short)(pos.y - window->Pos.y)); + window->HitTestHoleSize = ImVec2ih(size); + window->HitTestHoleOffset = ImVec2ih(pos - window->Pos); } void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) @@ -10217,7 +10217,7 @@ static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); } else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); } else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; } - else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2) { settings->ViewportPosh = ImVec2ih((short)x, (short)y); } + else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2) { settings->ViewportPos = ImVec2ih((short)x, (short)y); } else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; } else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; } @@ -10242,10 +10242,10 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); } IM_ASSERT(settings->ID == window->ID); - settings->Pos = ImVec2ih((short)(window->Pos.y - window->ViewportPos.y), (short)(window->Pos.y - window->ViewportPos.y)); - settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y); + settings->Pos = ImVec2ih(window->Pos - window->ViewportPos); + settings->Size = ImVec2ih(window->SizeFull); settings->ViewportId = window->ViewportId; - settings->ViewportPosh = ImVec2ih((short)window->ViewportPos.x, (short)window->ViewportPos.y); + settings->ViewportPos = ImVec2ih(window->ViewportPos); IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId); settings->DockId = window->DockId; settings->ClassId = window->WindowClass.ClassId; @@ -10261,7 +10261,7 @@ static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandl buf->appendf("[%s][%s]\n", handler->TypeName, settings->Name); if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID) { - buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPosh.x, settings->ViewportPosh.y); + buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y); buf->appendf("ViewportId=0x%08X\n", settings->ViewportId); } if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID) @@ -13929,10 +13929,10 @@ void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_ } else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name)) { - ImVec2ih window_pos_2ih = ImVec2ih((short)src_window->Pos.x, (short)src_window->Pos.y); + ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos); if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID) { - dst_settings->ViewportPosh = window_pos_2ih; + dst_settings->ViewportPos = window_pos_2ih; dst_settings->ViewportId = src_window->ViewportId; dst_settings->Pos = ImVec2ih(0, 0); } @@ -13940,7 +13940,7 @@ void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_ { dst_settings->Pos = window_pos_2ih; } - dst_settings->Size = ImVec2ih((short)src_window->SizeFull.x, (short)src_window->SizeFull.y); + dst_settings->Size = ImVec2ih(src_window->SizeFull); dst_settings->Collapsed = src_window->Collapsed; } } @@ -14412,9 +14412,9 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None; node_settings.Depth = (char)depth; node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_); - node_settings.Pos = ImVec2ih((short)node->Pos.x, (short)node->Pos.y); - node_settings.Size = ImVec2ih((short)node->Size.x, (short)node->Size.y); - node_settings.SizeRef = ImVec2ih((short)node->SizeRef.x, (short)node->SizeRef.y); + node_settings.Pos = ImVec2ih(node->Pos); + node_settings.Size = ImVec2ih(node->Size); + node_settings.SizeRef = ImVec2ih(node->SizeRef); dc->SettingsNodes.push_back(node_settings); if (node->ChildNodes[0]) DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1); diff --git a/imgui_internal.h b/imgui_internal.h index eb01cb67..aad0bb77 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -544,8 +544,9 @@ struct ImVec1 struct ImVec2ih { short x, y; - ImVec2ih() { x = y = 0; } - ImVec2ih(short _x, short _y) { x = _x; y = _y; } + ImVec2ih() { x = y = 0; } + ImVec2ih(short _x, short _y) { x = _x; y = _y; } + explicit ImVec2ih(const ImVec2& rhs) { x = (short)rhs.x; y = (short)rhs.y; } }; // 2D axis aligned bounding-box @@ -677,14 +678,14 @@ struct ImGuiWindowSettings ImGuiID ID; ImVec2ih Pos; // NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions. ImVec2ih Size; - ImVec2ih ViewportPosh; + ImVec2ih ViewportPos; ImGuiID ViewportId; ImGuiID DockId; // ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none. ImGuiID ClassId; // ID of window class if specified short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. bool Collapsed; - ImGuiWindowSettings() { Name = NULL; ID = 0; Pos = Size = ViewportPosh = ImVec2ih(0, 0); ViewportId = DockId = ClassId = 0; DockOrder = -1; Collapsed = false; } + ImGuiWindowSettings() { Name = NULL; ID = 0; Pos = Size = ViewportPos = ImVec2ih(0, 0); ViewportId = DockId = ClassId = 0; DockOrder = -1; Collapsed = false; } }; struct ImGuiSettingsHandler @@ -1210,7 +1211,7 @@ struct ImGuiContext { Initialized = false; FrameScopeActive = FrameScopePushedFallbackWindow = false; - ConfigFlagsCurrFrame = ImGuiConfigFlags_None; + ConfigFlagsCurrFrame = ConfigFlagsLastFrame = ImGuiConfigFlags_None; Font = NULL; FontSize = FontBaseSize = 0.0f; FontAtlasOwnedByContext = shared_font_atlas ? false : true; From bcdb89ab078780ac256ec6ee155af0a0c55460a7 Mon Sep 17 00:00:00 2001 From: Tommy Nguyen Date: Tue, 27 Aug 2019 22:40:34 +0200 Subject: [PATCH 552/566] Rebased imstb_rectpack on stb_rect_pack v1.00. --- docs/CHANGELOG.txt | 2 ++ imstb_rectpack.h | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ede7464d..046e59d4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,8 @@ Other Changes: - Backends: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. (#2705, #2706) [@vilya] +- Misc: Updated stb_rect_pack from 0.99 to 1.00 (fixes by @rygorous: off-by-1 bug in best-fit heuristic, + fix handling of rectangles too large to fit inside texture). (#2762) [@tido64] ----------------------------------------------------------------------- diff --git a/imstb_rectpack.h b/imstb_rectpack.h index 23f922a5..ff2a85df 100644 --- a/imstb_rectpack.h +++ b/imstb_rectpack.h @@ -1,10 +1,10 @@ -// [DEAR IMGUI] -// This is a slightly modified version of stb_rect_pack.h 0.99. +// [DEAR IMGUI] +// This is a slightly modified version of stb_rect_pack.h 1.00. // Those changes would need to be pushed into nothings/stb: // - Added STBRP__CDECL // Grep for [DEAR IMGUI] to find the changes. -// stb_rect_pack.h - v0.99 - public domain - rectangle packing +// stb_rect_pack.h - v1.00 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -37,9 +37,11 @@ // // Bugfixes / warning fixes // Jeremy Jaussaud +// Fabian Giesen // // Version history: // +// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles // 0.99 (2019-02-07) warning fixes // 0.11 (2017-03-03) return packing success/fail result // 0.10 (2016-10-25) remove cast-away-const to avoid warnings @@ -357,6 +359,13 @@ static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int widt width -= width % c->align; STBRP_ASSERT(width % c->align == 0); + // if it can't possibly fit, bail immediately + if (width > c->width || height > c->height) { + fr.prev_link = NULL; + fr.x = fr.y = 0; + return fr; + } + node = c->active_head; prev = &c->active_head; while (node->x + width <= c->width) { @@ -420,7 +429,7 @@ static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int widt } STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); - if (y + height < c->height) { + if (y + height <= c->height) { if (y <= best_y) { if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { best_x = xpos; From a01d149369ac2a91c4838509fdc08cc05ddc1d88 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 28 Aug 2019 10:52:17 +0200 Subject: [PATCH 553/566] Fixed context popup windows from not having the NoDocking flag. (#2763) --- imgui.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7e3977e4..f2f4f3fd 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8276,7 +8276,7 @@ void ImGui::CloseCurrentPopup() window->DC.NavHideHighlightOneFrame = true; } -bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) +bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; if (!IsPopupOpen(id)) @@ -8286,12 +8286,13 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) } char name[20]; - if (extra_flags & ImGuiWindowFlags_ChildMenu) + if (flags & ImGuiWindowFlags_ChildMenu) ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth else ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame - bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup); + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking; + bool is_open = Begin(name, NULL, flags); if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) EndPopup(); @@ -8306,7 +8307,7 @@ bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } - flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking; + flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags); } From c8418015c22fad3479ebd5cd91f7658d56e47ad8 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 28 Aug 2019 12:31:43 +0200 Subject: [PATCH 554/566] SliderScalar: Improved assert when using U32 or U64 types with a large v_max value. (#2765) + misc minor stuff. --- docs/CHANGELOG.txt | 1 + imgui.h | 2 +- imgui_widgets.cpp | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 046e59d4..d9a60769 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,7 @@ Other Changes: when enabled will have small overlap glitches with (style.Alpha < 1.0). - TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. - TabBar: fixed single-tab not shrinking their width down. +- SliderScalar: Improved assert when using U32 or U64 types with a large v_max value. (#2765) [@loicmouton] - ImDrawList: clarified the name of many parameters so reading the code is a little easier. (#2740) - Using offsetof() when available in C++11. Avoids Clang sanitizer complaining about old-style macros. (#94) - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, diff --git a/imgui.h b/imgui.h index 63a8eec8..6b0de93a 100644 --- a/imgui.h +++ b/imgui.h @@ -1789,7 +1789,7 @@ struct ImDrawCmd ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // The draw callback code can access this. - ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; } + ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; } }; // Vertex index diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 89e6ca0b..79f5b2d4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2464,13 +2464,13 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type IM_ASSERT(*(const ImS32*)v_min >= IM_S32_MIN/2 && *(const ImS32*)v_max <= IM_S32_MAX/2); return SliderBehaviorT(bb, id, data_type, (ImS32*)v, *(const ImS32*)v_min, *(const ImS32*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_U32: - IM_ASSERT(*(const ImU32*)v_min <= IM_U32_MAX/2); + IM_ASSERT(*(const ImU32*)v_max <= IM_U32_MAX/2); return SliderBehaviorT(bb, id, data_type, (ImU32*)v, *(const ImU32*)v_min, *(const ImU32*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_S64: IM_ASSERT(*(const ImS64*)v_min >= IM_S64_MIN/2 && *(const ImS64*)v_max <= IM_S64_MAX/2); return SliderBehaviorT(bb, id, data_type, (ImS64*)v, *(const ImS64*)v_min, *(const ImS64*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_U64: - IM_ASSERT(*(const ImU64*)v_min <= IM_U64_MAX/2); + IM_ASSERT(*(const ImU64*)v_max <= IM_U64_MAX/2); return SliderBehaviorT(bb, id, data_type, (ImU64*)v, *(const ImU64*)v_min, *(const ImU64*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_Float: IM_ASSERT(*(const float*)v_min >= -FLT_MAX/2.0f && *(const float*)v_max <= FLT_MAX/2.0f); @@ -3384,7 +3384,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ BeginGroup(); const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); From 45a0db597925777ffaa08f58089eca36382edddc Mon Sep 17 00:00:00 2001 From: Hanif Bin Ariffin Date: Mon, 26 Aug 2019 19:52:08 -0400 Subject: [PATCH 555/566] Demo: PlotLine example displays the average value. (#2759) + extra comments --- imgui_demo.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b2b7a7e4..04214437 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1043,6 +1043,8 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } + // Plot/Graph widgets are currently fairly limited. + // Consider writing your own plotting widget, or using a third-party one (see "Wiki->Useful Widgets", or github.com/ocornut/imgui/issues/2747) if (ImGui::TreeNode("Plots Widgets")) { static bool animate = true; @@ -1066,7 +1068,18 @@ static void ShowDemoWindowWidgets() phase += 0.10f*values_offset; refresh_time += 1.0f/60.0f; } - ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); + + // Plots can display overlay texts + // (in this example, we will display an average value) + { + float average = 0.0f; + for (int n = 0; n < IM_ARRAYSIZE(values); n++) + average += values[n]; + average /= (float)IM_ARRAYSIZE(values); + char overlay[32]; + sprintf(overlay, "avg %f", average); + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0,80)); + } ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); // Use functions to generate output From 62f75c7fb163a2fcd0455ae4e68ea4acf0b15d17 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 30 Jun 2019 12:48:19 +0200 Subject: [PATCH 556/566] Added a mechanism to compact/free the larger allocations of unused windows (buffers are compacted when a window is unused for 60 seconds, as per io.ConfigWindowsMemoryCompactTimer = 60.0f). Note that memory usage has never been reported as a problem, so this is merely a touch of overzealous luxury. (#2636) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 51 +++++++++++++++++++++++++++++++++++++++++++++- imgui.h | 1 + imgui_demo.cpp | 1 + imgui_internal.h | 9 +++++++- 5 files changed, 63 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d9a60769..9dee4195 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,9 @@ Other Changes: - SliderScalar: Improved assert when using U32 or U64 types with a large v_max value. (#2765) [@loicmouton] - ImDrawList: clarified the name of many parameters so reading the code is a little easier. (#2740) - Using offsetof() when available in C++11. Avoids Clang sanitizer complaining about old-style macros. (#94) +- Added a mechanism to compact/free the larger allocations of unused windows (buffers are compacted when + a window is unused for 60 seconds, as per io.ConfigWindowsMemoryCompactTimer = 60.0f). Note that memory + usage has never been reported as a problem, so this is merely a touch of overzealous luxury. (#2636) - Backends: DX11: Fixed GSGetShader() call not passing an initialized instance count, would generally make the debug layer complain (Added in 1.72). - Backends: Vulkan: Added support for specifying multisample count. diff --git a/imgui.cpp b/imgui.cpp index fbe7a29e..6a8cc176 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1244,6 +1244,7 @@ ImGuiIO::ImGuiIO() ConfigInputTextCursorBlink = true; ConfigWindowsResizeFromEdges = true; ConfigWindowsMoveFromTitleBarOnly = false; + ConfigWindowsMemoryCompactTimer = 60.0f; // Platform Functions BackendPlatformName = BackendRendererName = NULL; @@ -2699,6 +2700,7 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; + LastTimeActive = -1.0f; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; SettingsIdx = -1; @@ -2713,6 +2715,9 @@ ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) NavLastIds[0] = NavLastIds[1] = 0; NavRectRel[0] = NavRectRel[1] = ImRect(); NavLastChildNavWindow = NULL; + + MemoryCompacted = false; + MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0; } ImGuiWindow::~ImGuiWindow() @@ -2783,6 +2788,36 @@ static void SetCurrentWindow(ImGuiWindow* window) g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } +// Free up/compact internal window buffers, we can use this when a window becomes unused. +// This is currently unused by the library, but you may call this yourself for easy GC. +// Not freed: +// - ImGuiWindow, ImGuiWindowSettings, Name +// - StateStorage, ColumnsStorage (may hold useful data) +// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. +void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window) +{ + window->MemoryCompacted = true; + window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity; + window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity; + window->IDStack.clear(); + window->DrawList->ClearFreeMemory(); + window->DC.ChildWindows.clear(); + window->DC.ItemFlagsStack.clear(); + window->DC.ItemWidthStack.clear(); + window->DC.TextWrapPosStack.clear(); + window->DC.GroupStack.clear(); +} + +void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window) +{ + // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening. + // The other buffers tends to amortize much faster. + window->MemoryCompacted = false; + window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity); + window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity); + window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0; +} + void ImGui::SetNavID(ImGuiID id, int nav_layer) { ImGuiContext& g = *GImGui; @@ -3814,8 +3849,9 @@ void ImGui::NewFrame() g.NavIdTabCounter = INT_MAX; - // Mark all windows as not visible + // Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); + const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer > 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; @@ -3823,6 +3859,10 @@ void ImGui::NewFrame() window->BeginCount = 0; window->Active = false; window->WriteAccessed = false; + + // Garbage collect (this is totally functional but we may need decide if the side-effects are desirable) + if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time) + GcCompactTransientWindowBuffers(window); } // Closing the focused window restore focus to the first active root window in descending z-order @@ -5391,6 +5431,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { window->Flags = (ImGuiWindowFlags)flags; window->LastFrameActive = current_frame; + window->LastTimeActive = (float)g.Time; window->BeginOrderWithinParent = 0; window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++); } @@ -5404,6 +5445,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + // We allow window memory to be compacted so recreate the base stack when needed. + if (window->IDStack.Size == 0) + window->IDStack.push_back(window->ID); + // Add to stack // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow() g.CurrentWindowStack.push_back(window); @@ -5468,6 +5513,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->IDStack.resize(1); + // Restore buffer capacity when woken from a compacted state, to avoid + if (window->MemoryCompacted) + GcAwakeTransientWindowBuffers(window); + // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. bool window_title_visible_elsewhere = false; diff --git a/imgui.h b/imgui.h index 6b0de93a..28c7d20d 100644 --- a/imgui.h +++ b/imgui.h @@ -1360,6 +1360,7 @@ struct ImGuiIO bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) bool ConfigWindowsMoveFromTitleBarOnly; // = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected. + float ConfigWindowsMemoryCompactTimer;// = 60.0f // [BETA] Compact window memory usage when unused. Set to 0.0f to disable. //------------------------------------------------------------------ // Platform Functions diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 04214437..568da3b9 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3049,6 +3049,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly"); + if (io.ConfigWindowsMemoryCompactTimer > 0.0f) ImGui::Text("io.ConfigWindowsMemoryCompactTimer = %.1ff", io.ConfigWindowsMemoryCompactTimer); ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags); if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); diff --git a/imgui_internal.h b/imgui_internal.h index a936f69e..1018b1e9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1321,8 +1321,8 @@ struct IMGUI_API ImGuiWindow ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0,0) when positioning from top-left corner; ImVec2(0.5f,0.5f) for centering; ImVec2(1,1) for bottom right. + ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. - ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack // The best way to understand what those rectangles are is to use the 'Metrics -> Tools -> Show windows rectangles' viewer. // The main 'OuterRect', omitted as a field, is window->Rect(). @@ -1334,6 +1334,7 @@ struct IMGUI_API ImGuiWindow ImRect ContentsRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. int LastFrameActive; // Last frame number the window was Active. + float LastTimeActive; float ItemWidthDefault; ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items ImGuiStorage StateStorage; @@ -1352,6 +1353,10 @@ struct IMGUI_API ImGuiWindow ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space + bool MemoryCompacted; + int MemoryDrawListIdxCapacity; + int MemoryDrawListVtxCapacity; + public: ImGuiWindow(ImGuiContext* context, const char* name); ~ImGuiWindow(); @@ -1483,6 +1488,8 @@ namespace ImGui IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); + IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window); + IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); IMGUI_API void SetCurrentFont(ImFont* font); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } From bfcdaeb6108e5473a967532c712ed36d56d2fee9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 28 Aug 2019 20:30:36 +0200 Subject: [PATCH 557/566] Disable with ConfigWindowsMemoryCompactTimer < 0.0f (#2636) --- imgui.cpp | 2 +- imgui.h | 2 +- imgui_demo.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6a8cc176..89541b2f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3851,7 +3851,7 @@ void ImGui::NewFrame() // Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); - const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer > 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX; + const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; diff --git a/imgui.h b/imgui.h index 28c7d20d..a2701739 100644 --- a/imgui.h +++ b/imgui.h @@ -1360,7 +1360,7 @@ struct ImGuiIO bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) bool ConfigWindowsMoveFromTitleBarOnly; // = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected. - float ConfigWindowsMemoryCompactTimer;// = 60.0f // [BETA] Compact window memory usage when unused. Set to 0.0f to disable. + float ConfigWindowsMemoryCompactTimer;// = 60.0f // [BETA] Compact window memory usage when unused. Set to -1.0f to disable. //------------------------------------------------------------------ // Platform Functions diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 568da3b9..8485f7c9 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3049,7 +3049,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly"); - if (io.ConfigWindowsMemoryCompactTimer > 0.0f) ImGui::Text("io.ConfigWindowsMemoryCompactTimer = %.1ff", io.ConfigWindowsMemoryCompactTimer); + if (io.ConfigWindowsMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigWindowsMemoryCompactTimer = %.1ff", io.ConfigWindowsMemoryCompactTimer); ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags); if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); From 9e294be5c56848b9da7d55d67228edbe602affc0 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 21 Aug 2019 15:07:28 +0200 Subject: [PATCH 558/566] Docking: Fix for node created at the same time as windows that are still resizing (typically with io.ConfigDockingAlwaysTabBar) to not be zero/min sized. (#2109) The fix delay their visibility by one frame, which is not ideal but not very problematic as the .ini data gets populated after that --- imgui.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ imgui_internal.h | 9 +++++++++ 2 files changed, 50 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index f2f4f3fd..4b324a67 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11206,6 +11206,7 @@ namespace ImGui static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar); static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); + static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id); static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node); static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id); static void DockNodeHideHostWindow(ImGuiDockNode* node); @@ -11846,6 +11847,7 @@ bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* // - DockNodeHideHostWindow() // - ImGuiDockNodeFindInfoResults // - DockNodeFindInfo() +// - DockNodeFindWindowByID() // - DockNodeUpdateVisibleFlagAndInactiveChilds() // - DockNodeUpdateVisibleFlag() // - DockNodeStartMouseMovingWindow() @@ -11871,6 +11873,7 @@ ImGuiDockNode::ImGuiDockNode(ImGuiID id) TabBar = NULL; SplitAxis = ImGuiAxis_None; + State = ImGuiDockNodeState_Unknown; HostWindow = VisibleWindow = NULL; CentralNode = OnlyNodeWithWindows = NULL; LastFrameAlive = LastFrameActive = LastFrameFocused = -1; @@ -12131,6 +12134,15 @@ static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeFindInfoResults* DockNodeFindInfo(node->ChildNodes[1], results); } +static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id) +{ + IM_ASSERT(id != 0); + for (int n = 0; n < node->Windows.Size; n++) + if (node->Windows[n]->ID == id) + return node->Windows[n]; + return NULL; +} + // - Remove inactive windows/nodes. // - Update visibility flag. static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node) @@ -12169,6 +12181,7 @@ static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* nod if (node->Windows.Size == 1 && !node->IsCentralNode()) { DockNodeHideHostWindow(node); + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return return; } @@ -12285,6 +12298,7 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) } DockNodeHideHostWindow(node); + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; node->WantCloseAll = false; node->WantCloseTabID = 0; node->HasCloseButton = node->HasWindowMenuButton = node->EnableCloseButton = false; @@ -12295,6 +12309,31 @@ static void ImGui::DockNodeUpdate(ImGuiDockNode* node) return; } + // In some circumstance we will defer creating the host window (so everything will be kept hidden), + // while the expected visible window is resizing itself. + // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, + // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: + // N+0: Begin(): window created (with no known size), node is created + // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible + // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible + // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. + // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). + // In reality it isn't very important as user quickly ends up with size data in .ini file. + if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode()) + { + IM_ASSERT(node->Windows.Size > 0); + ImGuiWindow* ref_window = NULL; + if (node->SelectedTabID != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! + ref_window = DockNodeFindWindowByID(node, node->SelectedTabID); + if (ref_window == NULL) + ref_window = node->Windows[0]; + if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0) + { + node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing; + return; + } + } + const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); // Bind or create host window @@ -14161,6 +14200,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test) if (node->HostWindow == NULL) { + window->DockIsActive = (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing); window->DockTabIsVisible = false; return; } @@ -14168,6 +14208,7 @@ void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) IM_ASSERT(node->HostWindow); IM_ASSERT(node->IsLeafNode()); IM_ASSERT(node->Size.x > 0.0f && node->Size.y > 0.0f); + node->State = ImGuiDockNodeState_HostWindowVisible; // Undock if we are submitted earlier than the host window if (window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext) diff --git a/imgui_internal.h b/imgui_internal.h index aad0bb77..54c5bc51 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -929,6 +929,14 @@ enum ImGuiDataAuthority_ ImGuiDataAuthority_Window }; +enum ImGuiDockNodeState +{ + ImGuiDockNodeState_Unknown, + ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow, + ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing, + ImGuiDockNodeState_HostWindowVisible +}; + // sizeof() 116~160 struct ImGuiDockNode { @@ -945,6 +953,7 @@ struct ImGuiDockNode int SplitAxis; // [Split node only] Split axis (X or Y) ImGuiWindowClass WindowClass; + ImGuiDockNodeState State; ImGuiWindow* HostWindow; ImGuiWindow* VisibleWindow; // Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window. ImGuiDockNode* CentralNode; // [Root node only] Pointer to central node. From f8d3d8d7f5415e889315c6b7de430ead61ae7aeb Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 29 Aug 2019 12:13:29 +0200 Subject: [PATCH 559/566] TabBar: improved shrinking for large number of tabs to avoid leaving extraneous space on the right side. Individuals tabs are given integer-rounded width and remainder is spread between tabs left-to-right. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 20 +++++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9dee4195..649e75ed 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,8 @@ Other Changes: when enabled will have small overlap glitches with (style.Alpha < 1.0). - TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. - TabBar: fixed single-tab not shrinking their width down. +- TabBar: improved shrinking for large number of tabs to avoid leaving extraneous space on the right side. + Individuals tabs are given integer-rounded width and remainder is spread between tabs left-to-right. - SliderScalar: Improved assert when using U32 or U64 types with a large v_max value. (#2765) [@loicmouton] - ImDrawList: clarified the name of many parameters so reading the code is a little easier. (#2740) - Using offsetof() when available in C++11. Avoids Clang sanitizer complaining about old-style macros. (#94) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 79f5b2d4..42e13243 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1370,14 +1370,28 @@ void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_exc int count_same_width = 1; while (width_excess > 0.0f && count_same_width < count) { - while (count_same_width < count && items[0].Width == items[count_same_width].Width) + while (count_same_width < count && items[0].Width <= items[count_same_width].Width) count_same_width++; - float width_to_remove_per_item_max = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); - float width_to_remove_per_item = ImMin(width_excess / count_same_width, width_to_remove_per_item_max); + float max_width_to_remove_per_item = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); for (int item_n = 0; item_n < count_same_width; item_n++) items[item_n].Width -= width_to_remove_per_item; width_excess -= width_to_remove_per_item * count_same_width; } + + // Round width and redistribute remainder left-to-right (could make it an option of the function?) + // Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator. + width_excess = 0.0f; + for (int n = 0; n < count; n++) + { + float width_rounded = ImFloor(items[n].Width); + width_excess += items[n].Width - width_rounded; + items[n].Width = width_rounded; + } + if (width_excess > 0.0f) + for (int n = 0; n < count; n++) + if (items[n].Index < (int)(width_excess + 0.01f)) + items[n].Width += 1.0f; } //------------------------------------------------------------------------- From 09780b8b3dfca9cad9959a697a9c240f99ce1ab2 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys <19151258+rokups@users.noreply.github.com> Date: Thu, 29 Aug 2019 14:02:42 +0300 Subject: [PATCH 560/566] Viewport: Fix setting window size on macos (glfw). (#2767, #2117) MacOS positions windows by their bottom-left corner why the rest of the world (including imgui) position windows by the top-left corner. This created an issue where collapsing imgui window would cause window header to remain at the bottom the full window rect. Likewise resizing window by using sizing handle caused window to grow upwards when we tried to expand window downwards. This workaround moves window to the opposite direction by the delta of size change creating an illusion that windows are positioned by their top-left corner. --- examples/imgui_impl_glfw.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index cb5e88b9..dc2d9819 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -570,6 +570,16 @@ static ImVec2 ImGui_ImplGlfw_GetWindowSize(ImGuiViewport* viewport) static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) { ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData; +#if __APPLE__ + // Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are + // positioned from the upper-left corner. GLFW makes an effort to convert macOS style coordinates, however it + // doesn't handle it when changing size. We are manually moving the window in order for changes of size to be based + // on the upper-left corner. + int x, y, width, height; + glfwGetWindowPos(data->Window, &x, &y); + glfwGetWindowSize(data->Window, &width, &height); + glfwSetWindowPos(data->Window, x, y - height + size.y); +#endif glfwSetWindowSize(data->Window, (int)size.x, (int)size.y); } From 3f99890f40c999052e78490b26ce138f80c803b4 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 29 Aug 2019 14:46:02 +0200 Subject: [PATCH 561/566] TabBar: feed desired width (sum of unclipped tabs width) into layout system to allow for auto-resize. (#2768) Before 1.71 tab bars fed the sum of current width which created feedback loops in certain situations. Amend f95c77eeeae70383b3e278a33b511e0d63ee16ac. --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 3 ++- imgui_internal.h | 3 ++- imgui_widgets.cpp | 13 ++++++++----- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 649e75ed..d20df9d9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,8 @@ Other Changes: when enabled will have small overlap glitches with (style.Alpha < 1.0). - TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. - TabBar: fixed single-tab not shrinking their width down. +- TabBar: feed desired width (sum of unclipped tabs width) into layout system to allow for auto-resize. (#2768) + (before 1.71 tab bars fed the sum of current width which created feedback loops in certain situations). - TabBar: improved shrinking for large number of tabs to avoid leaving extraneous space on the right side. Individuals tabs are given integer-rounded width and remainder is spread between tabs left-to-right. - SliderScalar: Improved assert when using U32 or U64 types with a large v_max value. (#2765) [@loicmouton] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8485f7c9..d5bc96c5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4286,7 +4286,6 @@ static void ShowExampleAppWindowTitles(bool*) // Demonstrate using the low-level ImDrawList to draw custom shapes. static void ShowExampleAppCustomRendering(bool* p_open) { - ImGui::SetNextWindowSize(ImVec2(350, 560), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Example: Custom rendering", p_open)) { ImGui::End(); @@ -4406,7 +4405,9 @@ static void ShowExampleAppCustomRendering(bool* p_open) static bool draw_bg = true; static bool draw_fg = true; ImGui::Checkbox("Draw in Background draw list", &draw_bg); + ImGui::SameLine(); HelpMarker("The Background draw list will be rendered below every Dear ImGui windows."); ImGui::Checkbox("Draw in Foreground draw list", &draw_fg); + ImGui::SameLine(); HelpMarker("The Foreground draw list will be rendered over every Dear ImGui windows."); ImVec2 window_pos = ImGui::GetWindowPos(); ImVec2 window_size = ImGui::GetWindowSize(); ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); diff --git a/imgui_internal.h b/imgui_internal.h index 1018b1e9..e9139d60 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1435,8 +1435,9 @@ struct ImGuiTabBar int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; - float ContentsHeight; + float LastTabContentHeight; // Record the height of contents submitted below the tab bar float OffsetMax; // Distance from BarRect.Min.x, locked during layout + float OffsetMaxIdeal; // Ideal offset if all tabs were visible and not clipped float OffsetNextTab; // Distance from BarRect.Min.x, incremented with each BeginTabItem() call, not used if ImGuiTabBarFlags_Reorderable if set. float ScrollingAnim; float ScrollingTarget; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 42e13243..423a873b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6290,8 +6290,8 @@ ImGuiTabBar::ImGuiTabBar() ID = 0; SelectedTabId = NextSelectedTabId = VisibleTabId = 0; CurrFrameVisible = PrevFrameVisible = -1; - ContentsHeight = 0.0f; - OffsetMax = OffsetNextTab = 0.0f; + LastTabContentHeight = 0.0f; + OffsetMax = OffsetMaxIdeal = OffsetNextTab = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; @@ -6373,7 +6373,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->FramePadding = g.Style.FramePadding; // Layout - ItemSize(ImVec2(0.0f /*tab_bar->OffsetMax*/, tab_bar->BarRect.GetHeight())); // Don't feed width back + ItemSize(ImVec2(tab_bar->OffsetMaxIdeal, tab_bar->BarRect.GetHeight())); window->DC.CursorPos.x = tab_bar->BarRect.Min.x; // Draw separator @@ -6406,9 +6406,9 @@ 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) - tab_bar->ContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f); + tab_bar->LastTabContentHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f); else - window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->ContentsHeight; + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->LastTabContentHeight; if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) PopID(); @@ -6532,6 +6532,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Layout all active tabs float offset_x = initial_offset_x; + float offset_x_ideal = offset_x; tab_bar->OffsetNextTab = offset_x; // This is used by non-reorderable tab bar where the submission order is always honored. for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { @@ -6540,8 +6541,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID) scroll_track_selected_tab_id = tab->ID; offset_x += tab->Width + g.Style.ItemInnerSpacing.x; + offset_x_ideal += tab->WidthContents + g.Style.ItemInnerSpacing.x; } tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); + tab_bar->OffsetMaxIdeal = ImMax(offset_x_ideal - g.Style.ItemInnerSpacing.x, 0.0f); // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); From a89a3cd2f15b09a396428d7fcba433e0acc6880e Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 23 Aug 2019 16:12:06 +0300 Subject: [PATCH 562/566] Viewports, GLFW: Fix window having incorrect size after uncollapse. Issue manifests on Linux when window is in it's own viewport. (#2756, #2117) --- examples/imgui_impl_glfw.cpp | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index dc2d9819..59bd16d0 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -406,8 +406,9 @@ struct ImGuiViewportDataGlfw { GLFWwindow* Window; bool WindowOwned; + bool IgnoreSetWindowSizeEvent; - ImGuiViewportDataGlfw() { Window = NULL; WindowOwned = false; } + ImGuiViewportDataGlfw() { Window = NULL; WindowOwned = false; IgnoreSetWindowSizeEvent = false; } ~ImGuiViewportDataGlfw() { IM_ASSERT(Window == NULL); } }; @@ -426,7 +427,21 @@ static void ImGui_ImplGlfw_WindowPosCallback(GLFWwindow* window, int, int) static void ImGui_ImplGlfw_WindowSizeCallback(GLFWwindow* window, int, int) { if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window)) + { + if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData) + { + if (data->IgnoreSetWindowSizeEvent) + { + // GLFW will dispatch window size event. ImGui expects no such event sent when library explicitly requests setting + // window size. Depending on the platform this callback may be invoked during glfwSetWindowSize() call or queued + // for the next frame and invoked during glfwPollEvents() call. When latter happens - restoring collapsed window + // would have incorrect size. + data->IgnoreSetWindowSizeEvent = false; + return; + } + } viewport->PlatformRequestResize = true; + } } static void ImGui_ImplGlfw_CreateWindow(ImGuiViewport* viewport) @@ -569,6 +584,8 @@ static ImVec2 ImGui_ImplGlfw_GetWindowSize(ImGuiViewport* viewport) static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) { + if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData) + data->IgnoreSetWindowSizeEvent = true; ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData; #if __APPLE__ // Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are @@ -630,7 +647,7 @@ static void ImGui_ImplGlfw_RenderWindow(ImGuiViewport* viewport, void*) static void ImGui_ImplGlfw_SwapBuffers(ImGuiViewport* viewport, void*) { ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData; - if (g_ClientApi == GlfwClientApi_OpenGL) + if (g_ClientApi == GlfwClientApi_OpenGL) { glfwMakeContextCurrent(data->Window); glfwSwapBuffers(data->Window); From a4af3cc814f2540e279c166e64f4d2687851bb00 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 29 Aug 2019 15:53:33 +0200 Subject: [PATCH 563/566] Viewport, GLFW: Fix for #2756 under Windows. --- examples/imgui_impl_glfw.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 59bd16d0..166f06a1 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -1,7 +1,7 @@ // dear imgui: Platform Binding for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) -// (Requires: GLFW 3.1+) +// (Requires: GLFW 3.1+. Prefer GLFW 3.3+ for full feature support.) // Implemented features: // [X] Platform: Clipboard support. @@ -406,9 +406,9 @@ struct ImGuiViewportDataGlfw { GLFWwindow* Window; bool WindowOwned; - bool IgnoreSetWindowSizeEvent; + int IgnoreWindowSizeEventFrame; - ImGuiViewportDataGlfw() { Window = NULL; WindowOwned = false; IgnoreSetWindowSizeEvent = false; } + ImGuiViewportDataGlfw() { Window = NULL; WindowOwned = false; IgnoreWindowSizeEventFrame = -1; } ~ImGuiViewportDataGlfw() { IM_ASSERT(Window == NULL); } }; @@ -430,15 +430,16 @@ static void ImGui_ImplGlfw_WindowSizeCallback(GLFWwindow* window, int, int) { if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData) { - if (data->IgnoreSetWindowSizeEvent) - { - // GLFW will dispatch window size event. ImGui expects no such event sent when library explicitly requests setting - // window size. Depending on the platform this callback may be invoked during glfwSetWindowSize() call or queued - // for the next frame and invoked during glfwPollEvents() call. When latter happens - restoring collapsed window - // would have incorrect size. - data->IgnoreSetWindowSizeEvent = false; + // GLFW may dispatch window size event after calling glfwSetWindowSize(). + // However depending on the platform the callback may be invoked at different time: on Windows it + // appears to be called within the glfwSetWindowSize() call whereas on Linux it is queued and invoked + // during glfwPollEvents(). + // Because the event doesn't always fire on glfwSetWindowSize() we use a frame counter tag to only + // ignore recent glfwSetWindowSize() calls. + bool ignore_event = (ImGui::GetFrameCount() <= data->IgnoreWindowSizeEventFrame + 1); + data->IgnoreWindowSizeEventFrame = -1; + if (ignore_event) return; - } } viewport->PlatformRequestResize = true; } @@ -584,8 +585,6 @@ static ImVec2 ImGui_ImplGlfw_GetWindowSize(ImGuiViewport* viewport) static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) { - if (ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData) - data->IgnoreSetWindowSizeEvent = true; ImGuiViewportDataGlfw* data = (ImGuiViewportDataGlfw*)viewport->PlatformUserData; #if __APPLE__ // Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are @@ -597,6 +596,7 @@ static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) glfwGetWindowSize(data->Window, &width, &height); glfwSetWindowPos(data->Window, x, y - height + size.y); #endif + data->IgnoreWindowSizeEventFrame = ImGui::GetFrameCount(); glfwSetWindowSize(data->Window, (int)size.x, (int)size.y); } From b59ec7b9b7f85c60d26907690126f30bf4f1e11a Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 30 Aug 2019 20:28:14 +0200 Subject: [PATCH 564/566] DragInt, DragFloat, DragScalar: Using (v_min > v_max) allows locking any edit to the value. --- docs/CHANGELOG.txt | 1 + imgui.h | 2 ++ imgui_widgets.cpp | 13 ++++++++----- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d20df9d9..33ee2680 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,7 @@ Other Changes: - TabBar: improved shrinking for large number of tabs to avoid leaving extraneous space on the right side. Individuals tabs are given integer-rounded width and remainder is spread between tabs left-to-right. - SliderScalar: Improved assert when using U32 or U64 types with a large v_max value. (#2765) [@loicmouton] +- DragInt, DragFloat, DragScalar: Using (v_min > v_max) allows locking any edit to the value. - ImDrawList: clarified the name of many parameters so reading the code is a little easier. (#2740) - Using offsetof() when available in C++11. Avoids Clang sanitizer complaining about old-style macros. (#94) - Added a mechanism to compact/free the larger allocations of unused windows (buffers are compacted when diff --git a/imgui.h b/imgui.h index a2701739..42ee5340 100644 --- a/imgui.h +++ b/imgui.h @@ -426,6 +426,8 @@ namespace ImGui // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). + // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits. + // - Use v_min > v_max to lock edits. IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 423a873b..6cec3827 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1916,11 +1916,14 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const ImGuiContext& g = *GImGui; const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool has_min_max = (v_min != v_max); - const bool is_power = (power != 1.0f && is_decimal && has_min_max && (v_max - v_min < FLT_MAX)); + const bool is_clamped = (v_min < v_max); + const bool is_power = (power != 1.0f && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); + const bool is_locked = (v_min > v_max); + if (is_locked) + return false; // Default tweak speed - if (v_speed == 0.0f && has_min_max && (v_max - v_min < FLT_MAX)) + if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX)) v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio); // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings @@ -1948,7 +1951,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // Clear current value on activation // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. bool is_just_activated = g.ActiveIdIsJustActivated; - bool is_already_past_limits_and_pushing_outward = has_min_max && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); + bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0)); if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power) { @@ -2000,7 +2003,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const v_cur = (TYPE)0; // Clamp values (+ handle overflow/wrap-around for integer types) - if (*v != v_cur && has_min_max) + if (*v != v_cur && is_clamped) { if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_decimal)) v_cur = v_min; From 0537ac005f7e76311556a4e24c8ddfb4fa1bdcc8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 30 Aug 2019 20:33:35 +0200 Subject: [PATCH 565/566] ColorEdit: Disable Hue edit when Saturation==0 instead of letting Hue values jump around. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 33ee2680..a34aef92 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,7 @@ Other Changes: - ColorPicker: Made rendering aware of global style alpha of the picker can be faded out. (#2711) Note that some elements won't accurately fade down with the same intensity, and the color wheel when enabled will have small overlap glitches with (style.Alpha < 1.0). +- ColorEdit: Disable Hue edit when Saturation==0 instead of letting Hue values jump around. - TabBar: fixed ScrollToBar request creating bouncing loop when tab is larger than available space. - TabBar: fixed single-tab not shrinking their width down. - TabBar: feed desired width (sum of unclipped tabs width) into layout system to allow for auto-resize. (#2768) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6cec3827..a91268b3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4234,14 +4234,17 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (n > 0) SameLine(0, style.ItemInnerSpacing.x); SetNextItemWidth((n + 1 < components) ? w_item_one : w_item_last); + + // Disable Hue edit when Saturation is zero + const bool disable_hue_edit = (n == 0 && (flags & ImGuiColorEditFlags_DisplayHSV) && i[1] == 0); if (flags & ImGuiColorEditFlags_Float) { - value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); + value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, disable_hue_edit ? +FLT_MAX : 0.0f, disable_hue_edit ? -FLT_MAX : hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); value_changed_as_float |= value_changed; } else { - value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); + value_changed |= DragInt(ids[n], &i[n], 1.0f, disable_hue_edit ? INT_MAX : 0, disable_hue_edit ? INT_MIN : hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); From d049a7988c9c569ff240533e96d8500f3a715cab Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 31 Aug 2019 16:51:12 +0200 Subject: [PATCH 566/566] Docking: comments for DockBuilder API. --- imgui.cpp | 18 ++++++++++++------ imgui_internal.h | 10 +++++++--- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4b324a67..e7ddd574 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13740,8 +13740,12 @@ void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) node->AuthorityForSize = ImGuiDataAuthority_DockNode; } -// If you create a regular node, both ref_pos/ref_size will position the window. -// If you create a dockspace node: ref_pos won't be used, ref_size is useful on the first frame to... +// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node! +// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. +// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. +// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! +// For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. +// - Use (id == 0) to let the system allocate a node identifier. ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) { ImGuiContext* ctx = GImGui; @@ -13878,8 +13882,10 @@ void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persi } } +// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created. +// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set. // FIXME-DOCK: We are not exposing nor using split_outer. -ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_other) +ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir) { ImGuiContext* ctx = GImGui; IM_ASSERT(split_dir != ImGuiDir_None); @@ -13905,11 +13911,11 @@ ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_r DockContextProcessDock(ctx, &req); ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID; - ImGuiID id_other = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID; + ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID; if (out_id_at_dir) *out_id_at_dir = id_at_dir; - if (out_id_other) - *out_id_other = id_other; + if (out_id_at_opposite_dir) + *out_id_at_opposite_dir = id_at_opposite_dir; return id_at_dir; } diff --git a/imgui_internal.h b/imgui_internal.h index 54c5bc51..bca9c3dc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1800,17 +1800,21 @@ namespace ImGui IMGUI_API void SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond); // Docking - Builder function needs to be generally called before the DockSpace() node is submitted. - // Important: do not hold on ImGuiDockNode* pointers. They may be invalidated by any split/merge/remove operation and every frame. + // - The DockBuilderXXX functions are designed to _eventually_ become a public API, but it is too early to expose it and guarantee stability. + // - You can create dockspace _or_ floating nodes with this API. To create a dockspace node, make sure to set the ImGuiDockNodeFlags_DockSpace flag. + // - If you intend to split the node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand. + // - Call DockBuilderFinish() after you are done. + // - Important: do not hold on ImGuiDockNode* pointers! They may be invalidated by any split/merge/remove operation and every frame. IMGUI_API void DockBuilderDockWindow(const char* window_name, ImGuiID node_id); IMGUI_API ImGuiDockNode*DockBuilderGetNode(ImGuiID node_id); inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; } - IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags = 0); // Use (flags == ImGuiDockNodeFlags_DockSpace) to create a dockspace, otherwise it'll create a floating node. + IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id = 0, ImGuiDockNodeFlags flags = 0); IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_persistent_docking_references = true); IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the root. IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); - IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_dir, ImGuiID* out_id_other); + IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir); IMGUI_API void DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector* in_window_remap_pairs); IMGUI_API void DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector* out_node_remap_pairs); IMGUI_API void DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name);