From 528b12eb7a30ba264ddcb4e33860e403bd133623 Mon Sep 17 00:00:00 2001 From: u3shit Date: Tue, 21 Apr 2020 02:13:06 +0200 Subject: [PATCH 001/223] Fix glClipControl(GL_UPPER_LEFT) handling in opengl3. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_opengl3.cpp | 21 +++++++++++---------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 81cb3bab..18cb9659 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,8 @@ Other Changes: - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) +- Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the + projection matrix top and bottom values. (#3143, #3146) [@u3shit] ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 40e531dd..bf8225d0 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader. // 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader. @@ -243,6 +244,14 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif + // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) + bool clip_origin_lower_left = true; +#if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__) + GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); + if (current_clip_origin == GL_UPPER_LEFT) + clip_origin_lower_left = false; +#endif + // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); @@ -250,6 +259,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, @@ -318,12 +328,6 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); - bool clip_origin_lower_left = true; -#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; -#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) @@ -371,10 +375,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) 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 - 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 rarely used glClipControl(GL_UPPER_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)); // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); From fd6d3155c07fb2292e7ef84f4d53d0fb8eb1196a Mon Sep 17 00:00:00 2001 From: Silent Date: Wed, 22 Apr 2020 10:13:20 +0200 Subject: [PATCH 002/223] Fix wrong comment in ImGuiCond_ (#3139) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 5ac453c4..bdc241fa 100644 --- a/imgui.h +++ b/imgui.h @@ -1265,7 +1265,7 @@ enum ImGuiMouseCursor_ enum ImGuiCond_ { ImGuiCond_Always = 1 << 0, // Set the variable - ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) + ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will 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) }; From 223297b075a7c2c76f33356a3854e6dd8da2b49b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Apr 2020 16:30:37 +0200 Subject: [PATCH 003/223] Clarified comments about popups input blocking and ImGuiHoveredFlags_AllowWhenBlockedByPopup flag. (#3154) --- imgui.h | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index bdc241fa..f2b1cd9d 100644 --- a/imgui.h +++ b/imgui.h @@ -591,13 +591,16 @@ namespace ImGui // Popups, Modals // The properties of popups windows are: - // - They block normal mouse hovering detection outside them. (*) + // - They block normal mouse hovering detection outside them. (*1) // - 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. - // User can manipulate the visibility state by calling OpenPopup(). + // Because hovering detection is disabled outside the popup, when clicking outside the click will not be seen by underlying widgets! (*1) + // - 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(), CloseCurrentPopup() etc. // - We default to use the right mouse (ImGuiMouseButton_Right=1) for the Popup Context functions. - // (*) You 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. + // Those three properties are connected: we need to retain popup visibility state in the library because popups may be closed as any time. + // (*1) You can bypass that restriction and detect hovering even when normally blocked by a popup. + // To do this use the ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // This is what BeginPopupContextItem() and BeginPopupContextWindow() are doing already, allowing a right-click to reopen another popups without losing the click. IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! From 5ac5d3674fc79bfb41634df6ce412eb9bc098453 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Apr 2020 15:30:30 +0200 Subject: [PATCH 004/223] Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 1 + imgui.h | 15 ++++++++------- imgui_draw.cpp | 21 +++++++++------------ 4 files changed, 21 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 18cb9659..ad309327 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,9 @@ HOW TO UPDATE? Breaking Changes: +- Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please + note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. + Other Changes: - TreeNode: Fixed bug where BeginDragDropSource() failed when the _OpenOnDoubleClick flag is diff --git a/imgui.cpp b/imgui.cpp index 0d4d9780..f900a010 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,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. + - 2020/04/23 (1.77) - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead. - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value. diff --git a/imgui.h b/imgui.h index f2b1cd9d..d3460d72 100644 --- a/imgui.h +++ b/imgui.h @@ -2150,13 +2150,13 @@ struct ImFontGlyphRangesBuilder // See ImFontAtlas::AddCustomRectXXX functions. struct ImFontAtlasCustomRect { - unsigned int ID; // Input // User ID. Use < 0x110000 to map into a font glyph, >= 0x110000 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 < 0x110000): glyph xadvance - ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID < 0x110000): glyph display offset - ImFont* Font; // Input // For custom font glyphs only (ID < 0x110000): target font - ImFontAtlasCustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } + unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000) + float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance + ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset + ImFont* Font; // Input // For custom font glyphs only: target font + ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } bool IsPacked() const { return X != 0xFFFF; } }; @@ -2235,8 +2235,9 @@ 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 docs/FONTS.txt for more details about using colorful icons. - IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x110000. 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 < 0x110000 to register a rectangle to map into a specific font. + // Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. + IMGUI_API int AddCustomRectRegular(int width, int height); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } // [Internal] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d0d6a1e7..909949dc 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1543,7 +1543,6 @@ ImFontConfig::ImFontConfig() // 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; static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX " @@ -1826,14 +1825,11 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed return font; } -int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) +int ImFontAtlas::AddCustomRectRegular(int width, int height) { - // Breaking change on 2019/11/21 (1.74): ImFontAtlas::AddCustomRectRegular() now requires an ID >= 0x110000 (instead of >= 0x10000) - IM_ASSERT(id >= 0x110000); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); ImFontAtlasCustomRect r; - r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; CustomRects.push_back(r); @@ -1842,13 +1838,16 @@ int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) { +#ifdef IMGUI_USE_WCHAR32 + IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX); +#endif IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); ImFontAtlasCustomRect r; - r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; + r.GlyphID = id; r.GlyphAdvanceX = advance_x; r.GlyphOffset = offset; r.Font = font; @@ -1873,7 +1872,6 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou IM_ASSERT(CustomRectIds[0] != -1); 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]; *out_size = size; @@ -2208,9 +2206,9 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->CustomRectIds[0] >= 0) return; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); else - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, 2, 2); + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(2, 2); } void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) @@ -2259,7 +2257,6 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) IM_ASSERT(atlas->CustomRectIds[0] >= 0); IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; - IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); IM_ASSERT(r.IsPacked()); const int w = atlas->TexWidth; @@ -2294,13 +2291,13 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) for (int i = 0; i < atlas->CustomRects.Size; i++) { const ImFontAtlasCustomRect& r = atlas->CustomRects[i]; - if (r.Font == NULL || r.ID >= 0x110000) + if (r.Font == NULL || r.GlyphID == 0) continue; IM_ASSERT(r.Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; atlas->CalcCustomRectUV(&r, &uv0, &uv1); - r.Font->AddGlyph((ImWchar)r.ID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX); + r.Font->AddGlyph((ImWchar)r.GlyphID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX); } // Build all fonts lookup tables From d3212482fe6e158db71999ae84de754f908ab8fd Mon Sep 17 00:00:00 2001 From: Matt Haynie Date: Thu, 23 Apr 2020 13:58:45 -0700 Subject: [PATCH 005/223] Fix multiple macro definitions of GLFW_INCLUDE_NONE (#3157) --- examples/imgui_impl_opengl3.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index bf8225d0..c60df73d 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -121,12 +121,16 @@ #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Needs to be initialized with gladLoadGL() in user's code. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) +#ifndef GLFW_INCLUDE_NONE #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. +#endif #include // Needs to be initialized with glbinding::Binding::initialize() in user's code. #include using namespace gl; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) +#ifndef GLFW_INCLUDE_NONE #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. +#endif #include // Needs to be initialized with glbinding::initialize() in user's code. #include using namespace gl; From 73c30aa085d8432fcaa9288572b317a3c8951530 Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Thu, 4 Jul 2019 18:28:34 -0700 Subject: [PATCH 006/223] Backends: Vulkan: Don't skip drawing when there's no vertexes to ensure that user callbacks are still processed. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_vulkan.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ad309327..70480187 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData + structure didn't have any vertices. (#2697) [@kudaba] ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 095a7f26..72866dde 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) +// 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. // 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. @@ -274,6 +275,7 @@ static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkCommandBu } // Bind Vertex And Index Buffer: + if (draw_data->TotalVtxCount > 0) { VkBuffer vertex_buffers[1] = { rb->VertexBuffer }; VkDeviceSize vertex_offset[1] = { 0 }; @@ -314,7 +316,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // 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) + if (fb_width <= 0 || fb_height <= 0) return; ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; @@ -343,6 +345,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm 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 + if (vertex_size > 0) { ImDrawVert* vtx_dst = NULL; ImDrawIdx* idx_dst = NULL; From 2593b6a1c86dcfc2fee95bbe55fbd9ae04d5991c Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 27 Apr 2020 12:01:59 +0300 Subject: [PATCH 007/223] Drag and Drop: Fix unintended fallback "..." tooltip during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 2 +- imgui.h | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70480187..11a9560c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,8 +49,10 @@ Other Changes: - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] -- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] +- Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when + drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index f900a010..8e66bbed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4216,7 +4216,7 @@ void ImGui::EndFrame() } // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing. - if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount) + if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { g.DragDropWithinSource = true; SetTooltip("..."); diff --git a/imgui.h b/imgui.h index d3460d72..5420ac53 100644 --- a/imgui.h +++ b/imgui.h @@ -644,6 +644,7 @@ namespace ImGui // Drag and Drop // - [BETA API] API may evolve! + // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip as replacement) 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 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! From 8cbff5ccb23675f5b3eaa1080a79bb2ae575fc33 Mon Sep 17 00:00:00 2001 From: Ryan Pavlik Date: Fri, 24 Apr 2020 15:50:27 -0500 Subject: [PATCH 008/223] Fix various typos. (#3161) (found by Debian's lintian on a package that uses imgui.) (found by codespell.) --- imgui.cpp | 12 ++++++------ imgui.h | 4 ++-- imgui_demo.cpp | 10 +++++----- imgui_draw.cpp | 14 +++++++------- imgui_widgets.cpp | 10 +++++----- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8e66bbed..8ce07618 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -900,7 +900,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. +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 certain time, unless mouse moved. //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS @@ -4231,7 +4231,7 @@ void ImGui::EndFrame() UpdateMouseMovingWindowEndFrame(); // Sort the window list so that all child windows are after their parent - // We cannot do that on FocusWindow() because childs may not exist yet + // We cannot do that on FocusWindow() because children may not exist yet g.WindowsTempSortBuffer.resize(0); g.WindowsTempSortBuffer.reserve(g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) @@ -4331,7 +4331,7 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex } // 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 +// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is // called, aka before the next Begin(). Moving window isn't affected. static void FindHoveredWindow() @@ -6360,7 +6360,7 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) } // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) -// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly. +// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. // If you want a window to never be focused, you may use the e.g. NoInputs flag. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) { @@ -6814,7 +6814,7 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() { ImGuiContext& g = *GImGui; - // Verify that io.KeyXXX fields haven't been tampered with. Key mods shoudl not be modified between NewFrame() and EndFrame() + // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() const ImGuiKeyModFlags expected_key_mod_flags = GetMergedKeyModFlags(); IM_ASSERT(g.IO.KeyMods == expected_key_mod_flags && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(expected_key_mod_flags); @@ -7811,7 +7811,7 @@ void ImGui::EndPopup() // Make all menus and popups wrap around for now, may need to expose that policy. NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); - // Child-popups don't need to be layed out + // Child-popups don't need to be laid out IM_ASSERT(g.WithinEndChild == false); if (window->Flags & ImGuiWindowFlags_ChildWindow) g.WithinEndChild = true; diff --git a/imgui.h b/imgui.h index 5420ac53..3dfdc39c 100644 --- a/imgui.h +++ b/imgui.h @@ -371,7 +371,7 @@ namespace ImGui // Cursor / Layout // - 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. - // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceeding widget. + // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: // Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos() // Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. @@ -2299,7 +2299,7 @@ struct ImFont 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; // 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) - ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations accross all used codepoints. + ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. // Methods IMGUI_API ImFont(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e9652ef7..a052205c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -644,7 +644,7 @@ static void ShowDemoWindowWidgets() static bool test_drag_and_drop = false; ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be layed out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth); ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); @@ -994,7 +994,7 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Alignment")) { - HelpMarker("By default, Selectables uses style.SelectableTextAlign but it can be overriden on a per-item basis using PushStyleVar(). You'll probably want to always keep your default situation to left-align otherwise it becomes difficult to layout multiple items on a same line"); + HelpMarker("By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item basis using PushStyleVar(). You'll probably want to always keep your default situation to left-align otherwise it becomes difficult to layout multiple items on a same line"); static bool selected[3*3] = { true, false, true, false, true, false, true, false, true }; for (int y = 0; y < 3; y++) { @@ -1065,7 +1065,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Resize Callback")) { // To wire InputText() with std::string or any other custom string type, - // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper using your prefered type. + // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper using your preferred type. // See misc/cpp/imgui_stdlib.h 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 @@ -1082,7 +1082,7 @@ static void ShowDemoWindowWidgets() return 0; } - // Tip: Because ImGui:: is a namespace you would typicall add your own function into the namespace in your own source files. + // Tip: Because ImGui:: is a namespace you would typically 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) { @@ -3865,7 +3865,7 @@ struct ExampleAppConsole AddLog("Unknown command: '%s'\n", command_line); } - // On commad input, we scroll to bottom even if AutoScroll==false + // On command input, we scroll to bottom even if AutoScroll==false ScrollToBottom = true; } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 909949dc..954c5536 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -615,7 +615,7 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c _IdxWritePtr += 6; } -// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superflous function calls to optimize debug/non-inlined builds. +// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. // Those macros expects l-values. #define IM_NORMALIZE2F_OVER_ZERO(VX,VY) do { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } } while (0) #define IM_FIXNORMAL2F(VX,VY) do { 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; } while (0) @@ -684,7 +684,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_x *= AA_SIZE; dm_y *= AA_SIZE; - // Add temporary vertexes + // Add temporary vertices ImVec2* out_vtx = &temp_points[i2*2]; out_vtx[0].x = points[i2].x + dm_x; out_vtx[0].y = points[i2].y + dm_y; @@ -701,7 +701,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertexes + // Add vertices for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; @@ -741,7 +741,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 float dm_in_x = dm_x * half_inner_thickness; float dm_in_y = dm_y * half_inner_thickness; - // Add temporary vertexes + // Add temporary vertices ImVec2* out_vtx = &temp_points[i2*4]; out_vtx[0].x = points[i2].x + dm_out_x; out_vtx[0].y = points[i2].y + dm_out_y; @@ -764,7 +764,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertexes + // Add vertices for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; @@ -2307,7 +2307,7 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) // Ellipsis character is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis). // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character. - // FIXME: Also note that 0x2026 is currently seldomly included in our font ranges. Because of this we are more likely to use three individual dots. + // FIXME: Also note that 0x2026 is currently seldom included in our font ranges. Because of this we are more likely to use three individual dots. for (int i = 0; i < atlas->Fonts.size(); i++) { ImFont* font = atlas->Fonts[i]; @@ -3329,7 +3329,7 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im // Helper for ColorPicker4() // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. -// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether. +// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. // FIXME: uses ImGui::GetColorU32 void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 02ac3cd5..e58c8aea 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2345,7 +2345,7 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); } -// FIXME: Move some of the code into SliderBehavior(). Current responsability is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. +// FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { @@ -2942,7 +2942,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data 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. + flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. if (p_step != NULL) { @@ -3360,7 +3360,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (!is_resizable) return; - // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the midly similar code (until we remove the U16 buffer alltogether!) + // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!) ImGuiContext& g = *GImGui; ImGuiInputTextState* edit_state = &g.InputTextState; IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); @@ -4745,7 +4745,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl 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. + // FIXME: Hackily differentiating 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; @@ -6249,7 +6249,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) 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, - // However the final position is going to be different! It is choosen by FindBestWindowPosForPopup(). + // However the final position is going to be different! It is chosen 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) From a2454f2a45ea016443411fcf69a971e9b1d650f6 Mon Sep 17 00:00:00 2001 From: Clownacy Date: Tue, 28 Apr 2020 15:15:00 +0100 Subject: [PATCH 009/223] Use __NEWLIB__ instead of __SWITCH__ and __CYGWIN__ for alloca.h-detection (#3070) Cygwin uses newlib, so it's covered by the __NEWLIB__ check. You can see how it defines __NEWLIB__ here: https://cygwin.com/git/?p=newlib-cygwin.git;a=blob;f=newlib/configure.in#l453 --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 954c5536..1df83d12 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -36,7 +36,7 @@ Index of this file: #include // vsnprintf, sscanf, printf #if !defined(alloca) -#if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) || defined(__SWITCH__) +#if defined(__GLIBC__) || defined(__sun) || defined(__APPLE__) || defined(__NEWLIB__) #include // alloca (glibc uses . Note that Cygwin may have _WIN32 defined, so the order matters here) #elif defined(_WIN32) #include // alloca From d5ce3b43aeff58e31966903f23e8ed3dea6f11af Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 11:03:05 +0200 Subject: [PATCH 010/223] Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) --- docs/CHANGELOG.txt | 3 ++- examples/imgui_impl_vulkan.cpp | 25 ++++++++++++------------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 11a9560c..039a67ad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,7 +49,8 @@ Other Changes: - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] -- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData +- Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 72866dde..652476c7 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) +// 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices. // 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. // 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. @@ -334,22 +335,20 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm wrb->Index = (wrb->Index + 1) % wrb->Count; ImGui_ImplVulkanH_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; - VkResult err; - - // 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 (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 - if (vertex_size > 0) + if (draw_data->TotalVtxCount > 0) { + // 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 (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, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); + VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); check_vk_result(err); err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst)); check_vk_result(err); From 794bf7a28d80caffb423b1ede77ca993c3efa387 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 29 Apr 2020 13:32:16 +0300 Subject: [PATCH 011/223] CI: Implement builds with IMGUI_DISABLE_WIN32_FUNCTIONS, IMGUI_DISABLE_FILE_FUNCTIONS, IMGUI_USE_BGRA_PACKED_COLOR IM_VEC2_CLASS_EXTRA, IM_VEC4_CLASS_EXTRA and building library as a DLL. --- .github/workflows/build.yml | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b089bfb4..03641749 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,6 +59,29 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp + - name: Build example_null (with IMGUI_DISABLE_WIN32_FUNCTIONS) + shell: bash + run: | + echo '#define IMGUI_DISABLE_WIN32_FUNCTIONS' > example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp + + - name: Build example_null (as DLL) + shell: cmd + run: | + "%VS_PATH%\VC\Auxiliary\Build\vcvarsall.bat" x64 + echo '#ifdef _EXPORT' > example_single_file.cpp + echo '# define IMGUI_API __declspec(dllexport)' >> example_single_file.cpp + echo '#else' >> example_single_file.cpp + echo '# define IMGUI_API __declspec(dllimport)' >> example_single_file.cpp + echo '#endif' >> example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + cl.exe /D_USRDLL /D_WINDLL /D_EXPORT /I. example_single_file.cpp /LD /FeImGui.dll /link + cl.exe /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp + - name: Build Win32 example_glfw_opengl2 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj /p:Platform=Win32 /p:Configuration=Release' @@ -233,6 +256,38 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (with IMGUI_DISABLE_FILE_FUNCTIONS) + run: | + echo '#define IMGUI_DISABLE_FILE_FUNCTIONS' > example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + + - name: Build example_null (with IMGUI_USE_BGRA_PACKED_COLOR) + run: | + echo '#define IMGUI_USE_BGRA_PACKED_COLOR' > example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + + - name: Build example_null (with IM_VEC2_CLASS_EXTRA and IM_VEC4_CLASS_EXTRA) + run: | + echo 'struct MyVec2 { float x; float y; MyVec2(float x, float y) : x(x), y(y) { } };' > example_single_file.cpp + echo 'struct MyVec4 { float x; float y; float z; float w;' >> example_single_file.cpp + echo 'MyVec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { } };' >> example_single_file.cpp + echo '#define IM_VEC2_CLASS_EXTRA \' >> example_single_file.cpp + echo ' ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \' >> example_single_file.cpp + echo ' operator MyVec2() const { return MyVec2(x, y); }' >> example_single_file.cpp + echo '#define IM_VEC4_CLASS_EXTRA \' >> example_single_file.cpp + echo ' ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \' >> example_single_file.cpp + echo ' operator MyVec4() const { return MyVec4(x, y, z, w); }' >> example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 From 1e9abf60d1b6c71a738c96ef9c123ab358608bf8 Mon Sep 17 00:00:00 2001 From: Silent Date: Tue, 28 Apr 2020 21:53:46 +0200 Subject: [PATCH 012/223] Backends: Keep shader blobs as local variables. (#3176) --- examples/imgui_impl_dx10.cpp | 33 ++++++++++++++++++++------------- examples/imgui_impl_dx11.cpp | 33 ++++++++++++++++++++------------- examples/imgui_impl_dx12.cpp | 30 ++++++++++++++++++------------ 3 files changed, 58 insertions(+), 38 deletions(-) diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 7eb4e5af..ffaa7707 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -41,11 +41,9 @@ static ID3D10Device* g_pd3dDevice = NULL; static IDXGIFactory* g_pFactory = NULL; static ID3D10Buffer* g_pVB = NULL; static ID3D10Buffer* g_pIB = NULL; -static ID3D10Blob* g_pVertexShaderBlob = NULL; static ID3D10VertexShader* g_pVertexShader = NULL; static ID3D10InputLayout* g_pInputLayout = NULL; static ID3D10Buffer* g_pVertexConstantBuffer = NULL; -static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D10PixelShader* g_pPixelShader = NULL; static ID3D10SamplerState* g_pFontSampler = NULL; static ID3D10ShaderResourceView*g_pFontTextureView = NULL; @@ -369,11 +367,14 @@ bool ImGui_ImplDX10_CreateDeviceObjects() return output;\ }"; - D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL); - if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK) + ID3DBlob* vertexShaderBlob; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK) + { + vertexShaderBlob->Release(); return false; + } // Create the input layout D3D10_INPUT_ELEMENT_DESC local_layout[] = @@ -382,8 +383,12 @@ bool ImGui_ImplDX10_CreateDeviceObjects() { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; - if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + { + vertexShaderBlob->Release(); return false; + } + vertexShaderBlob->Release(); // Create the constant buffer { @@ -415,11 +420,15 @@ bool ImGui_ImplDX10_CreateDeviceObjects() return out_col; \ }"; - D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL); - if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK) + ID3DBlob* pixelShaderBlob; + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK) + { + pixelShaderBlob->Release(); return false; + } + pixelShaderBlob->Release(); } // Create the blending setup @@ -482,11 +491,9 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; } if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; } if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; } - if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; } if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; } if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; } if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; } - if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; } } bool ImGui_ImplDX10_Init(ID3D10Device* device) diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 97e17ff1..5aa09f9b 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -42,11 +42,9 @@ static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; static IDXGIFactory* g_pFactory = NULL; static ID3D11Buffer* g_pVB = NULL; static ID3D11Buffer* g_pIB = NULL; -static ID3D10Blob* g_pVertexShaderBlob = NULL; static ID3D11VertexShader* g_pVertexShader = NULL; static ID3D11InputLayout* g_pInputLayout = NULL; static ID3D11Buffer* g_pVertexConstantBuffer = NULL; -static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D11PixelShader* g_pPixelShader = NULL; static ID3D11SamplerState* g_pFontSampler = NULL; static ID3D11ShaderResourceView*g_pFontTextureView = NULL; @@ -381,11 +379,14 @@ bool ImGui_ImplDX11_CreateDeviceObjects() return output;\ }"; - D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL); - if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK) + ID3DBlob* vertexShaderBlob; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK) + { + vertexShaderBlob->Release(); return false; + } // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = @@ -394,8 +395,12 @@ bool ImGui_ImplDX11_CreateDeviceObjects() { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; - if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + { + vertexShaderBlob->Release(); return false; + } + vertexShaderBlob->Release(); // Create the constant buffer { @@ -427,11 +432,15 @@ bool ImGui_ImplDX11_CreateDeviceObjects() return out_col; \ }"; - D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL); - if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK) + ID3DBlob* pixelShaderBlob; + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK) + { + pixelShaderBlob->Release(); return false; + } + pixelShaderBlob->Release(); } // Create the blending setup @@ -494,11 +503,9 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; } if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; } if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; } - if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; } if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; } if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; } if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; } - if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; } } bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index e7bb5e9c..a2913613 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -37,8 +37,6 @@ // DirectX data static ID3D12Device* g_pd3dDevice = NULL; -static ID3D10Blob* g_pVertexShaderBlob = NULL; -static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D12RootSignature* g_pRootSignature = NULL; static ID3D12PipelineState* g_pPipelineState = NULL; static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN; @@ -473,6 +471,9 @@ bool ImGui_ImplDX12_CreateDeviceObjects() psoDesc.SampleDesc.Count = 1; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + ID3DBlob* vertexShaderBlob; + ID3DBlob* pixelShaderBlob; + // Create the vertex shader { static const char* vertexShader = @@ -503,10 +504,9 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return output;\ }"; - D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL); - if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - psoDesc.VS = { g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize() }; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &vertexShaderBlob, NULL))) + return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() }; // Create the input layout static D3D12_INPUT_ELEMENT_DESC local_layout[] = { @@ -535,10 +535,12 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return out_col; \ }"; - D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL); - if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - psoDesc.PS = { g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize() }; + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &pixelShaderBlob, NULL))) + { + vertexShaderBlob->Release(); + return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + } + psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() }; } // Create the blending setup @@ -584,7 +586,13 @@ bool ImGui_ImplDX12_CreateDeviceObjects() } if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK) + { + vertexShaderBlob->Release(); + pixelShaderBlob->Release(); return false; + } + vertexShaderBlob->Release(); + pixelShaderBlob->Release(); ImGui_ImplDX12_CreateFontsTexture(); @@ -596,8 +604,6 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() if (!g_pd3dDevice) return; - SafeRelease(g_pVertexShaderBlob); - SafeRelease(g_pPixelShaderBlob); SafeRelease(g_pRootSignature); SafeRelease(g_pPipelineState); SafeRelease(g_pFontTextureResource); From 099091280f055c1267bf75dc390a8d95665e8c3f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 11:32:58 +0200 Subject: [PATCH 013/223] Backends: DX10/DX11: Minor tweaks. --- examples/imgui_impl_dx10.cpp | 30 +++++++++++++++--------------- examples/imgui_impl_dx11.cpp | 30 +++++++++++++++--------------- examples/imgui_impl_dx12.cpp | 9 +++------ 3 files changed, 33 insertions(+), 36 deletions(-) diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index ffaa7707..23ade277 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -342,29 +342,29 @@ bool ImGui_ImplDX10_CreateDeviceObjects() static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ - float4x4 ProjectionMatrix; \ + float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ - float2 pos : POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float2 pos : POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ - float4 pos : SV_POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float4 pos : SV_POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ - PS_INPUT output;\ - output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ - output.col = input.col;\ - output.uv = input.uv;\ - return output;\ + PS_INPUT output;\ + output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ + output.col = input.col;\ + output.uv = input.uv;\ + return output;\ }"; ID3DBlob* vertexShaderBlob; @@ -379,9 +379,9 @@ bool ImGui_ImplDX10_CreateDeviceObjects() // Create the input layout D3D10_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) { diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 5aa09f9b..26eb407f 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -354,29 +354,29 @@ bool ImGui_ImplDX11_CreateDeviceObjects() static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ - float4x4 ProjectionMatrix; \ + float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ - float2 pos : POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float2 pos : POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ - float4 pos : SV_POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float4 pos : SV_POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ - PS_INPUT output;\ - output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ - output.col = input.col;\ - output.uv = input.uv;\ - return output;\ + PS_INPUT output;\ + output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ + output.col = input.col;\ + output.uv = input.uv;\ + return output;\ }"; ID3DBlob* vertexShaderBlob; @@ -391,9 +391,9 @@ bool ImGui_ImplDX11_CreateDeviceObjects() // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) { diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index a2913613..167a189b 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -585,14 +585,11 @@ bool ImGui_ImplDX12_CreateDeviceObjects() desc.BackFace = desc.FrontFace; } - if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK) - { - vertexShaderBlob->Release(); - pixelShaderBlob->Release(); - return false; - } + HRESULT result_pipeline_state = g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)); vertexShaderBlob->Release(); pixelShaderBlob->Release(); + if (result_pipeline_state != S_OK) + return false; ImGui_ImplDX12_CreateFontsTexture(); From b4dd28ffbbe4d382d38ef6de742db93388b5482f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 14:58:21 +0200 Subject: [PATCH 014/223] Style: Added style.TabMinWidthForUnselectedCloseButton settings. Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 3 +++ imgui.h | 1 + imgui_internal.h | 2 +- imgui_widgets.cpp | 23 +++++++++++++++++++---- 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 039a67ad..819abbec 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,10 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) +- Style: Added style.TabMinWidthForUnselectedCloseButton settings. + Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). + Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). + Set to an intermediary value to toggle behavior based on width (same as Firefox). - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] diff --git a/imgui.cpp b/imgui.cpp index 8ce07618..680a3289 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1028,6 +1028,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. + TabMinWidthForUnselectedCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. 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. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. @@ -1064,6 +1065,8 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); TabRounding = ImFloor(TabRounding * scale_factor); + if (TabMinWidthForUnselectedCloseButton != FLT_MAX) + TabMinWidthForUnselectedCloseButton = ImFloor(TabMinWidthForUnselectedCloseButton * scale_factor); DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); diff --git a/imgui.h b/imgui.h index 3dfdc39c..9c85e97b 100644 --- a/imgui.h +++ b/imgui.h @@ -1393,6 +1393,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. + float TabMinWidthForUnselectedCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. 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. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. diff --git a/imgui_internal.h b/imgui_internal.h index d6ef765d..46cca946 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1827,7 +1827,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, ImVec2 frame_padding, 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, bool is_contents_visible); // 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 e58c8aea..200c43e4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7090,6 +7090,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->NextSelectedTabId = id; // Lock visibility + // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!) bool tab_contents_visible = (tab_bar->VisibleTabId == id); if (tab_contents_visible) tab_bar->VisibleTabWasSubmitted = true; @@ -7195,7 +7196,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, tab_bar->FramePadding, label, id, close_button_id); + bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); if (just_closed && p_open != NULL) { *p_open = false; @@ -7270,13 +7271,21 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic // 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) +bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible) { ImGuiContext& g = *GImGui; ImVec2 label_size = CalcTextSize(label, NULL, true); if (bb.GetWidth() <= 1.0f) return false; + // In Style V2 we'll have full override of all colors per state (e.g. focused, selected) + // But right now if you want to alter text color of tabs this is what you need to do. +#if 0 + const float backup_alpha = g.Style.Alpha; + if (!is_contents_visible) + g.Style.Alpha *= 0.7f; +#endif + // Render text label (with clipping + alpha gradient) + unsaved marker const char* TAB_UNSAVED_MARKER = "*"; 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); @@ -7296,8 +7305,9 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, bool close_button_pressed = false; bool close_button_visible = false; if (close_button_id != 0) - if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id) - close_button_visible = true; + if (is_contents_visible || bb.GetWidth() >= g.Style.TabMinWidthForUnselectedCloseButton) + if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id) + close_button_visible = true; if (close_button_visible) { ImGuiItemHoveredDataBackup last_item_backup; @@ -7318,6 +7328,11 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, 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); +#if 0 + if (!is_contents_visible) + g.Style.Alpha = backup_alpha; +#endif + return close_button_pressed; } From 11a3e75f47085fe14da5ff4ca5fe2298092fd937 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 20:46:20 +0200 Subject: [PATCH 015/223] Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_win32.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 819abbec..96cadc9b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) +- Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index aa00a1f9..ae18eb6e 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -359,7 +359,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA #if !defined(_versionhelpers_H_INCLUDED_) && !defined(_INC_VERSIONHELPERS) static BOOL IsWindowsVersionOrGreater(WORD major, WORD minor, WORD sp) { - OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0, { 0 }, sp }; + OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0, { 0 }, sp, 0, 0, 0, 0 }; DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR; ULONGLONG cond = ::VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL); cond = ::VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL); @@ -405,7 +405,9 @@ void ImGui_ImplWin32_EnableDpiAwareness() return; } } - SetProcessDPIAware(); +#if _WIN32_WINNT >= 0x0600 + ::SetProcessDPIAware(); +#endif } #if defined(_MSC_VER) && !defined(NOGDI) From 419f905f91f1a7f0dc0c836a73b7579b66e454ce Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 May 2020 19:53:54 +0200 Subject: [PATCH 016/223] Demo: Extracted some code out of ShowStyleEditor() into NodeFont(). --- imgui_demo.cpp | 160 +++++++++++++++++++++++++++---------------------- 1 file changed, 90 insertions(+), 70 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a052205c..24699261 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3285,6 +3285,95 @@ void ImGui::ShowFontSelector(const char* label) "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); } +// [Internal] Display details for a single font, called by ShowStyleEditor(). +static void NodeFont(ImFont* font) +{ + ImGuiIO& io = ImGui::GetIO(); + ImGuiStyle& style = ImGui::GetStyle(); + bool font_details_opened = ImGui::TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)", + font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); + ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; } + if (!font_details_opened) + return; + + ImGui::PushFont(font); + 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(); HelpMarker( + "Note than the default embedded font is NOT meant to be scaled.\n\n" + "Font 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 will be rewritten in the future to make scaling more flexible.)"); + 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' (U+%04X)", font->FallbackChar, font->FallbackChar); + ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar); + const int surface_sqrt = (int)sqrtf((float)font->MetricsTotalSurface); + ImGui::Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + if (font->ConfigData) + 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)) + { + // Display all glyphs of the fonts in separate pages of 256 characters + const ImU32 glyph_col = ImGui::GetColorU32(ImGuiCol_Text); + for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) + { + // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT is large. + // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) + { + base += 4096 - 256; + continue; + } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (font->FindGlyphNoFallback((ImWchar)(base + n))) + count++; + if (count <= 0) + continue; + if (!ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + float cell_size = font->FontSize * 1; + float cell_spacing = style.ItemSpacing.y; + ImVec2 base_pos = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (unsigned int n = 0; n < 256; n++) + { + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available here + // in order to generate a zero-terminated string. + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); + const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); + if (glyph) + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) + { + ImGui::BeginTooltip(); + ImGui::Text("Codepoint: U+%04X", base + n); + ImGui::Separator(); + ImGui::Text("Visible: %d", glyph->Visible); + ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX); + ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + ImGui::EndTooltip(); + } + } + ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); +} + void ImGui::ShowStyleEditor(ImGuiStyle* ref) { // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to an internally stored reference) @@ -3433,76 +3522,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")) { io.FontDefault = font; } - if (font_details_opened) - { - ImGui::PushFont(font); - 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(); 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' (U+%04X)", font->FallbackChar, font->FallbackChar); - ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar); - const float surface_sqrt = sqrtf((float)font->MetricsTotalSurface); - ImGui::Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, (int)surface_sqrt, (int)surface_sqrt); - for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) - if (font->ConfigData) - 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)) - { - // Display all glyphs of the fonts in separate pages of 256 characters - for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) - { - // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) - // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT is large. - // (if ImWchar==ImWchar32 we will do at least about 272 queries here) - if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) - { - base += 4096 - 256; - continue; - } - - int count = 0; - for (unsigned int n = 0; n < 256; n++) - count += font->FindGlyphNoFallback((ImWchar)(base + n)) ? 1 : 0; - if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) - { - float cell_size = font->FontSize * 1; - float cell_spacing = style.ItemSpacing.y; - ImVec2 base_pos = ImGui::GetCursorScreenPos(); - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - for (unsigned int n = 0; n < 256; n++) - { - ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); - ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); - const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); - draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50)); - if (glyph) - font->RenderChar(draw_list, cell_size, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base + n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string. - if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) - { - ImGui::BeginTooltip(); - ImGui::Text("Codepoint: U+%04X", base + n); - ImGui::Separator(); - ImGui::Text("Visible: %d", glyph->Visible); - ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX); - ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); - ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); - ImGui::EndTooltip(); - } - } - ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - } - ImGui::TreePop(); - } + NodeFont(font); ImGui::PopID(); } if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) From f152fac4f1962aedf1d483a5b05a525637354b3a Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 May 2020 19:39:24 +0200 Subject: [PATCH 017/223] Demo: Wrapped many (not all) code and comments lines to 120 characters to fit below GitHub viewer limit. (#3193) --- imgui.cpp | 2 +- imgui.h | 2 +- imgui_demo.cpp | 1238 ++++++++++++++++++++++++++++++------------------ 3 files changed, 781 insertions(+), 461 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 680a3289..86af727d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4,7 +4,7 @@ // Help: // - Read FAQ at http://dearimgui.org/faq // - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. -// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // Read imgui.cpp for details, links and comments. // Resources: diff --git a/imgui.h b/imgui.h index 9c85e97b..788f74c9 100644 --- a/imgui.h +++ b/imgui.h @@ -4,7 +4,7 @@ // Help: // - Read FAQ at http://dearimgui.org/faq // - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. -// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // Read imgui.cpp for details, links and comments. // Resources: diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 24699261..3b2ceee1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4,38 +4,39 @@ // Help: // - Read FAQ at http://dearimgui.org/faq // - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. -// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // Read imgui.cpp for more details, documentation and comments. // Get latest version at https://github.com/ocornut/imgui // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: -// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other coders -// will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available debug menu of -// your game/app! Removing this file from your project is hindering access to documentation for everyone in your team, -// likely leading you to poorer usage of the library. +// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other +// coders will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available +// debug menu of your game/app! Removing this file from your project is hindering access to documentation for everyone +// in your team, likely leading you to poorer usage of the library. // Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow(). -// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be linked, -// you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty. +// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be +// linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty. // In other situation, whenever you have Dear ImGui available you probably want this to be available for reference. // Thank you, // -Your beloved friend, imgui_demo.cpp (which you won't delete) // Message to beginner C/C++ programmers about the meaning of the 'static' keyword: -// 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 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. +// 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 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 in 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 never omit the ImGui:: prefix when calling functions, even though most code here is 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 of our 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. +// - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API. +// - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided +// by imgui_internal.h using the IMGUI_DEFINE_MATH_OPERATORS define. 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 can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp. /* @@ -82,31 +83,31 @@ Index of this file: #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif #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' -#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. +#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.. // 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 +#pragma clang diagnostic ignored "-Wformat-security" // 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: 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 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") -#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. +#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 #if __has_warning("-Wreserved-id-macro") -#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#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 -#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. +#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 +#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 (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!) +// Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!) #ifdef _WIN32 #define IM_NEWLINE "\r\n" #else @@ -161,7 +162,9 @@ void ImGui::ShowUserGuide() { ImGuiIO& io = ImGui::GetIO(); ImGui::BulletText("Double-click on title bar to collapse window."); - ImGui::BulletText("Click and drag on lower corner to resize window\n(double-click to auto fit window to its contents)."); + ImGui::BulletText( + "Click and drag on lower corner to resize window\n" + "(double-click to auto fit window to its contents)."); ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text."); ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); if (io.FontAllowUserScaling) @@ -196,7 +199,8 @@ void ImGui::ShowUserGuide() // - ShowDemoWindowMisc() //----------------------------------------------------------------------------- -// We split the contents of the big ShowDemoWindow() function into smaller functions (because the link time of very large functions grow non-linearly) +// We split the contents of the big ShowDemoWindow() function into smaller functions +// (because the link time of very large functions grow non-linearly) static void ShowDemoWindowWidgets(); static void ShowDemoWindowLayout(); static void ShowDemoWindowPopups(); @@ -204,10 +208,13 @@ static void ShowDemoWindowColumns(); static void ShowDemoWindowMisc(); // Demonstrate most Dear ImGui features (this is big function!) -// 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. +// 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 + // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup + // Most ImGui functions would normally just crash if the context is missing. + IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); // Examples Apps (accessible from the "Examples" menu) static bool show_app_documents = false; @@ -241,9 +248,14 @@ void ImGui::ShowDemoWindow(bool* p_open) static bool show_app_style_editor = false; static bool show_app_about = false; - if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); } - if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); } - if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); } + if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); } + if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); } + if (show_app_style_editor) + { + ImGui::Begin("Dear ImGui Style Editor", &show_app_style_editor); + ImGui::ShowStyleEditor(); + ImGui::End(); + } // Demonstrate the various window flags. Typically you would just use the default! static bool no_titlebar = false; @@ -269,7 +281,8 @@ void ImGui::ShowDemoWindow(bool* p_open) if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; if (no_close) p_open = NULL; // Don't pass our bool* to Begin - // We specify a default position/size in case there's no data in the .ini file. Typically this isn't required! We only do it to make the Demo applications a little more welcoming. + // We specify a default position/size in case there's no data in the .ini file. + // We only do it to make the demo applications a little more welcoming, but typically this isn't required. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); @@ -281,9 +294,13 @@ void ImGui::ShowDemoWindow(bool* p_open) return; } - // 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) - 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. + // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. + + // e.g. Use 2/3 of the space for widgets and 1/3 for labels (default) + //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); + + // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. + ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // Menu Bar if (ImGui::BeginMenuBar()) @@ -350,13 +367,15 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Configuration##2")) { - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); 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(); 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! + ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); + + // The "NoMouse" option above can get us stuck with a disable mouse! Provide an alternative way to fix it: + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) { if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f) { @@ -374,18 +393,22 @@ void ImGui::ShowDemoWindow(bool* p_open) 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(); 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::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. 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")) { - HelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.\nHere we expose then as read-only fields to avoid breaking interactions with your back-end."); - 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); + HelpMarker( + "Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.\n" + "Here we expose then as read-only fields to avoid breaking interactions with your back-end."); + + // Make a local copy to avoid modifying actual back-end flags. + ImGuiBackendFlags backend_flags = io.BackendFlags; + 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: RendererHasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); ImGui::TreePop(); ImGui::Separator(); @@ -401,10 +424,13 @@ 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."); - HelpMarker("Try opening any of the contents below in this window and then click one of the \"Log To\" button."); + HelpMarker( + "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.\n" + "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."); + + HelpMarker("You can also call ImGui::LogText() to output directly to the log without a visual output."); if (ImGui::Button("Copy \"Hello, world!\" to clipboard")) { ImGui::LogToClipboard(); @@ -478,7 +504,9 @@ static void ShowDemoWindowWidgets() ImGui::PopID(); } - // Use AlignTextToFramePadding() to align text baseline to the baseline of framed elements (otherwise a Text+SameLine+Button sequence will have the text a little too high by default) + // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + // See 'Demo->Layout->Text Baseline Alignment' for details. ImGui::AlignTextToFramePadding(); ImGui::Text("Hold to repeat:"); ImGui::SameLine(); @@ -516,7 +544,7 @@ static void ShowDemoWindowWidgets() { // Using the _simplified_ one-liner Combo() api here // See "Combo" section for examples of how to use the more complete BeginCombo()/EndCombo() api. - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; static int item_current = 0; ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); HelpMarker("Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n"); @@ -527,14 +555,28 @@ static void ShowDemoWindowWidgets() // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. static char str0[128] = "Hello, world!"; ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); - 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)."); + ImGui::SameLine(); HelpMarker( + "USER:\n" + "Hold 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\n" + "PROGRAMMER:\n" + "You 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(); HelpMarker("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 ]\n" + "Use +- to subtract."); static float f0 = 0.001f; ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); @@ -544,7 +586,9 @@ static void ShowDemoWindowWidgets() static float f1 = 1.e10f; ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); - ImGui::SameLine(); HelpMarker("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\"."); static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; ImGui::InputFloat3("input float3", vec4a); @@ -553,7 +597,10 @@ static void ShowDemoWindowWidgets() { static int i1 = 50, i2 = 42; ImGui::DragInt("drag int", &i1, 1); - 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::SameLine(); HelpMarker( + "Click and drag to edit value.\n" + "Hold SHIFT/ALT for faster/slower edit.\n" + "Double-click or CTRL+click to input value."); ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%"); @@ -578,10 +625,10 @@ static void ShowDemoWindowWidgets() // 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); + static int elem = Element_Fire; + const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; + const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown"; + ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); } @@ -589,16 +636,20 @@ 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(); 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::SameLine(); HelpMarker( + "Click on the colored square to open a color picker.\n" + "Click and hold to use drag and drop.\n" + "Right-click on the colored square to show options.\n" + "CTRL+click on individual component to input value.\n"); ImGui::ColorEdit4("color 2", col2); } { // List box - const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; - static int listbox_item_current = 1; - ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int item_current = 1; + ImGui::ListBox("listbox\n(single select)", &item_current, items, IM_ARRAYSIZE(items), 4); //static int listbox_item_current2 = 2; //ImGui::SetNextItemWidth(-1); @@ -620,8 +671,8 @@ static void ShowDemoWindowWidgets() { 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! + // 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); @@ -638,25 +689,31 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Advanced, with Selectable nodes")) { - 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."); + HelpMarker( + "This is a more typical looking tree with selectable nodes.\n" + "Click to select, CTRL+Click to toggle, click on arrows or double-click to open."); static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; static bool align_label_with_current_x_position = false; static bool test_drag_and_drop = false; - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth); ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position); ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop); ImGui::Text("Hello!"); if (align_label_with_current_x_position) ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); - static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. - int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc. + // 'selection_mask' is dumb representation of what may be user-side selection state. + // You may retain selection state inside or outside your objects in whatever format you see fit. + // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end + /// of the loop. May be a pointer to your own node type, etc. + static int selection_mask = (1 << 2); + int node_clicked = -1; 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. + // Disable the default "open on single-click behavior" + set Selected flag according to our selection. ImGuiTreeNodeFlags node_flags = base_flags; const bool is_selected = (selection_mask & (1 << i)) != 0; if (is_selected) @@ -682,8 +739,8 @@ static void ShowDemoWindowWidgets() else { // 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 advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + // The only reason we use TreeNode at all is to allow selection of the leaf. 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()) @@ -698,10 +755,11 @@ static void ShowDemoWindowWidgets() } if (node_clicked != -1) { - // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. + // Update selection state + // (process outside of tree loop to avoid visual inconsistencies during the clicking frame) if (ImGui::GetIO().KeyCtrl) selection_mask ^= (1 << node_clicked); // CTRL+click to toggle - else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection selection_mask = (1 << node_clicked); // Click to single-select } if (align_label_with_current_x_position) @@ -769,21 +827,24 @@ static void ShowDemoWindowWidgets() static float wrap_width = 200.0f; ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); - ImGui::Text("Test paragraph 1:"); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("The lazy dog is a good dog. This paragraph is made to fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); - ImGui::PopTextWrapPos(); - - ImGui::Text("Test paragraph 2:"); - pos = ImGui::GetCursorScreenPos(); - ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); - ImGui::PopTextWrapPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 2; n++) + { + ImGui::Text("Test paragraph %d:", n); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y); + ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + if (n == 0) + ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); + if (n == 1) + ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + + // Draw actual text bounding box, following by marker of our expected limit (should not overlap!) + draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)); + ImGui::PopTextWrapPos(); + } ImGui::TreePop(); } @@ -791,14 +852,19 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("UTF-8 Text")) { // UTF-8 test with Japanese characters - // (Needs a suitable font, try Noto, or Arial Unicode, or M+ fonts. Read docs/FONTS.txt for details.) + // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.txt for details.) // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 - // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. Visual Studio save your file as 'UTF-8 without signature') - // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 CHARACTERS IN THIS SOURCE FILE. - // Instead we are encoding a few strings with hexadecimal constants. Don't do this in your application! - // Please use u8"text in any language" in your application! - // Note that characters values are preserved even by InputText() if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. - ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. Read docs/FONTS.txt for details."); + // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you + // can save your source files as 'UTF-8 without signature'). + // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 + // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants. + // Don't do this in your application! Please use u8"text in any language" in your application! + // Note that characters values are preserved even by InputText() if the font cannot be displayed, + // so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped( + "CJK text will only appears if the font was loaded with the appropriate CJK character ranges. " + "Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. " + "Read docs/FONTS.txt for details."); ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); // Normally we would use u8"blah blah" with the proper characters directly in the string. ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; @@ -814,41 +880,63 @@ static void ShowDemoWindowWidgets() ImGuiIO& io = ImGui::GetIO(); ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); - // 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_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(). + // Below we are displaying the font texture because it is the only texture we have access to inside the demo! + // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that + // will be passed to the rendering back-end via the ImDrawCmd structure. + // If you use one of the default imgui_impl_XXXX.cpp rendering back-end, they all have comments at the top + // of their respective source 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_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. + // More: + // - 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. + // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, + // it will help you debug issues if you are confused about it. + // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). + // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md + // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples ImTextureID my_tex_id = io.Fonts->TexID; float my_tex_w = (float)io.Fonts->TexWidth; float my_tex_h = (float)io.Fonts->TexHeight; - - 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), ImVec4(1.0f,1.0f,1.0f,1.0f), ImVec4(1.0f,1.0f,1.0f,0.5f)); - if (ImGui::IsItemHovered()) { - ImGui::BeginTooltip(); - float region_sz = 32.0f; - float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; if (region_x < 0.0f) region_x = 0.0f; else if (region_x > my_tex_w - region_sz) region_x = my_tex_w - region_sz; - float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; if (region_y < 0.0f) region_y = 0.0f; else if (region_y > my_tex_h - region_sz) region_y = my_tex_h - region_sz; - float zoom = 4.0f; - ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); - 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, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), ImVec4(1.0f, 1.0f, 1.0f, 0.5f)); - ImGui::EndTooltip(); + ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left + ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); // 50% opaque white + ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + float region_sz = 32.0f; + float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; + float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; + float zoom = 4.0f; + if (region_x < 0.0f) { region_x = 0.0f; } + else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; } + if (region_y < 0.0f) { region_y = 0.0f; } + else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; } + ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); + 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, tint_col, border_col); + ImGui::EndTooltip(); + } } ImGui::TextWrapped("And now some textured buttons.."); static int pressed_count = 0; for (int i = 0; i < 8; i++) { 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, ImVec4(0.0f,0.0f,0.0f,1.0f))) + int frame_padding = -1 + i; // -1 == uses default padding (style.FramePadding) + ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible + ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left + ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32 / my_tex_h); // UV coordinates for (32,32) in our texture + ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + if (ImGui::ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col)) pressed_count += 1; ImGui::PopID(); ImGui::SameLine(); @@ -869,19 +957,23 @@ static void ShowDemoWindowWidgets() if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", (unsigned int*)&flags, ImGuiComboFlags_NoPreview)) flags &= ~ImGuiComboFlags_NoArrowButton; // Clear the other flag, as we cannot combine both - // General BeginCombo() API, you have full control over your selection data and display type. - // (your selection data could be an index, a pointer to the object, an id for the object, a flag stored in the object itself, etc.) + // Using the generic BeginCombo() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; - static const char* item_current = items[0]; // Here our selection is a single pointer stored outside the object. - if (ImGui::BeginCombo("combo 1", item_current, flags)) // The second parameter is the label previewed before opening the combo. + static int item_current_idx = 0; // Here our selection data is an index. + const char* combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically could be anything)( + if (ImGui::BeginCombo("combo 1", combo_label, flags)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { - bool is_selected = (item_current == items[n]); + const bool is_selected = (item_current_idx == n); if (ImGui::Selectable(items[n], is_selected)) - item_current = items[n]; + item_current_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (is_selected) - ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch) + ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } @@ -905,9 +997,11 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Selectables")) { // Selectable() has 2 overloads: - // - The one taking "bool selected" as a read-only selection information. When Selectable() has been clicked is returns true and you can alter selection state accordingly. + // - The one taking "bool selected" as a read-only selection information. + // When Selectable() has been clicked it returns true and you can alter selection state accordingly. // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) - // The earlier is more flexible, as in real application your selection may be stored in a different manner (in flags within objects, as an external list, etc). + // The earlier is more flexible, as in real application your selection may be stored in many different ways + // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). if (ImGui::TreeNode("Basic")) { static bool selection[5] = { false, true, false, false, false }; @@ -951,7 +1045,8 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Rendering more text into the same line")) { - // Using the Selectable() override that takes "bool* p_selected" parameter and toggle your booleans automatically. + // Using the Selectable() override that takes "bool* p_selected" parameter, + // this function toggle your bool value automatically. static bool selected[3] = { false, false, false }; ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); @@ -973,13 +1068,17 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Grid")) { - static bool selected[4*4] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; + static int selected[4*4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; for (int i = 0; i < 4*4; i++) { ImGui::PushID(i); - if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50))) + if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50,50))) { - // Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer. The second part of each test is unnecessary. + // Toggle + selected[i] = !selected[i]; + + // Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer. + // The second part of each test is unnecessary. int x = i % 4; int y = i / 4; if (x > 0) { selected[i - 1] ^= 1; } @@ -994,8 +1093,11 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Alignment")) { - HelpMarker("By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item basis using PushStyleVar(). You'll probably want to always keep your default situation to left-align otherwise it becomes difficult to layout multiple items on a same line"); - static bool selected[3*3] = { true, false, true, false, true, false, true, false, true }; + HelpMarker( + "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " + "basis using PushStyleVar(). You'll probably want to always keep your default situation to " + "left-align otherwise it becomes difficult to layout multiple items on a same line"); + static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true }; for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) @@ -1045,12 +1147,22 @@ static void ShowDemoWindowWidgets() 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); + struct TextFilters + { + // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i' + static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) + { + if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) + return 0; + return 1; + } + }; + + 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 buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); ImGui::Text("Password input"); @@ -1065,9 +1177,11 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Resize Callback")) { // To wire InputText() with std::string or any other custom string type, - // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper using your preferred type. - // See misc/cpp/imgui_stdlib.h 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."); + // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper + // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. + HelpMarker( + "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n" + "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); struct Funcs { static int MyResizeCallback(ImGuiInputTextCallbackData* data) @@ -1076,14 +1190,14 @@ static void ShowDemoWindowWidgets() { 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 + 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 would typically 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). + // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace. + // For example, you code may declare a function '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); @@ -1092,7 +1206,8 @@ static void ShowDemoWindowWidgets() }; // 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. + // 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); @@ -1105,7 +1220,8 @@ static void ShowDemoWindowWidgets() } // 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) + // Consider writing your own plotting widget, or using a third-party one + // (for third-party Plot widgets, see 'Wiki->Useful Widgets' or https://github.com/ocornut/imgui/labels/plot%2Fgraph) if (ImGui::TreeNode("Plots Widgets")) { static bool animate = true; @@ -1115,13 +1231,14 @@ static void ShowDemoWindowWidgets() ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); // Create a dummy array of contiguous float values to plot - // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter. + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float + // and the sizeof() of your structure in the "stride" parameter. static float values[90] = {}; static int values_offset = 0; static double refresh_time = 0.0; if (!animate || refresh_time == 0.0) refresh_time = ImGui::GetTime(); - while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 hz rate for the demo + while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 Hz rate for the demo { static float phase = 0.0f; values[values_offset] = cosf(phase); @@ -1139,12 +1256,13 @@ static void ShowDemoWindowWidgets() 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::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); } - ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); // Use functions to generate output - // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count. + // FIXME: This is rather awkward because current plot API only pass in indices. + // We probably want an API passing floats and user provide sample rate/count. struct Funcs { static float Sin(void*, int i) { return sinf(i * 0.1f); } @@ -1200,7 +1318,9 @@ static void ShowDemoWindowWidgets() 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"); + ImGui::SameLine(); HelpMarker( + "Click on the colored square to open a color picker.\n" + "CTRL+click on individual component to input value.\n"); ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); ImGui::Text("Color widget HSV with Alpha:"); @@ -1210,7 +1330,10 @@ static void ShowDemoWindowWidgets() ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); ImGui::Text("Color button with Picker:"); - 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::SameLine(); HelpMarker( + "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n" + "With 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:"); @@ -1222,7 +1345,8 @@ static void ShowDemoWindowWidgets() { for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) { - ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); + ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, + saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); saved_palette[n].w = 1.0f; // Alpha } saved_palette_init = false; @@ -1257,11 +1381,13 @@ static void ShowDemoWindowWidgets() ImGui::PushID(n); if ((n % 8) != 0) ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); - if (ImGui::ColorButton("##palette", saved_palette[n], ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip, ImVec2(20,20))) + + ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20,20))) color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! - // Allow user to drop colors into each palette entry - // (Note that ColorButton is already a drag source by default, unless using ImGuiColorEditFlags_NoDragDrop) + // Allow user to drop colors into each palette entry. Note that ColorButton() is already a + // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag. if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) @@ -1304,7 +1430,10 @@ static void ShowDemoWindowWidgets() } } ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0"); - 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::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(); HelpMarker("User can right-click the picker to change mode."); ImGuiColorEditFlags flags = misc_flags; @@ -1319,22 +1448,29 @@ static void ShowDemoWindowWidgets() 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(); 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."); + ImGui::Text("Set defaults in code:"); + ImGui::SameLine(); HelpMarker( + "SetColorEditOptions() is designed to allow you to set boot-time default.\n" + "We 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")) 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); + static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV! 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::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 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::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f); ImGui::TreePop(); } @@ -1350,20 +1486,23 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Data Types")) { - // The DragScalar/InputScalar/SliderScalar functions allow various data types: signed/unsigned int/long long and float/double - // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum to pass the type, - // and passing all arguments by address. + // DragScalar/InputScalar/SliderScalar functions allow various data types + // - signed/unsigned + // - 8/16/32/64-bits + // - integer/float/double + // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + // to pass the type, and passing all arguments by pointer. // This is the reason the test code below creates local variables to hold "zero" "one" etc. for each types. - // In practice, if you frequently use a given type that is not covered by the normal API entry points, you can wrap it - // yourself inside a 1 line function which can take typed argument as value instead of void*, and then pass their address - // to the generic function. For example: + // In practice, if you frequently use a given type that is not covered by the normal API entry points, + // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*, + // and then pass their address to the generic function. For example: // bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld") // { // return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format); // } - // Limits (as helper variables that we can take the address of) - // Note that the SliderScalar function has a maximum usable range of half the natural type maximum, hence the /2 below. + // Setup limits (as helper variables so we can take their address, as explained above) + // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. #ifndef LLONG_MIN ImS64 LLONG_MIN = -9223372036854775807LL - 1; ImS64 LLONG_MAX = 9223372036854775807LL; @@ -1552,8 +1691,9 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Drag and drop in standard widgets")) { // ColorEdit widgets automatically act as drag source and drag target. - // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F to allow your own widgets - // to use colors in their drag and drop interaction. Also see the demo in Color Picker -> Palette demo. + // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + // to allow your own widgets to use colors in their drag and drop interaction. + // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. HelpMarker("You can drag from the colored squares."); static float col1[3] = { 1.0f, 0.0f, 0.2f }; static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; @@ -1574,7 +1714,12 @@ static void ShowDemoWindowWidgets() if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } - static const char* names[9] = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }; + const char* names[9] = + { + "Bobby", "Beatrice", "Betty", + "Brianna", "Barry", "Bernard", + "Bibi", "Blaine", "Bryn" + }; for (int n = 0; n < IM_ARRAYSIZE(names); n++) { ImGui::PushID(n); @@ -1585,8 +1730,12 @@ static void ShowDemoWindowWidgets() // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { - ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); // Set payload to carry the index of our item (could be anything) - if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } // Display preview (could be anything, e.g. when dragging an image we could decide to display the filename and a small preview of the image, etc.) + // Set payload to carry the index of our item (could be anything) + ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); + + // Display preview (could be anything, e.g. when dragging an image we could decide to display + // the filename and a small preview of the image, etc.) + if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); } if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); } ImGui::EndDragDropSource(); @@ -1623,7 +1772,9 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Drag to reorder items (simple)")) { // Simple reordering - HelpMarker("We don't use the drag and drop api at all here! Instead we query when the item is held but not hovered, and order items accordingly."); + HelpMarker( + "We don't use the drag and drop api at all here! " + "Instead we query when the item is held but not hovered, and order items accordingly."); static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }; for (int n = 0; n < IM_ARRAYSIZE(item_names); n++) { @@ -1649,11 +1800,18 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Querying Status (Active/Focused/Hovered etc.)")) { - // Submit an item (various types available) so we can query their status in the following block. + // Select an item type + const char* item_names[] = + { + "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputFloat", + "InputFloat3", "ColorEdit4", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "ListBox" + }; static int item_type = 1; - ImGui::Combo("Item Type", &item_type, "Text\0Button\0Button (w/ repeat)\0Checkbox\0SliderFloat\0InputText\0InputFloat\0InputFloat3\0ColorEdit4\0MenuItem\0TreeNode\0TreeNode (w/ double-click)\0ListBox\0", 20); + ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names)); ImGui::SameLine(); HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions."); + + // Submit selected item item so we can query their status in the code following it. bool ret = false; static bool b = false; static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; @@ -1672,10 +1830,10 @@ static void ShowDemoWindowWidgets() if (item_type == 11){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. if (item_type == 12){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } - // Display the value of IsItemHovered() and other common item state functions. + // Display the values of IsItemHovered() and other common item state functions. // Note that the ImGuiHoveredFlags_XXX flags can be combined. // Because BulletText is an item itself and that would affect the output of IsItemXXX functions, - // we query every state in a single call to avoid storing them and to simplify the code + // we query every state in a single call to avoid storing them and to simplify the code. ImGui::BulletText( "Return value = %d\n" "IsItemFocused() = %d\n" @@ -1718,7 +1876,7 @@ static void ShowDemoWindowWidgets() static bool embed_all_inside_a_child_window = false; ImGui::Checkbox("Embed everything inside a child window (for additional testing)", &embed_all_inside_a_child_window); if (embed_all_inside_a_child_window) - ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20), true); + ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), true); // Testing IsWindowFocused() function with its various flags. // Note that the ImGuiFocusedFlags_XXX flags can be combined. @@ -1764,7 +1922,7 @@ static void ShowDemoWindowWidgets() 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. + // This is useful in particular if you want to create a context menu associated to the title bar of a window. static bool test_window = false; ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window); if (test_window) @@ -1807,7 +1965,9 @@ static void ShowDemoWindowLayout() // Child 1: no border, enable horizontal scrollbar { - ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; ImGui::BeginChild("ChildL", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags); for (int i = 0; i < 100; i++) { @@ -1824,7 +1984,11 @@ static void ShowDemoWindowLayout() // Child 2: rounded border { - ImGuiWindowFlags window_flags = (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_None; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; + if (!disable_menu) + window_flags |= ImGuiWindowFlags_MenuBar; ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); ImGui::BeginChild("ChildR", ImVec2(0, 260), true, window_flags); if (!disable_menu && ImGui::BeginMenuBar()) @@ -1852,10 +2016,11 @@ static void ShowDemoWindowLayout() // Demonstrate a few extra things // - Changing ImGuiCol_ChildBg (which is transparent black in default styles) - // - Using SetCursorPos() to position the child window (because the child window is an item from the POV of the parent window) - // You can also call SetNextWindowPos() to position the child window. The parent window will effectively layout from this position. - // - 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. + // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) + // You can also call SetNextWindowPos() to position the child window. The parent window will effectively + // layout from this position. + // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from + // the POV of the parent window). See 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details. { ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10); ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); @@ -1876,6 +2041,9 @@ static void ShowDemoWindowLayout() { // Use SetNextItemWidth() to set the width of a single upcoming item. // Use PushItemWidth()/PopItemWidth() to set the width of a group of items. + // In real code use you'll probably want to choose width values that are proportional to your font size + // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. + static float f = 0.0f; ImGui::Text("SetNextItemWidth/PushItemWidth(100)"); ImGui::SameLine(); HelpMarker("Fixed width."); @@ -1897,7 +2065,8 @@ static void ShowDemoWindowLayout() ImGui::SetNextItemWidth(-100); ImGui::DragFloat("float##4", &f); - // Demonstrate using PushItemWidth to surround three items. Calling SetNextItemWidth() before each of them would have the same effect. + // 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); @@ -1978,7 +2147,8 @@ static void ShowDemoWindowLayout() ImGui::Dummy(button_sz); ImGui::SameLine(); ImGui::Button("B", button_sz); - // Manually wrapping (we should eventually provide this as an automatic layout feature, but for now you can do it manually) + // Manually wrapping + // (we should eventually provide this as an automatic layout feature, but for now you can do it manually) ImGui::Text("Manually wrapping:"); ImGuiStyle& style = ImGui::GetStyle(); int buttons_count = 20; @@ -2049,7 +2219,8 @@ static void ShowDemoWindowLayout() ImGui::Checkbox(names[n], &opened[n]); } - // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): the underlying bool will be set to false when the tab is closed. + // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): + // the underlying bool will be set to false when the tab is closed. if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { for (int n = 0; n < IM_ARRAYSIZE(opened); n++) @@ -2070,7 +2241,10 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Groups")) { - 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."); + 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(); @@ -2093,9 +2267,9 @@ static void ShowDemoWindowLayout() const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); - ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f, size.y)); + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); ImGui::SameLine(); - ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f, size.y)); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); ImGui::EndGroup(); ImGui::SameLine(); @@ -2116,8 +2290,9 @@ static void ShowDemoWindowLayout() { { ImGui::BulletText("Text baseline:"); - ImGui::SameLine(); - 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::SameLine(); 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 use less vertical space than lines with framed widgets."); ImGui::Indent(); ImGui::Text("KO Blahblah"); ImGui::SameLine(); @@ -2125,7 +2300,8 @@ static void ShowDemoWindowLayout() HelpMarker("Baseline of button will look misaligned with text.."); // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. - // Because we don't know what's coming after the Text() statement, we need to move the text baseline down by FramePadding.y + // (because we don't know what's coming after the Text() statement, we need to move the text baseline + // down by FramePadding.y ahead of time) ImGui::AlignTextToFramePadding(); ImGui::Text("OK Blahblah"); ImGui::SameLine(); ImGui::Button("Some framed item"); ImGui::SameLine(); @@ -2177,7 +2353,7 @@ static void ShowDemoWindowLayout() ImGui::BulletText("Misc items:"); ImGui::Indent(); - // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button + // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. ImGui::Button("80x80", ImVec2(80, 80)); ImGui::SameLine(); ImGui::Button("50x50", ImVec2(50, 50)); @@ -2190,12 +2366,29 @@ static void ShowDemoWindowLayout() const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; ImGui::Button("Button##1"); ImGui::SameLine(0.0f, spacing); - if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + if (ImGui::TreeNode("Node##1")) + { + // Dummy tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } - ImGui::AlignTextToFramePadding(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit). - bool node_open = ImGui::TreeNode("Node##2");// Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. + // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. + // Otherwise you can use SmallButton() (smaller fit). + ImGui::AlignTextToFramePadding(); + + // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add + // other contents below the node. + bool node_open = ImGui::TreeNode("Node##2"); ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); - if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + if (node_open) + { + // Dummy tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } // Bullet ImGui::Button("Button##3"); @@ -2252,8 +2445,9 @@ static void ShowDemoWindowLayout() const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" }; ImGui::TextUnformatted(names[i]); - ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; - bool window_visible = ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, child_flags); + const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; + const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), true, child_flags); if (ImGui::BeginMenuBar()) { ImGui::TextUnformatted("abc"); @@ -2263,7 +2457,7 @@ static void ShowDemoWindowLayout() ImGui::SetScrollY(scroll_to_off_px); if (scroll_to_pos) ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f); - if (window_visible) // Avoid calling SetScrollHereY when running with culled items + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items { for (int item = 0; item < 100; item++) { @@ -2288,18 +2482,25 @@ static void ShowDemoWindowLayout() // 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."); + HelpMarker( + "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" + "Using 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; ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0); - bool window_visible = ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(-100, child_height), true, child_flags); + ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), true, child_flags); 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); - if (window_visible) // Avoid calling SetScrollHereY when running with culled items + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items { for (int item = 0; item < 100; item++) { @@ -2326,16 +2527,21 @@ static void ShowDemoWindowLayout() 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()."); + HelpMarker( + "Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n" + "You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin()."); static int lines = 7; ImGui::SliderInt("Lines", &lines, 1, 15); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); - ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar); + ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30); + ImGui::BeginChild("scrolling", scrolling_child_size, true, ImGuiWindowFlags_HorizontalScrollbar); for (int line = 0; line < lines; line++) { - // Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off - // manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API) + // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() + // If you want to create your own time line for a real application you may be better off manipulating + // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets + // yourself. You may also want to use the lower-level ImDrawList API. int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); for (int n = 0; n < num_buttons; n++) { @@ -2358,13 +2564,21 @@ static void ShowDemoWindowLayout() ImGui::EndChild(); ImGui::PopStyleVar(2); float scroll_x_delta = 0.0f; - ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) { scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; } ImGui::SameLine(); + ImGui::SmallButton("<<"); + if (ImGui::IsItemActive()) + scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("Scroll from code"); ImGui::SameLine(); - ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) { scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; } ImGui::SameLine(); + ImGui::SmallButton(">>"); + if (ImGui::IsItemActive()) + scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x); if (scroll_x_delta != 0.0f) { - ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window) + // Demonstrate a trick: you can use Begin to set yourself in the context of another window + // (here we are already out of your child window) + ImGui::BeginChild("scrolling"); ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); ImGui::EndChild(); } @@ -2465,15 +2679,22 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Clipping")) { static ImVec2 size(100, 100), offset(50, 20); - ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + ImGui::TextWrapped( + "On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. " + "Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. " + "The system is designed to try minimizing both execution and CPU/GPU rendering cost."); ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); ImGui::TextWrapped("(Click and drag)"); ImVec2 pos = ImGui::GetCursorScreenPos(); ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); ImGui::InvisibleButton("##dummy", size); - if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; } + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) + { + offset.x += ImGui::GetIO().MouseDelta.x; + offset.y += ImGui::GetIO().MouseDelta.y; + } ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x + size.x, pos.y + size.y), IM_COL32(90, 90, 120, 255)); - ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x + offset.x, pos.y + offset.y), IM_COL32(255, 255, 255, 255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x + offset.x, pos.y + offset.y), IM_COL32_WHITE, "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); ImGui::TreePop(); } } @@ -2486,10 +2707,12 @@ 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 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. + // - 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. // Typical use for regular windows: // bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End(); @@ -2501,14 +2724,16 @@ static void ShowDemoWindowPopups() if (ImGui::TreeNode("Popups")) { - ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it."); + ImGui::TextWrapped( + "When a popup is active, it inhibits interacting with windows that are behind the popup. " + "Clicking outside the popup closes it."); static int selected_fish = -1; const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; static bool toggles[] = { true, false, false, false, false }; - // Simple selection popup - // (If you want to show the current selection inside the Button itself, you may want to build a string using the "###" operator to preserve a constant ID with a variable label) + // Simple selection popup (if you want to show the current selection inside the Button itself, + // you may want to build a string using the "###" operator to preserve a constant ID with a variable label) if (ImGui::Button("Select..")) ImGui::OpenPopup("my_select_popup"); ImGui::SameLine(); @@ -2582,7 +2807,8 @@ static void ShowDemoWindowPopups() // if (IsItemHovered() && IsMouseReleased(0)) // OpenPopup(id); // return BeginPopup(id); - // For more advanced uses you may want to replicate and cuztomize this code. This the comments inside BeginPopupContextItem() implementation. + // For more advanced uses you may want to replicate and customize this code. + // See details in BeginPopupContextItem(). static float value = 0.5f; ImGui::Text("Value = %.3f (<-- right-click here)", value); if (ImGui::BeginPopupContextItem("item context menu")) @@ -2594,16 +2820,19 @@ static void ShowDemoWindowPopups() ImGui::EndPopup(); } - // 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. + // 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 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(). + // When used after an item that has an ID (e.g.Button), we can skip providing an ID to BeginPopupContextItem(). // BeginPopupContextItem() will use the last item ID as the popup ID. - // In addition here, we want to include your editable label inside the button label. We use the ### operator to override the ID (read FAQ about ID for details) + // In addition here, we want to include your editable label inside the button label. + // We use the ### operator to override the ID (read FAQ about ID for details) static char name[32] = "Label1"; - char buf[64]; sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label + char buf[64]; + sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label ImGui::Button(buf); if (ImGui::BeginPopupContextItem()) { @@ -2620,7 +2849,7 @@ static void ShowDemoWindowPopups() if (ImGui::TreeNode("Modals")) { - ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window."); + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside."); if (ImGui::Button("Delete..")) ImGui::OpenPopup("Delete?"); @@ -2669,8 +2898,9 @@ static void ShowDemoWindowPopups() if (ImGui::Button("Add another modal..")) ImGui::OpenPopup("Stacked 2"); - // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which will close the popup. - // Note that the visibility state of popups is owned by imgui, so the input value of the bool actually doesn't matter here. + // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which + // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value + // of the bool actually doesn't matter here. bool dummy_open = true; if (ImGui::BeginPopupModal("Stacked 2", &dummy_open)) { @@ -2692,9 +2922,12 @@ static void ShowDemoWindowPopups() { ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); ImGui::Separator(); - // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above. - // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here - // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus. + + // Note: As a quirk in this very specific example, we want to differentiate the parent of this menu from the + // parent of the various popup menus above. To do so we are encloding the items in a PushID()/PopID() block + // to make them two different menusets. If we don't, opening any popup above and hovering our menu here would + // open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, + // which is the desired behavior for regular menus. ImGui::PushID("foo"); ImGui::MenuItem("Menu item", "CTRL+M"); if (ImGui::BeginMenu("Menu inside a regular window")) @@ -2876,7 +3109,8 @@ static void ShowDemoWindowColumns() if (ImGui::TreeNode("Horizontal Scrolling")) { ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f)); - ImGui::BeginChild("##ScrollingRegion", ImVec2(0, ImGui::GetFontSize() * 20), false, ImGuiWindowFlags_HorizontalScrollbar); + ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f); + ImGui::BeginChild("##ScrollingRegion", child_size, false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::Columns(10); int ITEMS_COUNT = 2000; ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list @@ -2975,7 +3209,7 @@ static void ShowDemoWindowMisc() ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } - ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } 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); @@ -2985,9 +3219,9 @@ static void ShowDemoWindowMisc() 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); } - ImGui::Text("NavInputs duration:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]); } + 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); } + ImGui::Text("NavInputs duration:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]); } ImGui::Button("Hovering me sets the\nkeyboard capture flag"); if (ImGui::IsItemHovered()) @@ -3009,7 +3243,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(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + //ImGui::SameLine(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool) to disable tabbing through certain widgets."); ImGui::PopAllowKeyboardFocus(); ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); ImGui::TreePop(); @@ -3059,19 +3293,27 @@ static void ShowDemoWindowMisc() { ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); 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::Text("IsMouseDragging(%d):", button); + ImGui::Text(" w/ default threshold: %d,", ImGui::IsMouseDragging(button)); + ImGui::Text(" w/ zero threshold: %d,", ImGui::IsMouseDragging(button, 0.0f)); + ImGui::Text(" w/ large threshold: %d,", 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 - // 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() + // 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::Text("GetMouseDragDelta(0):"); + ImGui::Text(" w/ default threshold: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y); + ImGui::Text(" w/ zero threshold: (%.1f, %.1f)", value_raw.x, value_raw.y); + ImGui::Text("io.MouseDelta: (%.1f, %.1f)", mouse_delta.x, mouse_delta.y); ImGui::TreePop(); } @@ -3080,9 +3322,13 @@ static void ShowDemoWindowMisc() const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "NotAllowed" }; IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT); - ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]); + ImGuiMouseCursor current = ImGui::GetMouseCursor(); + ImGui::Text("Current mouse cursor = %d: %s", current, mouse_cursors_names[current]); ImGui::Text("Hover to see mouse cursors:"); - 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."); + 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]; @@ -3121,11 +3367,12 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGuiStyle& style = ImGui::GetStyle(); bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); - ImGui::BeginChildFrame(ImGui::GetID("cfginfos"), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18), ImGuiWindowFlags_NoMove); + ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18); + ImGui::BeginChildFrame(ImGui::GetID("cfg_infos"), child_size, 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::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub } ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); @@ -3242,7 +3489,8 @@ void ImGui::ShowAboutWindow(bool* p_open) //----------------------------------------------------------------------------- // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. -// Here we use the simplified Combo() api that packs items into a single literal string. Useful for quick combo boxes where the choices are known locally. +// Here we use the simplified Combo() api that packs items into a single literal string. +// Useful for quick combo boxes where the choices are known locally. bool ImGui::ShowStyleSelector(const char* label) { static int style_idx = -1; @@ -3324,8 +3572,8 @@ static void NodeFont(ImFont* font) for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256) { // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k) - // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT is large. - // (if ImWchar==ImWchar32 we will do at least about 272 queries here) + // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT + // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here) if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) { base += 4096 - 256; @@ -3346,8 +3594,8 @@ static void NodeFont(ImFont* font) ImDrawList* draw_list = ImGui::GetWindowDrawList(); for (unsigned int n = 0; n < 256; n++) { - // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available here - // in order to generate a zero-terminated string. + // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions + // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string. ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing)); ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size); const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n)); @@ -3376,7 +3624,8 @@ static void NodeFont(ImFont* font) void ImGui::ShowStyleEditor(ImGuiStyle* ref) { - // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to an internally stored reference) + // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to + // (without a reference style pointer, we will use one compared locally as a reference) ImGuiStyle& style = ImGui::GetStyle(); static ImGuiStyle ref_saved_style; @@ -3394,14 +3643,14 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ref_saved_style = style; ImGui::ShowFontSelector("Fonts##Selector"); - // Simplified Settings + // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f) if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f")) style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding - { bool window_border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &window_border)) style.WindowBorderSize = window_border ? 1.0f : 0.0f; } + { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } ImGui::SameLine(); - { bool frame_border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &frame_border)) style.FrameBorderSize = frame_border ? 1.0f : 0.0f; } + { bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } ImGui::SameLine(); - { bool popup_border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &popup_border)) style.PopupBorderSize = popup_border ? 1.0f : 0.0f; } + { bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } // Save/Revert button if (ImGui::Button("Save Ref")) @@ -3410,7 +3659,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::Button("Revert Ref")) style = *ref; ImGui::SameLine(); - HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. Use \"Export\" below to save them somewhere."); + HelpMarker( + "Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + "Use \"Export\" below to save them somewhere."); ImGui::Separator(); @@ -3447,9 +3698,12 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) style.WindowMenuButtonPosition = window_menu_button_position - 1; 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)."); + 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(); } @@ -3470,7 +3724,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) const ImVec4& col = style.Colors[i]; const char* name = ImGui::GetStyleColorName(i); if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) - ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, + name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w); } ImGui::LogFinish(); } @@ -3481,10 +3736,13 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) filter.Draw("Filter colors", ImGui::GetFontSize() * 16); static ImGuiColorEditFlags alpha_flags = 0; - if (ImGui::RadioButton("Opaque", alpha_flags == 0)) { alpha_flags = 0; } ImGui::SameLine(); - if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine(); - if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); - HelpMarker("In the color list:\nLeft-click on colored square to open color picker,\nRight-click to open edit options menu."); + if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine(); + if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine(); + if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); + HelpMarker( + "In the color list:\n" + "Left-click on colored square to open color picker,\n" + "Right-click to open edit options menu."); ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); ImGui::PushItemWidth(-160); @@ -3497,10 +3755,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) { - // Tips: in a real user application, you may want to merge and use an icon font into the main font, so instead of "Save"/"Revert" you'd use icons. + // Tips: in a real user application, you may want to merge and use an icon font into the main font, + // so instead of "Save"/"Revert" you'd use icons! // Read the FAQ and docs/FONTS.txt about using icon fonts. It's really easy and super convenient! - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; - ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) style.Colors[i] = ref->Colors[i]; + ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; } + ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; } } ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); ImGui::TextUnformatted(name); @@ -3535,9 +3794,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) 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("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::DragFloat("global scale", &io.FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.2f"); // Scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); @@ -3545,7 +3804,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::BeginTabItem("Rendering")) { - 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 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, 10.0f, "%.2f"); @@ -3572,7 +3832,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) // 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) +// - BeginMenuBar() = menu-bar inside current window (which 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() { @@ -3597,7 +3857,8 @@ static void ShowExampleAppMainMenuBar() } } -// Note that shortcuts are currently provided for display only (future version will add flags to BeginMenu to process shortcuts) +// Note that shortcuts are currently provided for display only +// (future version will add explicit flags to BeginMenu() to request processing shortcuts) static void ShowExampleMenuFile() { ImGui::MenuItem("(dummy menu)", NULL, false, false); @@ -3679,7 +3940,7 @@ static void ShowExampleMenuFile() //----------------------------------------------------------------------------- // Demonstrate creating a simple console window, with scrolling, filtering, completion and history. -// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions. +// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions. struct ExampleAppConsole { char InputBuf[256]; @@ -3696,10 +3957,12 @@ struct ExampleAppConsole ClearLog(); memset(InputBuf, 0, sizeof(InputBuf)); HistoryPos = -1; + + // "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. Commands.push_back("HELP"); 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. + Commands.push_back("CLASSIFY"); AutoScroll = true; ScrollToBottom = false; AddLog("Welcome to Dear ImGui!"); @@ -3712,10 +3975,10 @@ struct ExampleAppConsole } // Portable helpers - static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } - static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } - static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)str, len); } - static void Strtrim(char* str) { char* str_end = str + strlen(str); while (str_end > str && str_end[-1] == ' ') str_end--; *str_end = 0; } + static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; } + static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; } + static char* Strdup(const char* s) { size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); } + static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; } void ClearLog() { @@ -3745,7 +4008,8 @@ struct ExampleAppConsole return; } - // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. So e.g. IsItemHovered() will return true when hovering the title bar. + // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. + // So e.g. IsItemHovered() will return true when hovering the title bar. // Here we create a context menu only available from the title bar. if (ImGui::BeginPopupContextItem()) { @@ -3754,14 +4018,16 @@ struct ExampleAppConsole ImGui::EndPopup(); } - ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped( + "This example implements a console with basic coloring, completion and history. A more elaborate " + "implementation may want to store entries along with extra data such as timestamp, emitter, etc."); ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); // 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 Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); - if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); 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); } @@ -3781,25 +4047,38 @@ struct ExampleAppConsole 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 - ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); // Leave room for 1 separator + 1 InputText + // Reserve enough left-over height for 1 separator + 1 input text + const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); + ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); if (ImGui::BeginPopupContextWindow()) { if (ImGui::Selectable("Clear")) ClearLog(); ImGui::EndPopup(); } - // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); - // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items. - // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements. - // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with: - // ImGuiListClipper clipper(Items.Size); - // while (clipper.Step()) + // Display every line as a separate entry so we can change their color or add custom widgets. + // If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping + // to only process visible items. The clipper will automatically measure the height of your first item and then + // "seek" to display only items in the visible area. + // To use the clipper we can replace your standard loop: + // for (int i = 0; i < Items.Size; i++) + // With: + // ImGuiListClipper clipper(Items.Size); + // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) - // However, note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list. - // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter, - // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code! - // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list. + // - That your items are evenly spaced (same height) + // - That you have cheap random access to your elements (you can access them given their index, + // without processing all the ones before) + // You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property. + // We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices + // or offsets of items that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage + // to improve this example code! + // If your items are of variable height: + // - Split them into same height items would be simpler and facilitate random-seeking into your list. + // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); @@ -3809,12 +4088,16 @@ struct ExampleAppConsole if (!Filter.PassFilter(item)) continue; - // 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; } + // Normally you would store more information in your item than just a string. + // (e.g. make Items[] an array of structure, store color/type etc.) + ImVec4 color; + bool has_color = false; + if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; } + else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; } + if (has_color) + ImGui::PushStyleColor(ImGuiCol_Text, color); ImGui::TextUnformatted(item); - if (pop_color) + if (has_color) ImGui::PopStyleColor(); } if (copy_to_clipboard) @@ -3830,7 +4113,8 @@ struct ExampleAppConsole // Command-line bool reclaim_focus = false; - if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) + ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory; + if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this)) { char* s = InputBuf; Strtrim(s); @@ -3852,7 +4136,8 @@ struct ExampleAppConsole { AddLog("# %s\n", command_line); - // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. + // Insert into history. First find match and delete it so it can be pushed to the back. + // This isn't trying to be smart or optimal. HistoryPos = -1; for (int i = History.Size-1; i >= 0; i--) if (Stricmp(History[i], command_line) == 0) @@ -3889,7 +4174,8 @@ struct ExampleAppConsole ScrollToBottom = true; } - static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks + // In C++11 you'd be better off using lambdas for this sort of forwarding callbacks + static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) { ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; return console->TextEditCallback(data); @@ -3928,14 +4214,15 @@ struct ExampleAppConsole } else if (candidates.Size == 1) { - // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } else { - // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" + // Multiple matches. Complete as much as we can.. + // So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. int match_len = (int)(word_end - word_start); for (;;) { @@ -4014,8 +4301,8 @@ 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; // Keep scrolling if already at the bottom + ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls. + bool AutoScroll; // Keep scrolling if already at the bottom. ExampleAppLog() { @@ -4082,8 +4369,8 @@ struct ExampleAppLog { // 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). + // 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]; @@ -4096,13 +4383,17 @@ struct ExampleAppLog { // The simplest and easy way to display the entire buffer: // ImGui::TextUnformatted(buf_begin, buf_end); - // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward to skip non-visible lines. - // Here we instead demonstrate using the clipper to only process lines that are within the visible area. - // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them on your side is recommended. - // Using ImGuiListClipper requires A) random access into your data, and B) items all being the same height, + // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward + // to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are + // within the visible area. + // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them + // on your side is recommended. Using ImGuiListClipper requires + // - A) random access into your data + // - B) items all being the same height, // both of which we can handle since we an array pointing to the beginning of each line of text. - // When using the filter (in the block of code above) we don't have random access into the data to display anymore, which is why we don't use the clipper. - // Storing or skimming through the search result would make it possible (and would be recommended if you want to search through tens of thousands of entries) + // When using the filter (in the block of code above) we don't have random access into the data to display + // anymore, which is why we don't use the clipper. Storing or skimming through the search result would make + // it possible (and would be recommended if you want to search through tens of thousands of entries). ImGuiListClipper clipper; clipper.Begin(LineOffsets.Size); while (clipper.Step()) @@ -4139,12 +4430,14 @@ static void ShowExampleAppLog(bool* p_open) if (ImGui::SmallButton("[Debug] Add 5 entries")) { static int counter = 0; + const char* categories[3] = { "info", "warn", "error" }; + const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; for (int n = 0; n < 5; n++) { - const char* categories[3] = { "info", "warn", "error" }; - const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; + const char* category = categories[counter % IM_ARRAYSIZE(categories)]; + const char* word = words[counter % IM_ARRAYSIZE(words)]; log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n", - ImGui::GetFrameCount(), categories[counter % IM_ARRAYSIZE(categories)], ImGui::GetTime(), words[counter % IM_ARRAYSIZE(words)]); + ImGui::GetFrameCount(), category, ImGui::GetTime(), word); counter++; } } @@ -4174,43 +4467,47 @@ static void ShowExampleAppLayout(bool* p_open) ImGui::EndMenuBar(); } - // left + // Left static int selected = 0; - ImGui::BeginChild("left pane", ImVec2(150, 0), true); - for (int i = 0; i < 100; i++) { - char label[128]; - sprintf(label, "MyObject %d", i); - if (ImGui::Selectable(label, selected == i)) - selected = i; + ImGui::BeginChild("left pane", ImVec2(150, 0), true); + for (int i = 0; i < 100; i++) + { + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i)) + selected = i; + } + ImGui::EndChild(); } - ImGui::EndChild(); ImGui::SameLine(); - // right - ImGui::BeginGroup(); + // Right + { + ImGui::BeginGroup(); ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us - ImGui::Text("MyObject: %d", selected); - ImGui::Separator(); - if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) + { + if (ImGui::BeginTabItem("Description")) { - if (ImGui::BeginTabItem("Description")) - { - ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); - ImGui::EndTabItem(); - } - if (ImGui::BeginTabItem("Details")) - { - ImGui::Text("ID: 0123456789"); - ImGui::EndTabItem(); - } - ImGui::EndTabBar(); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("Details")) + { + ImGui::Text("ID: 0123456789"); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } ImGui::EndChild(); if (ImGui::Button("Revert")) {} ImGui::SameLine(); if (ImGui::Button("Save")) {} - ImGui::EndGroup(); + ImGui::EndGroup(); + } } ImGui::End(); } @@ -4219,6 +4516,47 @@ static void ShowExampleAppLayout(bool* p_open) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- +static void ShowDummyObject(const char* prefix, int uid) +{ + // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. + ImGui::PushID(uid); + ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than framed widgets, here we add vertical spacing to make the tree lines equal high. + bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + ImGui::NextColumn(); + ImGui::AlignTextToFramePadding(); + ImGui::Text("my sailor is rich"); + ImGui::NextColumn(); + if (node_open) + { + static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); // Use field index as identifier. + if (i < 2) + { + ShowDummyObject("Child", 424242); + } + else + { + // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well) + ImGui::AlignTextToFramePadding(); + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet; + ImGui::TreeNodeEx("Field", flags, "Field_%d", i); + ImGui::NextColumn(); + ImGui::SetNextItemWidth(-1); + if (i >= 5) + ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + else + ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::NextColumn(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + // Demonstrate create a simple property editor. static void ShowExampleAppPropertyEditor(bool* p_open) { @@ -4229,57 +4567,19 @@ static void ShowExampleAppPropertyEditor(bool* p_open) return; } - 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."); + HelpMarker( + "This example shows how you may implement a property editor using two columns.\n" + "All objects/fields data are dummies here.\n" + "Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\n" + "your cursor horizontally instead of using the Columns() API."); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); ImGui::Columns(2); ImGui::Separator(); - struct funcs - { - static void ShowDummyObject(const char* prefix, int uid) - { - ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. - ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high. - bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); - ImGui::NextColumn(); - ImGui::AlignTextToFramePadding(); - ImGui::Text("my sailor is rich"); - ImGui::NextColumn(); - if (node_open) - { - static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; - for (int i = 0; i < 8; i++) - { - ImGui::PushID(i); // Use field index as identifier. - if (i < 2) - { - ShowDummyObject("Child", 424242); - } - else - { - // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well) - ImGui::AlignTextToFramePadding(); - ImGui::TreeNodeEx("Field", ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet, "Field_%d", i); - ImGui::NextColumn(); - ImGui::SetNextItemWidth(-1); - if (i >= 5) - ImGui::InputFloat("##value", &dummy_members[i], 1.0f); - else - ImGui::DragFloat("##value", &dummy_members[i], 0.01f); - ImGui::NextColumn(); - } - ImGui::PopID(); - } - ImGui::TreePop(); - } - ImGui::PopID(); - } - }; - // Iterate dummy objects with dummy members (all the same data) for (int obj_i = 0; obj_i < 3; obj_i++) - funcs::ShowDummyObject("Object", obj_i); + ShowDummyObject("Object", obj_i); ImGui::Columns(1); ImGui::Separator(); @@ -4305,7 +4605,10 @@ 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\0Multiple calls to Text(), not clipped (slow)\0"); + ImGui::Combo("Test type", &test_type, + "Single call to TextUnformatted()\0" + "Multiple calls to Text(), clipped\0" + "Multiple 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(); @@ -4359,7 +4662,10 @@ static void ShowExampleAppAutoResize(bool* p_open) } static int lines = 10; - ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop."); + ImGui::TextUnformatted( + "Window will resize every-frame to the size of its content.\n" + "Note that you probably don't want to query the window size to\n" + "output your content because that would create a feedback loop."); ImGui::SliderInt("Number of lines", &lines, 1, 20); for (int i = 0; i < lines; i++) ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally @@ -4373,12 +4679,24 @@ static void ShowExampleAppAutoResize(bool* p_open) // Demonstrate creating a window with custom resize constraints. static void ShowExampleAppConstrainedResize(bool* p_open) { - struct CustomConstraints // Helper functions to demonstrate programmatic constraints + struct CustomConstraints { + // Helper functions to demonstrate programmatic constraints static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = (data->DesiredSize.x > data->DesiredSize.y ? data->DesiredSize.x : data->DesiredSize.y); } static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } }; + const char* test_desc[] = + { + "Resize vertical only", + "Resize horizontal only", + "Width > 100, Height > 100", + "Width 400-500", + "Height 400-500", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + static bool auto_resize = false; static int type = 0; static int display_lines = 10; @@ -4393,21 +4711,11 @@ static void ShowExampleAppConstrainedResize(bool* p_open) ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0; if (ImGui::Begin("Example: Constrained Resize", p_open, flags)) { - const char* desc[] = - { - "Resize vertical only", - "Resize horizontal only", - "Width > 100, Height > 100", - "Width 400-500", - "Height 400-500", - "Custom: Always Square", - "Custom: Fixed Steps (100)", - }; 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::SetNextItemWidth(200); - ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); + ImGui::Combo("Constraint", &type, test_desc, IM_ARRAYSIZE(test_desc)); ImGui::SetNextItemWidth(200); ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100); ImGui::Checkbox("Auto-resize", &auto_resize); @@ -4421,7 +4729,8 @@ static void ShowExampleAppConstrainedResize(bool* p_open) // [SECTION] Example App: Simple Overlay / ShowExampleAppSimpleOverlay() //----------------------------------------------------------------------------- -// Demonstrate creating a simple static window with no decoration + a context-menu to choose which corner of the screen to use. +// Demonstrate creating a simple static window with no decoration +// + a context-menu to choose which corner of the screen to use. static void ShowExampleAppSimpleOverlay(bool* p_open) { const float DISTANCE = 10.0f; @@ -4434,7 +4743,10 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); } 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)) + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; + if (corner != -1) + window_flags |= ImGuiWindowFlags_NoMove; + if (ImGui::Begin("Example: Simple overlay", p_open, window_flags)) { ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)"); ImGui::Separator(); @@ -4461,7 +4773,8 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) //----------------------------------------------------------------------------- // Demonstrate using "##" and "###" in identifiers to manipulate ID generation. -// This apply to all regular items as well. Read FAQ section "How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs." for details. +// This apply to all regular items as well. +// Read FAQ section "How can I have multiple widgets with the same label?" for details. static void ShowExampleAppWindowTitles(bool*) { // By default, Windows are uniquely identified by their title. @@ -4500,10 +4813,10 @@ static void ShowExampleAppCustomRendering(bool* p_open) return; } - // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. - // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. - // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) - // In this example we are not using the maths operators! + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of + // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your + // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not + // exposed outside (to avoid messing with your types) In this example we are not using the maths operators! ImDrawList* draw_list = ImGui::GetWindowDrawList(); if (ImGui::BeginTabBar("##TabBar")) @@ -4517,17 +4830,19 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Text("Gradients"); ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); { - ImVec2 p = ImGui::GetCursorScreenPos(); + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - draw_list->AddRectFilledMultiColor(p, ImVec2(p.x + gradient_size.x, p.y + gradient_size.y), col_a, col_b, col_b, col_a); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient1", gradient_size); } { - ImVec2 p = ImGui::GetCursorScreenPos(); + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)); ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - draw_list->AddRectFilledMultiColor(p, ImVec2(p.x + gradient_size.x, p.y + gradient_size.y), col_a, col_b, col_b, col_a); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient2", gradient_size); } @@ -4598,23 +4913,25 @@ static void ShowExampleAppCustomRendering(bool* p_open) 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)); + // 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 with SetCursorPos(max). + ImVec2 canvas_p = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f; + if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f; + draw_list->AddRectFilledMultiColor(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.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_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.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); + ImGui::InvisibleButton("canvas", canvas_sz); + ImVec2 mouse_pos_global = ImGui::GetIO().MousePos; + ImVec2 mouse_pos_canvas = ImVec2(mouse_pos_global.x - canvas_p.x, mouse_pos_global.y - canvas_p.y); if (adding_line) { adding_preview = true; - points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_canvas); if (!ImGui::IsMouseDown(0)) adding_line = adding_preview = false; } @@ -4622,7 +4939,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) { if (!adding_line && ImGui::IsMouseClicked(0)) { - points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_canvas); adding_line = true; } if (ImGui::IsMouseClicked(1) && !points.empty()) @@ -4632,9 +4949,11 @@ static void ShowExampleAppCustomRendering(bool* p_open) 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.) + + // Draw all lines in the canvas (with a clipping rectangle so they don't stray out of it). + draw_list->PushClipRect(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), true); 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->AddLine(ImVec2(canvas_p.x + points[i].x, canvas_p.y + points[i].y), ImVec2(canvas_p.x + points[i + 1].x, canvas_p.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); draw_list->PopClipRect(); if (adding_preview) points.pop_back(); @@ -4672,12 +4991,12 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Simplified structure to mimic a Document model struct MyDocument { - const char* Name; // Document title - bool Open; // Set when the document is open (in this demo, we keep an array of all available documents to simplify the demo) - bool OpenPrev; // Copy of Open from last update. - bool Dirty; // Set when the document has been modified - bool WantClose; // Set when the document - ImVec4 Color; // An arbitrary variable associated to the document + const char* Name; // Document title + bool Open; // Set when open (we keep an array of all available documents to simplify demo code!) + bool OpenPrev; // Copy of Open from last update. + bool Dirty; // Set when the document has been modified + bool WantClose; // Set when the document + ImVec4 Color; // An arbitrary variable associated to the document MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f,1.0f,1.0f,1.0f)) { @@ -4741,10 +5060,11 @@ struct ExampleAppDocuments }; // [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. -// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, as opposed -// to clicking on the regular tab closing button) and stops being submitted, it will take a frame for the tab bar to notice its absence. -// During this frame there will be a gap in the tab bar, and if the tab that has disappeared was the selected one, the tab bar -// will report no selected tab during the frame. This will effectively give the impression of a flicker for one frame. +// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, +// as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for +// the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has +// disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively +// give the impression of a flicker for one frame. // We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. // Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag. static void NotifyOfDocumentsClosedElsewhere(ExampleAppDocuments& app) From 673d6df85f21e8c252bc22f4e64ed46b8423cdee Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 11:38:45 +0200 Subject: [PATCH 018/223] Demo: Clamping font scale. Added helpers in demo. Comments. Update sponsors. (#3206) --- docs/README.md | 2 +- imgui.cpp | 2 ++ imgui_demo.cpp | 34 ++++++++++++++++++++++++++-------- 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/docs/README.md b/docs/README.md index 72ebea3d..341bdcbe 100644 --- a/docs/README.md +++ b/docs/README.md @@ -194,7 +194,7 @@ Ongoing Dear ImGui development is financially supported by users and private spo - [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui/) *Double-chocolate and Salty caramel sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [DotEmu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) +- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors). diff --git a/imgui.cpp b/imgui.cpp index 86af727d..f84fb0d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6610,6 +6610,7 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() void ImGui::SetWindowFontScale(float scale) { + IM_ASSERT(scale > 0.0f); ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; @@ -6818,6 +6819,7 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() ImGuiContext& g = *GImGui; // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() + // One possible reason leading to this assert is that your back-ends update inputs _AFTER_ NewFrame(). const ImGuiKeyModFlags expected_key_mod_flags = GetMergedKeyModFlags(); IM_ASSERT(g.IO.KeyMods == expected_key_mod_flags && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(expected_key_mod_flags); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3b2ceee1..42f0844a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -114,6 +114,7 @@ Index of this file: #define IM_NEWLINE "\n" #endif +// Helpers #if defined(_MSC_VER) && !defined(snprintf) #define snprintf _snprintf #endif @@ -121,6 +122,14 @@ Index of this file: #define vsnprintf _vsnprintf #endif +// Helpers macros +// We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste, +// but making an exception here as those are largely simplifying code... +// In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo. +#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B)) +#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) +#define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V)) + //----------------------------------------------------------------------------- // [SECTION] Forward Declarations, Helpers //----------------------------------------------------------------------------- @@ -709,7 +718,7 @@ static void ShowDemoWindowWidgets() // You may retain selection state inside or outside your objects in whatever format you see fit. // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end /// of the loop. May be a pointer to your own node type, etc. - static int selection_mask = (1 << 2); + static int selection_mask = (1 << 2); int node_clicked = -1; for (int i = 0; i < 6; i++) { @@ -1294,7 +1303,7 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::Text("Progress Bar"); - float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress; + float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); char buf[32]; sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); @@ -2379,7 +2388,7 @@ static void ShowDemoWindowLayout() ImGui::AlignTextToFramePadding(); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add - // other contents below the node. + // other contents below the node. bool node_open = ImGui::TreeNode("Node##2"); ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); if (node_open) @@ -3792,11 +3801,20 @@ 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."); + // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below. + // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds). + const float MIN_SCALE = 0.3f; + const float MAX_SCALE = 2.0f; + HelpMarker( + "Those are old settings provided for convenience.\n" + "However, 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.\n" + "Using those settings here will give you poor quality results."); static float window_scale = 1.0f; - 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 + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale only this window + ImGui::SetWindowFontScale(IM_MAX(window_scale, MIN_SCALE)); + if (ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale everything + io.FontGlobalScale = IM_MAX(io.FontGlobalScale, MIN_SCALE); ImGui::PopItemWidth(); ImGui::EndTabItem(); @@ -4682,7 +4700,7 @@ static void ShowExampleAppConstrainedResize(bool* p_open) struct CustomConstraints { // Helper functions to demonstrate programmatic constraints - static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = (data->DesiredSize.x > data->DesiredSize.y ? data->DesiredSize.x : data->DesiredSize.y); } + static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y); } static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } }; From 0679e0567764d5b3362628bdf1e75c608b2a1b8b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 12:14:49 +0200 Subject: [PATCH 019/223] Internals: Added code in TempInputScalar() to clamp values, NOT used by stock Drag/Float (#3209, #1829, #946, #413) --- imgui_internal.h | 8 ++++- imgui_widgets.cpp | 80 ++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 75 insertions(+), 13 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 46cca946..f20e9d52 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -715,6 +715,11 @@ struct IMGUI_API ImRect bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } }; +struct ImGuiDataTypeTempStorage +{ + ImU8 Data[8]; // Can fit any data up to ImGuiDataType_COUNT +}; + // Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). struct ImGuiDataTypeInfo { @@ -1893,11 +1898,12 @@ namespace ImGui IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, 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* p_data, const char* format); + IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); // 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 TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 200c43e4..d1509479 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1669,6 +1669,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa // - DataTypeFormatString() // - DataTypeApplyOp() // - DataTypeApplyOpFromText() +// - DataTypeClamp() // - GetMinimumStepAtDecimalPrecision // - RoundScalarWithFormat<>() //------------------------------------------------------------------------- @@ -1820,11 +1821,9 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b return false; // 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]; - const ImGuiDataTypeInfo* type_info = ImGui::DataTypeGetInfo(data_type); - IM_ASSERT(type_info->Size <= sizeof(data_backup)); - memcpy(data_backup, p_data, type_info->Size); + const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type); + ImGuiDataTypeTempStorage data_backup; + memcpy(&data_backup, p_data, type_info->Size); if (format == NULL) format = type_info->ScanFmt; @@ -1896,7 +1895,35 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b IM_ASSERT(0); } - return memcmp(data_backup, p_data, type_info->Size) != 0; + return memcmp(&data_backup, p_data, type_info->Size) != 0; +} + +template +static bool ClampBehaviorT(T* v, T v_min, T v_max) +{ + if (*v < v_min) { *v = v_min; return true; } + if (*v > v_max) { *v = v_max; return true; } + return false; +} + +bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max) +{ + switch (data_type) + { + case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, *(const ImS8* )p_min, *(const ImS8* )p_max); + case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, *(const ImU8* )p_min, *(const ImU8* )p_max); + case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, *(const ImS16* )p_min, *(const ImS16* )p_max); + case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, *(const ImU16* )p_min, *(const ImU16* )p_max); + case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, *(const ImS32* )p_min, *(const ImS32* )p_max); + case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, *(const ImU32* )p_min, *(const ImU32* )p_max); + case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, *(const ImS64* )p_min, *(const ImS64* )p_max); + case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, *(const ImU64* )p_min, *(const ImU64* )p_max); + case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, *(const float* )p_min, *(const float* )p_max); + case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, *(const double*)p_min, *(const double*)p_max); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; } static float GetMinimumStepAtDecimalPrecision(int decimal_precision) @@ -2148,8 +2175,10 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, } } } + + // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active || temp_input_start) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -2599,8 +2628,10 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat } } } + + // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active || temp_input_start) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -2899,7 +2930,21 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* return value_changed; } -bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format) +// Note that Drag/Slider functions are currently NOT forwarding the min/max values clamping values! +// This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. +// However this may not be ideal for all uses, as some user code may break on out of bound values. +// In the future we should add flags to Slider/Drag to specify how to enforce min/max values with CTRL+Click. +// See GitHub issues #1829 and #3209 +// In the meanwhile, you can easily "wrap" those functions to enforce clamping, using wrapper functions, e.g. +// bool SliderFloatClamp(const char* label, float* v, float v_min, float v_max) +// { +// float v_backup = *v; +// if (!SliderFloat(label, v, v_min, v_max)) +// return false; +// *v = ImClamp(*v, v_min, v_max); +// return v_backup != *v; +// } +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) { ImGuiContext& g = *GImGui; @@ -2911,10 +2956,21 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); - bool value_changed = TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags); - if (value_changed) + bool value_changed = false; + if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) { - value_changed = DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL); + // Backup old value + size_t data_type_size = DataTypeGetInfo(data_type)->Size; + ImGuiDataTypeTempStorage data_backup; + memcpy(&data_backup, p_data, data_type_size); + + // Apply new value (or operations) then clamp + DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL); + if (p_clamp_min && p_clamp_max) + DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); + + // Only mark as edited if new value is different + value_changed = memcmp(&data_type, p_data, data_type_size) != 0; if (value_changed) MarkItemEdited(id); } From 510f301c9fef49b7a2194fa7795f0e70af0a1e23 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 18:58:29 +0200 Subject: [PATCH 020/223] Internals: Removed seemingly unnecessary size_on_first_use arg to CreateNewWindow(), extracted code into ApplyWindowSettings. --- docs/TODO.txt | 1 - imgui.cpp | 23 ++++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 474b5ce5..75438a6a 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -26,7 +26,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window: GetWindowSize() returns (0,0) when not calculated? (#1045) - window: investigate better auto-positioning for new windows. - window: top most window flag? (#2574) - - window: the size_on_first_use path of Begin() can probably be removed - window/size: manually triggered auto-fit (double-click on grip) shouldn't resize window down to viewport size? - 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: background options for child windows, border option (disable rounding). diff --git a/imgui.cpp b/imgui.cpp index f84fb0d2..f7f0e1b9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -908,7 +908,7 @@ static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock static void SetCurrentWindow(ImGuiWindow* window); static void FindHoveredWindow(); -static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); +static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list); @@ -4874,7 +4874,15 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name) return FindWindowByID(id); } -static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) +static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) +{ + window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y)); + if (settings->Size.x > 0 && settings->Size.y > 0) + window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y)); + window->Collapsed = settings->Collapsed; +} + +static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); @@ -4894,12 +4902,8 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl // Retrieve settings from .ini file window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); - window->Pos = ImVec2(settings->Pos.x, settings->Pos.y); - window->Collapsed = settings->Collapsed; - if (settings->Size.x > 0 && settings->Size.y > 0) - size = ImVec2(settings->Size.x, settings->Size.y); + ApplyWindowSettings(window, settings); } - window->Size = window->SizeFull = ImFloor(size); window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) @@ -5446,10 +5450,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) ImGuiWindow* window = FindWindowByName(name); const bool window_just_created = (window == NULL); 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. - window = CreateNewWindow(name, size_on_first_use, flags); - } + window = CreateNewWindow(name, flags); // Automatically disable manual moving/resizing when NoInputs is set if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) From 9ee442d3f0bc72e5172539659bfd542e6bafc9cc Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 18:00:11 +0200 Subject: [PATCH 021/223] Metrics: Added a "Settings" section with some details about persistent ini settings. InputText: Assert early on null buffer. --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 38 ++++++++++++++++++++++++++++++++++++++ imgui_widgets.cpp | 1 + 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 96cadc9b..116ee156 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,12 +50,13 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Metrics: Added a "Settings" section with some details about persistent ini settings. - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) -- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] diff --git a/imgui.cpp b/imgui.cpp index f7f0e1b9..38185fae 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10282,6 +10282,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } + static void NodeWindowSettings(ImGuiWindowSettings* settings) + { + ImGui::Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d", + settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed); + } + static void NodeTabBar(ImGuiTabBar* tab_bar) { // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. @@ -10398,6 +10404,38 @@ void ImGui::ShowMetricsWindow(bool* p_open) } #endif // #define IMGUI_HAS_DOCK + // Settings + if (ImGui::TreeNode("Settings")) + { + if (ImGui::SmallButton("Save to disk")) + ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); + ImGui::SameLine(); + if (g.IO.IniFilename) + ImGui::Text("\"%s\"", g.IO.IniFilename); + else + ImGui::TextUnformatted(""); + ImGui::Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer); + if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) + { + for (int n = 0; n < g.SettingsHandlers.Size; n++) + ImGui::TextUnformatted(g.SettingsHandlers[n].TypeName); + ImGui::TreePop(); + } + if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) + { + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + Funcs::NodeWindowSettings(settings); + ImGui::TreePop(); + } + if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) + { + char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); + ImGui::InputTextMultiline("##Ini", buf, g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + // Misc Details if (ImGui::TreeNode("Internal state")) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d1509479..71153c20 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3523,6 +3523,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (window->SkipItems) return false; + IM_ASSERT(buf != NULL && buf_size >= 0); IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) From b6a04d77500327a33a1b1de776aa67096075380b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 21:10:10 +0200 Subject: [PATCH 022/223] Settings: Added Clear Settings in Metrics. (#2188) + Preserve last loaded copy in internal buffer used for save (so it can be browsed easily). --- imgui.cpp | 56 ++++++++++++++++++++++++++++++++++++------------ imgui_internal.h | 1 + 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 38185fae..d5f6d8b3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9598,6 +9598,19 @@ void ImGui::LogButtons() //----------------------------------------------------------------------------- // [SECTION] SETTINGS //----------------------------------------------------------------------------- +// - UpdateSettings() [Internal] +// - MarkIniSettingsDirty() [Internal] +// - CreateNewWindowSettings() [Internal] +// - FindWindowSettings() [Internal] +// - FindOrCreateWindowSettings() [Internal] +// - FindSettingsHandler() [Internal] +// - ClearIniSettings() [Internal] +// - LoadIniSettingsFromDisk() +// - LoadIniSettingsFromMemory() +// - SaveIniSettingsToDisk() +// - SaveIniSettingsToMemory() +// - WindowSettingsHandler_***() [Internal] +//----------------------------------------------------------------------------- // Called by NewFrame() void ImGui::UpdateSettings() @@ -9680,16 +9693,6 @@ ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) 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); - IM_FREE(file_data); -} - ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) { ImGuiContext& g = *GImGui; @@ -9700,6 +9703,25 @@ ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) return NULL; } +void ImGui::ClearIniSettings() +{ + ImGuiContext& g = *GImGui; + g.SettingsIniData.clear(); + for (int i = 0; i != g.Windows.Size; i++) + g.Windows[i]->SettingsOffset = -1; + g.SettingsWindows.clear(); +} + +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); + IM_FREE(file_data); +} + // Zero-tolerance, no error reporting, cheap .ini parsing void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) { @@ -9711,10 +9733,11 @@ 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*)IM_ALLOC(ini_size + 1); - char* buf_end = buf + ini_size; + g.SettingsIniData.Buf.resize((int)ini_size + 1); + char* const buf = g.SettingsIniData.Buf.Data; + char* const buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); - buf[ini_size] = 0; + buf_end[0] = 0; void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; @@ -9752,8 +9775,10 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); } } - IM_FREE(buf); g.SettingsLoaded = true; + + // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) + memcpy(buf, ini_data, ini_size); } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) @@ -10407,6 +10432,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Settings if (ImGui::TreeNode("Settings")) { + if (ImGui::SmallButton("Clear")) + ImGui::ClearIniSettings(); + ImGui::SameLine(); if (ImGui::SmallButton("Save to disk")) ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); ImGui::SameLine(); diff --git a/imgui_internal.h b/imgui_internal.h index f20e9d52..67ad424a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1718,6 +1718,7 @@ namespace ImGui // Settings IMGUI_API void MarkIniSettingsDirty(); IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); + IMGUI_API void ClearIniSettings(); IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id); IMGUI_API ImGuiWindowSettings* FindOrCreateWindowSettings(const char* name); From d33021d82816a9e256301331e7ec84fd4cd7ddc2 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 21:28:17 +0200 Subject: [PATCH 023/223] Settings: Made it possible to load window .ini data mid-frame. Added clear and post-read handlers. (#2573) --- imgui.cpp | 40 ++++++++++++++++++++++++++++++++++++---- imgui_internal.h | 5 ++++- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d5f6d8b3..6fb27a5b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -917,6 +917,8 @@ static void AddWindowToSortBuffer(ImVector* out_sorted static ImRect GetViewportRect(); // Settings +static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); +static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); @@ -3941,6 +3943,8 @@ void ImGui::Initialize(ImGuiContext* context) ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Window"; ini_handler.TypeHash = ImHashStr("Window"); + ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll; + ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen; ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine; ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll; @@ -9707,9 +9711,9 @@ void ImGui::ClearIniSettings() { ImGuiContext& g = *GImGui; g.SettingsIniData.clear(); - for (int i = 0; i != g.Windows.Size; i++) - g.Windows[i]->SettingsOffset = -1; - g.SettingsWindows.clear(); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ClearAllFn) + g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]); } void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) @@ -9727,7 +9731,8 @@ 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); + //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()"); + //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.. @@ -9779,6 +9784,11 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) memcpy(buf, ini_data, ini_size); + + // Call post-read handlers + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ApplyAllFn) + g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]); } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) @@ -9814,11 +9824,33 @@ const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) return g.SettingsIniData.c_str(); } +static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Windows.Size; i++) + g.Windows[i]->SettingsOffset = -1; + g.SettingsWindows.clear(); +} + +// Apply to existing windows (if any) +static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->WantApply) + { + if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) + ApplyWindowSettings(window, settings); + settings->WantApply = false; + } +} + static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); if (!settings) settings = ImGui::CreateNewWindowSettings(name); + settings->WantApply = true; return (void*)settings; } diff --git a/imgui_internal.h b/imgui_internal.h index 67ad424a..3c209974 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -824,8 +824,9 @@ struct ImGuiWindowSettings ImVec2ih Pos; ImVec2ih Size; bool Collapsed; + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = false; } + ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = WantApply = false; } char* GetName() { return (char*)(this + 1); } }; @@ -833,6 +834,8 @@ struct ImGuiSettingsHandler { const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHashStr(TypeName) + void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) 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' From 51e568f9dc1dec33017376a6fa6a71b9ced6cda9 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 22:46:06 +0200 Subject: [PATCH 024/223] Docking: Fix to allow basic reload of non-docking .ini data (following d33021d8) + moved settings blocks --- imgui.cpp | 113 ++++++++++++++++++++++------------------------- imgui_internal.h | 2 +- 2 files changed, 55 insertions(+), 60 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 27c71337..f0e76d5a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5206,6 +5206,8 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name) static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) { + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + window->ViewportPos = main_viewport->Pos; if (settings->ViewportId) { window->ViewportId = settings->ViewportId; @@ -5217,7 +5219,6 @@ static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settin window->Collapsed = settings->Collapsed; window->DockId = settings->DockId; window->DockOrder = settings->DockOrder; - } static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) @@ -5233,6 +5234,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. ImGuiViewport* main_viewport = ImGui::GetMainViewport(); window->Pos = main_viewport->Pos + ImVec2(60, 60); + window->ViewportPos = main_viewport->Pos; // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. if (!(flags & ImGuiWindowFlags_NoSavedSettings)) @@ -5241,7 +5243,6 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) // Retrieve settings from .ini file window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); - window->ViewportPos = main_viewport->Pos; ApplyWindowSettings(window, settings); } window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values @@ -10564,8 +10565,6 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].ApplyAllFn) g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]); - - DockContextOnLoadSettings(&g); } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) @@ -10624,9 +10623,10 @@ static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandl static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { - ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); - if (!settings) - settings = ImGui::CreateNewWindowSettings(name); + ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name); + ImGuiID id = settings->ID; + *settings = ImGuiWindowSettings(); + settings->ID = id; settings->WantApply = true; return (void*)settings; } @@ -11683,6 +11683,7 @@ namespace ImGui static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count); static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id); + static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); @@ -11700,7 +11701,6 @@ namespace ImGui //----------------------------------------------------------------------------- // - DockContextInitialize() // - DockContextShutdown() -// - DockContextOnLoadSettings() // - DockContextClearNodes() // - DockContextRebuildNodes() // - DockContextUpdateUndocking() @@ -11726,6 +11726,7 @@ void ImGui::DockContextInitialize(ImGuiContext* ctx) ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Docking"; ini_handler.TypeHash = ImHashStr("Docking"); + ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; @@ -11743,13 +11744,6 @@ void ImGui::DockContextShutdown(ImGuiContext* ctx) g.DockContext = NULL; } -void ImGui::DockContextOnLoadSettings(ImGuiContext* ctx) -{ - ImGuiDockContext* dc = ctx->DockContext; - DockContextPruneUnusedSettingsNodes(ctx); - DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); -} - void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references) { IM_UNUSED(ctx); @@ -14251,6 +14245,7 @@ void ImGui::DockBuilderRemoveNode(ImGuiID node_id) DockContextRemoveNode(ctx, node, true); } +// root_id = 0 to remove all, root_id != 0 to remove child of given node. void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) { ImGuiContext* ctx = GImGui; @@ -14821,6 +14816,7 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) // - DockSettingsRenameNodeReferences() // - DockSettingsRemoveNodeReferences() // - DockSettingsFindNodeSettings() +// - DockSettingsHandler_ApplyAll() // - DockSettingsHandler_ReadOpen() // - DockSettingsHandler_ReadLine() // - DockSettingsHandler_DockNodeToSettings() @@ -14871,6 +14867,15 @@ static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* return NULL; } +static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + // Prune settings at boot time only + ImGuiDockContext* dc = ctx->DockContext; + if (ctx->Windows.Size == 0) + DockContextPruneUnusedSettingsNodes(ctx); + DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); +} + static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { if (strcmp(name, "Data") != 0) @@ -15690,52 +15695,17 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Details for Docking #ifdef IMGUI_HAS_DOCK - if (ImGui::TreeNode("Docking")) + if (ImGui::TreeNode("Dock nodes")) { ImGuiDockContext* dc = g.DockContext; ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes); - - 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 (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) - if (settings->DockId != 0) - ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->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->SelectedWindowId) - { - if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowId)) - selected_tab_name = window->Name; - else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowId)) - selected_tab_name = window_settings->GetName(); - } - 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(); - } + if (ImGui::SmallButton("Clear nodes")) { 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(); } #endif // #define IMGUI_HAS_DOCK @@ -15746,6 +15716,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear")) ImGui::ClearIniSettings(); ImGui::SameLine(); + if (ImGui::SmallButton("Save to memory")) + ImGui::SaveIniSettingsToMemory(); + ImGui::SameLine(); if (ImGui::SmallButton("Save to disk")) ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); ImGui::SameLine(); @@ -15757,7 +15730,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) { for (int n = 0; n < g.SettingsHandlers.Size; n++) - ImGui::TextUnformatted(g.SettingsHandlers[n].TypeName); + ImGui::BulletText("%s", g.SettingsHandlers[n].TypeName); ImGui::TreePop(); } if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) @@ -15766,6 +15739,28 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeWindowSettings(settings); ImGui::TreePop(); } + if (ImGui::TreeNode("SettingsDocking", "Settings packed data: Docking")) + { + ImGui::Text("In SettingsWindows:"); + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId != 0) + ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId); + ImGui::Text("In SettingsNodes:"); + for (int n = 0; n < g.DockContext->SettingsNodes.Size; n++) + { + ImGuiDockNodeSettings* settings = &g.DockContext->SettingsNodes[n]; + const char* selected_tab_name = NULL; + if (settings->SelectedWindowId) + { + if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowId)) + selected_tab_name = window->Name; + else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowId)) + selected_tab_name = window_settings->GetName(); + } + 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(); + } if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); diff --git a/imgui_internal.h b/imgui_internal.h index a3b76688..2f43e9b5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2058,7 +2058,7 @@ namespace ImGui 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 DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the remaining root node (node_id). 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_at_dir, ImGuiID* out_id_at_opposite_dir); // Create 2 child nodes in this parent node. From 574ff0a280d09b5115c489f5e204ba1af13c9c0a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 23:28:29 +0200 Subject: [PATCH 025/223] Docking, Settings: Allow reload of settings data at runtime. (#2573) --- imgui.cpp | 24 ++++++++++++++++++++++-- imgui_internal.h | 3 ++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f0e76d5a..08090188 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10520,6 +10520,12 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) memcpy(buf, ini_data, ini_size); buf_end[0] = 0; + // Call pre-read handlers + // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ReadInitFn) + g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]); + void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; @@ -11683,6 +11689,7 @@ namespace ImGui static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count); static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id); + static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); @@ -11726,9 +11733,11 @@ void ImGui::DockContextInitialize(ImGuiContext* ctx) ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Docking"; ini_handler.TypeHash = ImHashStr("Docking"); - ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; + ini_handler.ClearAllFn = DockSettingsHandler_ClearAll; + ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; g.SettingsHandlers.push_back(ini_handler); } @@ -11752,7 +11761,8 @@ void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear DockBuilderRemoveNodeChildNodes(root_id); } -// This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) { IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); @@ -14867,6 +14877,15 @@ static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* return NULL; } +// Clear settings data +static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiDockContext* dc = ctx->DockContext; + dc->SettingsNodes.clear(); + DockContextClearNodes(ctx, 0, true); +} + +// Recreate dones based on settings data static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { // Prune settings at boot time only @@ -14874,6 +14893,7 @@ static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettings if (ctx->Windows.Size == 0) DockContextPruneUnusedSettingsNodes(ctx); DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); + DockContextBuildAddWindowsToNodes(ctx, 0); } static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) diff --git a/imgui_internal.h b/imgui_internal.h index 2f43e9b5..bf443573 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -855,9 +855,10 @@ struct ImGuiSettingsHandler const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHashStr(TypeName) void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data - void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) + void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order) 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 (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' void* UserData; From 53ebd6a02f92390e402edbc1ebaf445432066e08 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 23:51:47 +0200 Subject: [PATCH 026/223] Metrics: Added Table settings block. --- imgui.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 6fb27a5b..14be81f6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10487,6 +10487,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeWindowSettings(settings); ImGui::TreePop(); } +#ifdef IMGUI_HAS_TABLE + if (ImGui::TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) + { + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + Funcs::NodeTableSettings(settings); + ImGui::TreePop(); + } +#endif if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); From c0d5b3f55a977fb3909bd80d90018a47fa5b0191 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 23:58:35 +0200 Subject: [PATCH 027/223] Fix to facilitate branch merges --- imgui.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 14be81f6..97950b63 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10487,6 +10487,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeWindowSettings(settings); ImGui::TreePop(); } + #ifdef IMGUI_HAS_TABLE if (ImGui::TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) { @@ -10495,6 +10496,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } #endif + +#ifdef IMGUI_HAS_DOCK +#endif + if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); From 3aa1684129646a7ad688d13139688beea70f27a3 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 15:59:39 +0200 Subject: [PATCH 028/223] Comments --- imgui.cpp | 9 ++++---- imgui_internal.h | 56 +++++++++++++++++++++++++----------------------- 2 files changed, 34 insertions(+), 31 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 97950b63..11d9a79d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4281,7 +4281,7 @@ void ImGui::Render() // Add ImDrawList to render 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.NavWindowingListWindow : NULL); for (int n = 0; n != g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; @@ -5590,7 +5590,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // 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; - if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB + if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB window_title_visible_elsewhere = true; if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) { @@ -6628,6 +6628,7 @@ void ImGui::ActivateItem(ImGuiID id) g.NavNextActivateId = id; } +// Note: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there. void ImGui::PushFocusScope(ImGuiID id) { ImGuiContext& g = *GImGui; @@ -9067,8 +9068,8 @@ void ImGui::NavUpdateWindowingOverlay() if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) return; - if (g.NavWindowingList == NULL) - g.NavWindowingList = FindWindowByName("###NavWindowingList"); + if (g.NavWindowingListWindow == NULL) + g.NavWindowingListWindow = FindWindowByName("###NavWindowingList"); SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 3c209974..5a1fa677 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -14,9 +14,9 @@ Index of this file: // STB libraries includes // Context pointer // Generic helpers -// Misc data structures +// Flags, enums and data structures // Main imgui context -// Tab bar, tab item +// Tab bar, Tab item // Internal API */ @@ -431,7 +431,7 @@ struct IMGUI_API ImChunkStream }; //----------------------------------------------------------------------------- -// Misc data structures +// Flags, enums and data structures //----------------------------------------------------------------------------- enum ImGuiButtonFlags_ @@ -1011,7 +1011,7 @@ struct ImGuiNextItemData }; //----------------------------------------------------------------------------- -// Tabs +// Tab bar, Tab item //----------------------------------------------------------------------------- struct ImGuiShrinkWidthItem @@ -1111,7 +1111,7 @@ struct ImGuiContext // Gamepad/keyboard Navigation ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow' ImGuiID NavId; // Focused item for navigation - ImGuiID NavFocusScopeId; + ImGuiID NavFocusScopeId; // Identify a selection scope (selection code often wants to "clear other items" when landing on an item of the selection set) ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem() ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0 ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0 @@ -1133,8 +1133,8 @@ struct ImGuiContext bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest bool NavInitRequest; // Init request for appearing window to select first item bool NavInitRequestFromMove; - ImGuiID NavInitResultId; - ImRect NavInitResultRectRel; + ImGuiID NavInitResultId; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) + ImRect NavInitResultRectRel; // Init request result rectangle (relative to parent window) bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items bool NavMoveRequest; // Move request for this frame ImGuiNavMoveFlags NavMoveRequestFlags; @@ -1146,10 +1146,10 @@ 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) - // Navigation: Windowing (CTRL+TAB, holding Menu button + directional pads to move/resize) - 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; + // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) + ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! + ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. + ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents float NavWindowingTimer; float NavWindowingHighlightAlpha; bool NavWindowingToggleLayer; @@ -1226,8 +1226,8 @@ struct ImGuiContext ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries // Capture/Logging - bool LogEnabled; - ImGuiLogType LogType; + bool LogEnabled; // Currently capturing + ImGuiLogType LogType; // Capture target ImFileHandle 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; @@ -1237,7 +1237,7 @@ struct ImGuiContext int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. // Debug Tools - bool DebugItemPickerActive; + bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker()) ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this id // Misc @@ -1322,7 +1322,7 @@ struct ImGuiContext NavMoveRequestKeyMods = ImGuiKeyModFlags_None; NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; - NavWindowingTarget = NavWindowingTargetAnim = NavWindowingList = NULL; + NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; NavWindowingToggleLayer = false; @@ -1563,8 +1563,8 @@ 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; + bool MemoryCompacted; // Set when window extraneous data have been garbage collected + int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy int MemoryDrawListVtxCapacity; public: @@ -1736,7 +1736,7 @@ namespace ImGui IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect); // Basic Accessors - inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } + inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } // Get ID of last item (~~ often same ImGui::GetID(label) beforehand) inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemStatusFlags; } inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } @@ -1747,7 +1747,7 @@ namespace ImGui IMGUI_API void SetHoveredID(ImGuiID id); IMGUI_API void KeepAliveID(ImGuiID id); IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function. - IMGUI_API void PushOverrideID(ImGuiID id); // Push given value at the top of the ID stack (whereas PushID combines old and new hashes) + IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes) // Basic Helpers for widget code IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f); @@ -1762,27 +1762,27 @@ 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 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 - 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 + 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 bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags); IMGUI_API void OpenPopupEx(ImGuiID id); 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 IsPopupOpen(ImGuiID id); // Test for id at 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, ImGuiTooltipFlags tooltip_flags); 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); - // Navigation + // Gamepad/Keyboard Navigation IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); IMGUI_API bool NavMoveRequestButNoResultYet(); IMGUI_API void NavMoveRequestCancel(); @@ -1795,8 +1795,10 @@ namespace ImGui IMGUI_API void SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id); IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel); - // Focus scope (WIP) - IMGUI_API void PushFocusScope(ImGuiID id); // Note: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there. + // Focus Scope (WIP) + // This is generally used to identify a selection set (multiple of which may be in the same window), as selection + // patterns generally need to react (e.g. clear selection) when landing on an item of the set. + IMGUI_API void PushFocusScope(ImGuiID id); IMGUI_API void PopFocusScope(); inline ImGuiID GetFocusScopeID() { ImGuiContext& g = *GImGui; return g.NavFocusScopeId; } @@ -1816,7 +1818,7 @@ namespace ImGui IMGUI_API void ClearDragDrop(); IMGUI_API bool IsDragDropPayloadBeingAccepted(); - // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables api) + // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) 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); From f466cfc2caa4851ab6c99df825ea04eedabfc91f Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 16:21:00 +0200 Subject: [PATCH 029/223] Internals: shuffling some sections, added index. --- imgui_internal.h | 396 +++++++++++++++++++++++++---------------------- 1 file changed, 208 insertions(+), 188 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5a1fa677..5e8d063b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -9,15 +9,21 @@ /* Index of this file: -// Header mess -// Forward declarations -// STB libraries includes -// Context pointer -// Generic helpers -// Flags, enums and data structures -// Main imgui context -// Tab bar, Tab item -// Internal API + +// [SECTION] Header mess +// [SECTION] Forward declarations +// [SECTION] Context pointer +// [SECTION] STB libraries includes +// [SECTION] Macros +// [SECTION] Generic helpers +// [SECTION] ImDrawList support +// [SECTION] Misc flags, enums and data structures +// [SECTION] Settings support +// [SECTION] ImGuiContext (main imgui context) +// [SECTION] ImGuiWindowTempData, ImGuiWindow +// [SECTION] Tab bar, Tab item +// [SECTION] Internal API +// [SECTION] Test Engine Hooks (imgui_test_engine) */ @@ -25,7 +31,7 @@ Index of this file: #ifndef IMGUI_DISABLE //----------------------------------------------------------------------------- -// Header mess +// [SECTION] Header mess //----------------------------------------------------------------------------- #ifndef IMGUI_VERSION @@ -46,8 +52,8 @@ Index of this file: // 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" @@ -57,20 +63,20 @@ Index of this file: #endif #elif defined(__GNUC__) #pragma GCC diagnostic push -#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 +#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 // Legacy defines -#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 +#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 #error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS #endif -#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 +#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 #error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS #endif //----------------------------------------------------------------------------- -// Forward declarations +// [SECTION] Forward declarations //----------------------------------------------------------------------------- struct ImBitVector; // Store 1-bit per value @@ -115,8 +121,17 @@ typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // F typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() +//----------------------------------------------------------------------------- +// [SECTION] Context pointer +// See implementation of this variable in imgui.cpp for comments and details. +//----------------------------------------------------------------------------- + +#ifndef GImGui +extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer +#endif + //------------------------------------------------------------------------- -// STB libraries includes +// [SECTION] STB libraries includes //------------------------------------------------------------------------- namespace ImStb @@ -134,15 +149,7 @@ namespace ImStb } // namespace ImStb //----------------------------------------------------------------------------- -// Context pointer -//----------------------------------------------------------------------------- - -#ifndef GImGui -extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer -#endif - -//----------------------------------------------------------------------------- -// Macros +// [SECTION] Macros //----------------------------------------------------------------------------- // Debug Logging @@ -192,32 +199,50 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IMGUI_CDECL #endif +// 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 + //----------------------------------------------------------------------------- -// Generic helpers +// [SECTION] Generic helpers // Note that the ImXXX helpers functions are lower-level than ImGui functions. // ImGui functions or the ImGui context are never called/used from other ImXXX functions. //----------------------------------------------------------------------------- -// - Helpers: Misc +// - Helpers: Hashing +// - Helpers: Sorting // - Helpers: Bit manipulation // - Helpers: String, Formatting // - Helpers: UTF-8 <> wchar conversions // - Helpers: ImVec2/ImVec4 operators // - Helpers: Maths // - Helpers: Geometry -// - Helpers: Bit arrays +// - Helper: ImVec1 +// - Helper: ImVec2ih +// - Helper: ImRect +// - Helper: ImBitArray // - Helper: ImBitVector // - Helper: ImPool<> // - Helper: ImChunkStream<> //----------------------------------------------------------------------------- -// Helpers: Misc -#define ImQsort qsort +// Helpers: Hashing 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 = 0, ImU32 seed = 0); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS static inline ImU32 ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68] #endif +// Helpers: Sorting +#define ImQsort qsort + // Helpers: Color Blending IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); @@ -286,7 +311,6 @@ static inline ImU64 ImFileGetSize(ImFileHandle) static inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } static inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; } #endif - #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef FILE* ImFileHandle; IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode); @@ -354,7 +378,61 @@ IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& inline float ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; } IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy); -// Helpers: Bit arrays +// Helper: ImVec1 (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; } +}; + +// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) +struct ImVec2ih +{ + short x, 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; } +}; + +// Helper: ImRect (2D axis aligned bounding-box) +// NB: we can't rely on ImVec2 math operators being available here! +struct IMGUI_API ImRect +{ + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right + + ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} + ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} + ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} + ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} + + ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); } + float GetWidth() const { return Max.x - Min.x; } + float GetHeight() const { return Max.y - Min.y; } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } + void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } + void TranslateX(float dx) { Min.x += dx; Max.x += dx; } + void TranslateY(float dy) { Min.y += dy; Max.y += dy; } + void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. + void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. + void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } + bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } +}; + +// Helper: ImBitArray inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; } inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; } inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; } @@ -431,7 +509,50 @@ struct IMGUI_API ImChunkStream }; //----------------------------------------------------------------------------- -// Flags, enums and data structures +// [SECTION] ImDrawList support +//----------------------------------------------------------------------------- + +// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 12 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp((int)((IM_PI * 2.0f) / ImAcos(((_RAD) - (_MAXERROR)) / (_RAD))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) + +// ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path. +#ifndef IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER +#define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 +#endif + +// Data shared between all ImDrawList instances +// You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. +struct IMGUI_API ImDrawListSharedData +{ + ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas + ImFont* Font; // Current/default font (optional, for simplified AddText overload) + float FontSize; // Current/default font size (optional, for simplified AddText overload) + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() + float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc + 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) + + // [Internal] Lookup tables + ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas + ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) + + ImDrawListSharedData(); + void SetCircleSegmentMaxError(float max_error); +}; + +struct ImDrawDataBuilder +{ + ImVector Layers[2]; // Global layers for: regular, tooltip + + void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); } + void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); } + IMGUI_API void FlattenIntoSingleLayer(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Misc flags, enums and data structures //----------------------------------------------------------------------------- enum ImGuiButtonFlags_ @@ -662,59 +783,6 @@ 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 vector (half-size integer) -struct ImVec2ih -{ - short x, 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 -// NB: we can't rely on ImVec2 math operators being available here -struct IMGUI_API ImRect -{ - ImVec2 Min; // Upper-left - ImVec2 Max; // Lower-right - - ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} - ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} - ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} - ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} - - ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); } - ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); } - float GetWidth() const { return Max.x - Min.x; } - float GetHeight() const { return Max.y - Min.y; } - ImVec2 GetTL() const { return Min; } // Top-left - ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right - ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left - ImVec2 GetBR() const { return Max; } // Bottom-right - bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } - bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } - bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } - void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } - void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } - void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } - void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } - void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } - void TranslateX(float dx) { Min.x += dx; Max.x += dx; } - void TranslateY(float dy) { Min.y += dy; Max.y += dy; } - void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. - void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. - void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } - bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } -}; - struct ImGuiDataTypeTempStorage { ImU8 Data[8]; // Can fit any data up to ImGuiDataType_COUNT @@ -815,35 +883,6 @@ struct IMGUI_API ImGuiInputTextState void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } }; -// Windows data saved in imgui.ini file -// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. -// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) -struct ImGuiWindowSettings -{ - ImGuiID ID; - ImVec2ih Pos; - ImVec2ih Size; - bool Collapsed; - bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - - ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = WantApply = false; } - char* GetName() { return (char*)(this + 1); } -}; - -struct ImGuiSettingsHandler -{ - const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' - ImGuiID TypeHash; // == ImHashStr(TypeName) - void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data - void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) - 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' - void* UserData; - - ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } -}; - // Storage for current popup stack struct ImGuiPopupData { @@ -902,45 +941,6 @@ struct ImGuiColumns } }; -// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 12 -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp((int)((IM_PI * 2.0f) / ImAcos(((_RAD) - (_MAXERROR)) / (_RAD))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) - -// ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path. -#ifndef IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER -#define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 -#endif - -// Data shared between all ImDrawList instances -// You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. -struct IMGUI_API ImDrawListSharedData -{ - ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas - ImFont* Font; // Current/default font (optional, for simplified AddText overload) - float FontSize; // Current/default font size (optional, for simplified AddText overload) - float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() - float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc - 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) - - // [Internal] Lookup tables - ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas - ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) - - ImDrawListSharedData(); - void SetCircleSegmentMaxError(float max_error); -}; - -struct ImDrawDataBuilder -{ - ImVector Layers[2]; // Global layers for: regular, tooltip - - void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); } - void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); } - IMGUI_API void FlattenIntoSingleLayer(); -}; - struct ImGuiNavMoveResult { ImGuiWindow* Window; // Best candidate window @@ -1010,27 +1010,56 @@ struct ImGuiNextItemData inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; } // Also cleared manually by ItemAdd()! }; +struct ImGuiShrinkWidthItem +{ + int Index; + float Width; +}; + +struct ImGuiPtrOrIndex +{ + 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. + + ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } + ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } +}; + //----------------------------------------------------------------------------- -// Tab bar, Tab item +// [SECTION] Settings support //----------------------------------------------------------------------------- -struct ImGuiShrinkWidthItem +// Windows data saved in imgui.ini file +// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. +// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) +struct ImGuiWindowSettings { - int Index; - float Width; + ImGuiID ID; + ImVec2ih Pos; + ImVec2ih Size; + bool Collapsed; + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + + ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = WantApply = false; } + char* GetName() { return (char*)(this + 1); } }; -struct ImGuiPtrOrIndex +struct ImGuiSettingsHandler { - 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. + const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' + ImGuiID TypeHash; // == ImHashStr(TypeName) + void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) + 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' + void* UserData; - ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } - ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } + ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- -// Main Dear ImGui context +// [SECTION] ImGuiContext (main imgui context) //----------------------------------------------------------------------------- struct ImGuiContext @@ -1386,7 +1415,7 @@ struct ImGuiContext }; //----------------------------------------------------------------------------- -// ImGuiWindow +// [SECTION] ImGuiWindowTempData, 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. @@ -1580,12 +1609,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 { 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()); } + 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. @@ -1602,7 +1631,7 @@ struct ImGuiItemHoveredDataBackup }; //----------------------------------------------------------------------------- -// Tab bar, tab item +// [SECTION] Tab bar, Tab item //----------------------------------------------------------------------------- // Extend ImGuiTabBarFlags_ @@ -1672,8 +1701,8 @@ struct ImGuiTabBar }; //----------------------------------------------------------------------------- -// Internal API -// No guarantee of forward compatibility here. +// [SECTION] Internal API +// No guarantee of forward compatibility here! //----------------------------------------------------------------------------- namespace ImGui @@ -1944,19 +1973,10 @@ 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); -// 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 +//----------------------------------------------------------------------------- +// [SECTION] Test Engine Hooks (imgui_test_engine) +//----------------------------------------------------------------------------- -// Test Engine Hooks (imgui_tests) //#define IMGUI_ENABLE_TEST_ENGINE #ifdef IMGUI_ENABLE_TEST_ENGINE extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); From 5f752a5ba9e835e681015375fbbb99262036eec6 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 16:30:14 +0200 Subject: [PATCH 030/223] Internals: shuffling some sections (2) --- imgui_internal.h | 191 ++++++++++++++++++++++++----------------------- 1 file changed, 98 insertions(+), 93 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5e8d063b..ca9518c5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -17,7 +17,8 @@ Index of this file: // [SECTION] Macros // [SECTION] Generic helpers // [SECTION] ImDrawList support -// [SECTION] Misc flags, enums and data structures +// [SECTION] Widgets support: flags, enums, data structures +// [SECTION] Columns support // [SECTION] Settings support // [SECTION] ImGuiContext (main imgui context) // [SECTION] ImGuiWindowTempData, ImGuiWindow @@ -552,9 +553,45 @@ struct ImDrawDataBuilder }; //----------------------------------------------------------------------------- -// [SECTION] Misc flags, enums and data structures +// [SECTION] Widgets support: flags, enums, data structures //----------------------------------------------------------------------------- +// 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_None = 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_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 +}; + +// Storage for LastItem data +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_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_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. + ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. + ImGuiItemStatusFlags_Deactivated = 1 << 6 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. + +#ifdef IMGUI_ENABLE_TEST_ENGINE + , // [imgui_tests only] + ImGuiItemStatusFlags_Openable = 1 << 10, // + ImGuiItemStatusFlags_Opened = 1 << 11, // + ImGuiItemStatusFlags_Checkable = 1 << 12, // + ImGuiItemStatusFlags_Checked = 1 << 13 // +#endif +}; + enum ImGuiButtonFlags_ { ImGuiButtonFlags_None = 0, @@ -597,17 +634,6 @@ enum ImGuiDragFlags_ ImGuiDragFlags_Vertical = 1 << 0 }; -enum ImGuiColumnsFlags_ -{ - // Default: 0 - ImGuiColumnsFlags_None = 0, - ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers - ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers - ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns - ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window - 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_ { @@ -634,42 +660,6 @@ enum ImGuiSeparatorFlags_ ImGuiSeparatorFlags_SpanAllColumns = 1 << 2 }; -// 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_None = 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_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 -}; - -// Storage for LastItem data -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_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_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. - ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. - ImGuiItemStatusFlags_Deactivated = 1 << 6 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. - -#ifdef IMGUI_ENABLE_TEST_ENGINE - , // [imgui_tests only] - ImGuiItemStatusFlags_Openable = 1 << 10, // - ImGuiItemStatusFlags_Opened = 1 << 11, // - ImGuiItemStatusFlags_Checkable = 1 << 12, // - ImGuiItemStatusFlags_Checked = 1 << 13 // -#endif -}; - enum ImGuiTextFlags_ { ImGuiTextFlags_None = 0, @@ -897,50 +887,6 @@ struct ImGuiPopupData ImGuiPopupData() { PopupId = 0; Window = SourceWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; } }; -struct ImGuiColumnData -{ - float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) - float OffsetNormBeforeResize; - ImGuiColumnsFlags Flags; // Not exposed - ImRect ClipRect; - - ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; } -}; - -struct ImGuiColumns -{ - ImGuiID ID; - ImGuiColumnsFlags Flags; - bool IsFirstFrame; - bool IsBeingResized; - int Current; - int Count; - float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x - float LineMinY, LineMaxY; - 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; - ImDrawListSplitter Splitter; - - ImGuiColumns() { Clear(); } - void Clear() - { - ID = 0; - Flags = ImGuiColumnsFlags_None; - IsFirstFrame = false; - IsBeingResized = false; - Current = 0; - Count = 1; - OffMinX = OffMaxX = 0.0f; - LineMinY = LineMaxY = 0.0f; - HostCursorPosY = 0.0f; - HostCursorMaxPosX = 0.0f; - Columns.clear(); - } -}; - struct ImGuiNavMoveResult { ImGuiWindow* Window; // Best candidate window @@ -1025,6 +971,65 @@ struct ImGuiPtrOrIndex ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } }; +//----------------------------------------------------------------------------- +// [SECTION] Columns support +//----------------------------------------------------------------------------- + +enum ImGuiColumnsFlags_ +{ + // Default: 0 + ImGuiColumnsFlags_None = 0, + ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers + ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers + ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns + ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window + 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. +}; + +struct ImGuiColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + float OffsetNormBeforeResize; + ImGuiColumnsFlags Flags; // Not exposed + ImRect ClipRect; + + ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; } +}; + +struct ImGuiColumns +{ + ImGuiID ID; + ImGuiColumnsFlags Flags; + bool IsFirstFrame; + bool IsBeingResized; + int Current; + int Count; + float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x + float LineMinY, LineMaxY; + 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; + ImDrawListSplitter Splitter; + + ImGuiColumns() { Clear(); } + void Clear() + { + ID = 0; + Flags = ImGuiColumnsFlags_None; + IsFirstFrame = false; + IsBeingResized = false; + Current = 0; + Count = 1; + OffMinX = OffMaxX = 0.0f; + LineMinY = LineMaxY = 0.0f; + HostCursorPosY = 0.0f; + HostCursorMaxPosX = 0.0f; + Columns.clear(); + } +}; + //----------------------------------------------------------------------------- // [SECTION] Settings support //----------------------------------------------------------------------------- From 4f33dd15c4e28d161de406c18f2ebea649ba6b7d Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 16:55:37 +0200 Subject: [PATCH 031/223] Internals: stand-in for large branches to facilitate merging. --- imgui_internal.h | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ca9518c5..1fcd64de 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -20,9 +20,13 @@ Index of this file: // [SECTION] Widgets support: flags, enums, data structures // [SECTION] Columns support // [SECTION] Settings support +// [SECTION] Multi-select support +// [SECTION] Docking support +// [SECTION] Viewport support // [SECTION] ImGuiContext (main imgui context) // [SECTION] ImGuiWindowTempData, ImGuiWindow -// [SECTION] Tab bar, Tab item +// [SECTION] Tab bar, Tab item support +// [SECTION] Table support // [SECTION] Internal API // [SECTION] Test Engine Hooks (imgui_test_engine) @@ -1030,6 +1034,30 @@ struct ImGuiColumns } }; +//----------------------------------------------------------------------------- +// [SECTION] Multi-select support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_MULTI_SELECT +// +#endif // #ifdef IMGUI_HAS_MULTI_SELECT + +//----------------------------------------------------------------------------- +// [SECTION] Docking support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_DOCK +// +#endif // #ifdef IMGUI_HAS_DOCK + +//----------------------------------------------------------------------------- +// [SECTION] Viewport support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_VIEWPORT +// +#endif // #ifdef IMGUI_HAS_VIEWPORT + //----------------------------------------------------------------------------- // [SECTION] Settings support //----------------------------------------------------------------------------- @@ -1636,7 +1664,7 @@ struct ImGuiItemHoveredDataBackup }; //----------------------------------------------------------------------------- -// [SECTION] Tab bar, Tab item +// [SECTION] Tab bar, Tab item support //----------------------------------------------------------------------------- // Extend ImGuiTabBarFlags_ @@ -1705,6 +1733,14 @@ struct ImGuiTabBar } }; +//----------------------------------------------------------------------------- +// [SECTION] Table support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_TABLE +// +#endif // #ifdef IMGUI_HAS_TABLE + //----------------------------------------------------------------------------- // [SECTION] Internal API // No guarantee of forward compatibility here! From 1e7672acf46a81e36b3cf35734c015326dd97d58 Mon Sep 17 00:00:00 2001 From: Ivan Zinkevich Date: Thu, 7 May 2020 23:50:51 +0300 Subject: [PATCH 032/223] Backends: DX12: Fixed OBJECT_DELETED_WHILE_STILL_IN_USE on viewport resizing. (#3210) Tested with detaching/attaching a viewport and resizing it. DX12 debug layer is clean. --- examples/imgui_impl_dx12.cpp | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index bbe026e4..b10e8c65 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -846,22 +846,26 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) } } +static void ImGui_WaitForPendingOperations(ImGuiViewportDataDx12* data) +{ + HRESULT hr = S_FALSE; + if (data && data->CommandQueue && data->Fence && data->FenceEvent) + { + hr = data->CommandQueue->Signal(data->Fence, ++data->FenceSignaledValue); + IM_ASSERT(hr == S_OK); + ::WaitForSingleObject(data->FenceEvent, 0); // Reset any forgotten waits + hr = data->Fence->SetEventOnCompletion(data->FenceSignaledValue, data->FenceEvent); + IM_ASSERT(hr == S_OK); + ::WaitForSingleObject(data->FenceEvent, INFINITE); + } +} + static void ImGui_ImplDX12_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 (ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)viewport->RendererUserData) { - // Wait for pending operations to complete to safely release objects below - HRESULT hr; - if (data->CommandQueue && data->Fence && data->FenceEvent) - { - hr = data->CommandQueue->Signal(data->Fence, ++data->FenceSignaledValue); - IM_ASSERT(hr == S_OK); - ::WaitForSingleObject(data->FenceEvent, 0); // Reset any forgotten waits - hr = data->Fence->SetEventOnCompletion(data->FenceSignaledValue, data->FenceEvent); - IM_ASSERT(hr == S_OK); - ::WaitForSingleObject(data->FenceEvent, INFINITE); - } + ImGui_WaitForPendingOperations(data); SafeRelease(data->CommandQueue); SafeRelease(data->CommandList); @@ -887,6 +891,8 @@ static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) { ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)viewport->RendererUserData; + ImGui_WaitForPendingOperations(data); + for (UINT i = 0; i < g_numFramesInFlight; i++) SafeRelease(data->FrameCtx[i].RenderTarget); From 685ca27d84e59e1ecf520e4984bce027a0579ac6 Mon Sep 17 00:00:00 2001 From: Albert Vaca Date: Fri, 8 May 2020 17:29:14 +0200 Subject: [PATCH 033/223] Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_opengl3.cpp | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 116ee156..0b549802 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,7 @@ Other Changes: - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] +- Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) [@albertvaka] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index c60df73d..61131eb6 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader. @@ -184,6 +185,9 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) #elif defined(IMGUI_IMPL_OPENGL_ES3) if (glsl_version == NULL) glsl_version = "#version 300 es"; +#elif defined(__APPLE__) + if (glsl_version == NULL) + glsl_version = "#version 150"; #else if (glsl_version == NULL) glsl_version = "#version 130"; From 7b3d379819c487f0d5323ed7bd7c9109a2bc1d76 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 18:36:05 +0200 Subject: [PATCH 034/223] FocusWindow(NULL) correctly steal active id from previous window. (#1738) amend b0a9bbf6 --- imgui.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 11d9a79d..715b5dbb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6161,19 +6161,18 @@ void ImGui::FocusWindow(ImGuiWindow* window) // Close popups if any ClosePopupsOverWindow(window, false); - // Passing NULL allow to disable keyboard focus - if (!window) - return; - // Move the root window to the top of the pile - IM_ASSERT(window->RootWindow != NULL); - ImGuiWindow* focus_front_window = window->RootWindow; // NB: In docking branch this is window->RootWindowDockStop - ImGuiWindow* display_front_window = window->RootWindow; + IM_ASSERT(window == NULL || window->RootWindow != NULL); + ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop + ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; // Steal focus on active widgets - if (focus_front_window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement may be unnecessary? Need further testing before removing it.. - if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) - ClearActiveID(); + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) + ClearActiveID(); + + // Passing NULL allow to disable keyboard focus + if (!window) + return; // Bring to front BringWindowToFocusFront(focus_front_window); From a6f4b0fd70150a7cbde03e99fda09ef7b2bfb6d6 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 11 May 2020 13:58:40 +0300 Subject: [PATCH 035/223] Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) First call to EndPopup() called NavRequestTryWrapWindow() which performed wrap-around operation while we were not done composing menu. This resulted in navigation wrapping around to first item. Since wrap-around operation is only valid in last call to EndPopup() and there is no way to know which call is last - this operation is delayed to the end of the frame. --- docs/CHANGELOG.txt | 2 + imgui.cpp | 106 +++++++++++++++++++++++++++++++-------------- imgui_internal.h | 4 ++ 3 files changed, 79 insertions(+), 33 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0b549802..ebd6f735 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,8 @@ Other Changes: Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). - Metrics: Added a "Settings" section with some details about persistent ini settings. +- Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to + BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the diff --git a/imgui.cpp b/imgui.cpp index 715b5dbb..deb7e981 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -937,6 +937,7 @@ static void NavUpdateWindowingOverlay(); static void NavUpdateMoveResult(); static float NavUpdatePageUpPageDown(); static inline void NavUpdateAnyRequestFlag(); +static void NavEndFrame(); static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand); static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id); static ImVec2 NavCalcPreferredRefPos(); @@ -4209,9 +4210,8 @@ void ImGui::EndFrame() g.CurrentWindow->Active = false; End(); - // Show CTRL+TAB list window - if (g.NavWindowingTarget != NULL) - NavUpdateWindowingOverlay(); + // Update navigation: CTRL+Tab, wrap-around requests + NavEndFrame(); // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) if (g.DragDropActive) @@ -7819,7 +7819,8 @@ void ImGui::EndPopup() IM_ASSERT(g.BeginPopupStack.Size > 0); // Make all menus and popups wrap around for now, may need to expose that policy. - NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); + if (g.NavWindow == window) + NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); // Child-popups don't need to be laid out IM_ASSERT(g.WithinEndChild == false); @@ -8298,36 +8299,11 @@ void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const Im void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags) { ImGuiContext& g = *GImGui; - if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != ImGuiNavLayer_Main) - return; - IM_ASSERT(move_flags != 0); // No points calling this with no wrapping - ImRect bb_rel = window->NavRectRel[0]; - 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->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); - } - if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) - { - bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x; - if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; } - NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); - } - if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) - { - 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); - } - if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) - { - bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y; - if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; } - NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); - } + // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire + // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. + g.NavWrapRequestWindow = window; + g.NavWrapRequestFlags = move_flags; } // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). @@ -8457,6 +8433,8 @@ static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; g.IO.WantSetMousePos = false; + g.NavWrapRequestWindow = NULL; + g.NavWrapRequestFlags = ImGuiNavMoveFlags_None; #if 0 if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); #endif @@ -8870,6 +8848,68 @@ static float ImGui::NavUpdatePageUpPageDown() return 0.0f; } +static void ImGui::NavEndFrame() +{ + ImGuiContext& g = *GImGui; + + // Show CTRL+TAB list window + if (g.NavWindowingTarget != NULL) + NavUpdateWindowingOverlay(); + + // Perform wrap-around in menus + ImGuiWindow* window = g.NavWrapRequestWindow; + ImGuiNavMoveFlags move_flags = g.NavWrapRequestFlags; + if (window != NULL && g.NavWindow == window && NavMoveRequestButNoResultYet() && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == ImGuiNavLayer_Main) + { + IM_ASSERT(move_flags != 0); // No points calling this with no wrapping + ImRect bb_rel = window->NavRectRel[0]; + + 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->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); + } + if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) + { + bb_rel.TranslateY(+bb_rel.GetHeight()); + clip_dir = ImGuiDir_Down; + } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + 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); + } + if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) + { + bb_rel.TranslateX(+bb_rel.GetWidth()); + clip_dir = ImGuiDir_Right; + } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + } +} + static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index 1fcd64de..7dd635e2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1207,6 +1207,8 @@ struct ImGuiContext ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow 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) + ImGuiWindow* NavWrapRequestWindow; // Window which requested trying nav wrap-around. + ImGuiNavMoveFlags NavWrapRequestFlags; // Wrap-around operation flags. // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! @@ -1383,6 +1385,8 @@ struct ImGuiContext NavMoveRequestForward = ImGuiNavForward_None; NavMoveRequestKeyMods = ImGuiKeyModFlags_None; NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; + NavWrapRequestWindow = NULL; + NavWrapRequestFlags = ImGuiNavMoveFlags_None; NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; From 6636cb9f2f9dd607a93b8e46a4cb2255703851e3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 May 2020 17:29:50 +0200 Subject: [PATCH 036/223] Viewports: Don't set ImGuiViewportFlags_NoRendererClear when ImGuiWindowFlags_NoBackground is set. (#3213) --- imgui.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e1f51a77..db1fb892 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6236,7 +6236,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) UpdateViewportPlatformMonitor(window->Viewport); // Update common viewport flags - ImGuiViewportFlags viewport_flags = (window->Viewport->Flags) & ~(ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration); + const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; + ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; if (flags & ImGuiWindowFlags_Tooltip) viewport_flags |= ImGuiViewportFlags_TopMost; @@ -6266,7 +6267,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) 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; + if (!(flags & ImGuiWindowFlags_NoBackground)) + viewport_flags &= ~ImGuiViewportFlags_NoRendererClear; + window->Viewport->Flags = viewport_flags; } From c46b79846c18d131f00ee299c811bb7afd125e66 Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Sat, 9 May 2020 22:18:10 -0700 Subject: [PATCH 037/223] Metrics: Fix metrics crash with viewports. --- imgui.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index db1fb892..f16aa3d3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15318,10 +15318,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) return ImRect(); } - static void NodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, int elem_offset, bool show_mesh, bool show_aabb) + static void NodeDrawCmdShowMeshAndBoundingBox(ImDrawList* fg_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, int elem_offset, bool show_mesh, bool show_aabb) { IM_ASSERT(show_mesh || show_aabb); - ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // Draw wire-frame version of all triangles @@ -15350,6 +15349,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) fg_draw_list->Flags = backup_flags; } + // Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport. static void NodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, 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); @@ -15388,7 +15388,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) 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 (ImGui::IsItemHovered() && (show_drawcmd_mesh || show_drawcmd_aabb) && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, show_drawcmd_mesh, show_drawcmd_aabb); + NodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, elem_offset, show_drawcmd_mesh, show_drawcmd_aabb); if (!pcmd_node_open) continue; @@ -15407,7 +15407,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); ImGui::Selectable(buf); if (ImGui::IsItemHovered() && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, true, false); + NodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, elem_offset, true, false); // 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. From 6b80bd9cc3114c18f05b9fae544676233464f547 Mon Sep 17 00:00:00 2001 From: Maru Date: Sun, 10 May 2020 07:01:54 +0900 Subject: [PATCH 038/223] Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) https://en.wikipedia.org/wiki/Hangul_Syllables --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ebd6f735..6730d29f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1df83d12..f566cbc5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2340,7 +2340,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesKorean() { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3131, 0x3163, // Korean alphabets - 0xAC00, 0xD79D, // Korean characters + 0xAC00, 0xD7A3, // Korean characters 0, }; return &ranges[0]; From 03ea87ea287a7391603bcf85a441412d973f65f1 Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Fri, 8 May 2020 13:02:15 -0700 Subject: [PATCH 039/223] Backends, Win32: Request monitor update when dpi awarness is enabled to make sure they have the correct dpi settings. --- examples/imgui_impl_win32.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index b7a38785..207e54fe 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -473,6 +473,9 @@ typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWAR // Helper function to enable DPI awareness without setting up a manifest void ImGui_ImplWin32_EnableDpiAwareness() { + // Make sure monitors will be updated with latest correct scaling + g_WantUpdateMonitors = true; + // if (IsWindows10OrGreater()) // This needs a manifest to succeed. Instead we try to grab the function pointer! { static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process From 5fdfa32ccea2493f7ffc4801f2837199eabe1de5 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 May 2020 15:42:29 +0200 Subject: [PATCH 040/223] 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 341bdcbe..e8fa16f1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -194,7 +194,7 @@ Ongoing Dear ImGui development is financially supported by users and private spo - [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui/) *Double-chocolate and Salty caramel sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) +- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors). From 476daf9aac1b49f91a3c370eed4085c96e1725a5 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 May 2020 20:28:34 +0200 Subject: [PATCH 041/223] Settings: Added ReadInitFn pre-load handler. (docking branch already has it, so it'll probably conflict with same contents) --- imgui.cpp | 43 +++++++++++++++++++++++++------------------ imgui_internal.h | 3 ++- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index deb7e981..726b05f5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -918,9 +918,9 @@ static ImRect GetViewportRect(); // Settings static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); -static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); +static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); // Platform Dependents default implementation for IO functions @@ -3945,9 +3945,9 @@ void ImGui::Initialize(ImGuiContext* context) ini_handler.TypeName = "Window"; ini_handler.TypeHash = ImHashStr("Window"); ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll; - ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen; ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll; g.SettingsHandlers.push_back(ini_handler); } @@ -9784,6 +9784,12 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) memcpy(buf, ini_data, ini_size); buf_end[0] = 0; + // Call pre-read handlers + // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ReadInitFn) + g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]); + void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; @@ -9872,24 +9878,12 @@ static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandl g.SettingsWindows.clear(); } -// Apply to existing windows (if any) -static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) -{ - ImGuiContext& g = *ctx; - for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) - if (settings->WantApply) - { - if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) - ApplyWindowSettings(window, settings); - settings->WantApply = false; - } -} - static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { - ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); - if (!settings) - settings = ImGui::CreateNewWindowSettings(name); + ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name); + ImGuiID id = settings->ID; + *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry + settings->ID = id; settings->WantApply = true; return (void*)settings; } @@ -9904,6 +9898,19 @@ static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } +// Apply to existing windows (if any) +static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->WantApply) + { + if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) + ApplyWindowSettings(window, settings); + settings->WantApply = false; + } +} + static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { // Gather data from windows that were active during this session diff --git a/imgui_internal.h b/imgui_internal.h index 7dd635e2..2802f519 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1082,9 +1082,10 @@ struct ImGuiSettingsHandler const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHashStr(TypeName) void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data - void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) + void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order) 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 (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' void* UserData; From 1cd32d3afe8cc70338e02652795ce7a62fe680ea Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 May 2020 00:15:14 +0200 Subject: [PATCH 042/223] Docking: moving small docking context to imgui_internal.h, removed unnecessary indirection, renaming. --- imgui.cpp | 111 ++++++++++++++++++++--------------------------- imgui_internal.h | 14 ++++-- 2 files changed, 59 insertions(+), 66 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f16aa3d3..5cc867de 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4164,7 +4164,6 @@ void ImGui::Initialize(ImGuiContext* context) g.PlatformIO.Viewports.push_back(g.Viewports[0]); // Extensions - IM_ASSERT(g.DockContext == NULL); DockContextInitialize(&g); #endif // #ifdef IMGUI_HAS_DOCK @@ -4203,7 +4202,6 @@ void ImGui::Shutdown(ImGuiContext* context) SetCurrentContext(backup_context); // Shutdown extensions - IM_ASSERT(g.DockContext != NULL); DockContextShutdown(&g); // Clear everything else @@ -11626,15 +11624,6 @@ struct ImGuiDockNodeSettings ImGuiDockNodeSettings() { ID = ParentNodeId = ParentWindowId = SelectedWindowId = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } }; -struct ImGuiDockContext -{ - ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes - ImVector Requests; - ImVector SettingsNodes; - bool WantFullRebuild; - ImGuiDockContext() { WantFullRebuild = false; } -}; - //----------------------------------------------------------------------------- // Docking: Forward Declarations //----------------------------------------------------------------------------- @@ -11731,8 +11720,6 @@ namespace ImGui void ImGui::DockContextInitialize(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - IM_ASSERT(g.DockContext == NULL); - g.DockContext = IM_NEW(ImGuiDockContext)(); // Add .ini handle for persistent docking data ImGuiSettingsHandler ini_handler; @@ -11749,13 +11736,10 @@ void ImGui::DockContextInitialize(ImGuiContext* ctx) void ImGui::DockContextShutdown(ImGuiContext* ctx) { - ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) IM_DELETE(node); - IM_DELETE(g.DockContext); - g.DockContext = NULL; } void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references) @@ -11771,11 +11755,11 @@ void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) { IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; SaveIniSettingsToMemory(); ImGuiID root_id = 0; // Rebuild all DockContextClearNodes(ctx, root_id, false); - DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); DockContextBuildAddWindowsToNodes(ctx, root_id); } @@ -11783,7 +11767,7 @@ void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) { if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0) @@ -11827,7 +11811,7 @@ void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx) void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; @@ -11847,7 +11831,7 @@ void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id) { - return (ImGuiDockNode*)ctx->DockContext->Nodes.GetVoidPtr(id); + return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id); } ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx) @@ -11871,14 +11855,14 @@ static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id) // 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); + ctx->DockContext.Nodes.SetVoidPtr(node->ID, node); return node; } static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID); IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node); @@ -11925,16 +11909,16 @@ struct ImGuiDockContextPruneNodeData static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; IM_ASSERT(g.Windows.Size == 0); ImPool pool; - pool.Reserve(dc->SettingsNodes.Size); + pool.Reserve(dc->NodesSettings.Size); // Count child nodes and compute RootID - for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++) + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0; pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID; if (settings->ParentNodeId) @@ -11943,9 +11927,9 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) // 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++) + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; if (settings->ParentWindowId != 0) if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId)) if (window_settings->DockId) @@ -11965,9 +11949,9 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) } // Prune - for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++) + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID); if (data->CountWindows > 1) continue; @@ -12059,7 +12043,7 @@ void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDo req.DockSplitDir = split_dir; req.DockSplitRatio = split_ratio; req.DockSplitOuter = split_outer; - ctx->DockContext->Requests.push_back(req); + ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window) @@ -12067,7 +12051,7 @@ void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window) ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Undock; req.UndockTargetWindow = window; - ctx->DockContext->Requests.push_back(req); + ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) @@ -12075,12 +12059,12 @@ void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Undock; req.UndockTargetNode = node; - ctx->DockContext->Requests.push_back(req); + ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node) { - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; for (int n = 0; n < dc->Requests.Size; n++) if (dc->Requests[n].DockTargetNode == node) dc->Requests[n].Type = ImGuiDockRequestType_None; @@ -13725,12 +13709,12 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG if (child_0) { - ctx->DockContext->Nodes.SetVoidPtr(child_0->ID, NULL); + ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL); IM_DELETE(child_0); } if (child_1) { - ctx->DockContext->Nodes.SetVoidPtr(child_1->ID, NULL); + ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL); IM_DELETE(child_1); } } @@ -14264,7 +14248,7 @@ void ImGui::DockBuilderRemoveNode(ImGuiID node_id) void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) { ImGuiContext* ctx = GImGui; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL; if (root_id && root_node == NULL) @@ -14875,29 +14859,29 @@ static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id) { // FIXME-OPT - ImGuiDockContext* dc = ctx->DockContext; - for (int n = 0; n < dc->SettingsNodes.Size; n++) - if (dc->SettingsNodes[n].ID == id) - return &dc->SettingsNodes[n]; + ImGuiDockContext* dc = &ctx->DockContext; + for (int n = 0; n < dc->NodesSettings.Size; n++) + if (dc->NodesSettings[n].ID == id) + return &dc->NodesSettings[n]; return NULL; } // Clear settings data static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { - ImGuiDockContext* dc = ctx->DockContext; - dc->SettingsNodes.clear(); + ImGuiDockContext* dc = &ctx->DockContext; + dc->NodesSettings.clear(); DockContextClearNodes(ctx, 0, true); } -// Recreate dones based on settings data +// Recreate nodes based on settings data static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { // Prune settings at boot time only - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (ctx->Windows.Size == 0) DockContextPruneUnusedSettingsNodes(ctx); - DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); DockContextBuildAddWindowsToNodes(ctx, 0); } @@ -14943,11 +14927,10 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings 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, " Selected=0x%08X%n", &node.SelectedWindowId,&r) == 1) { line += r; } - ImGuiDockContext* dc = ctx->DockContext; if (node.ParentNodeId != 0) if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId)) node.Depth = parent_settings->Depth + 1; - dc->SettingsNodes.push_back(node); + ctx->DockContext.NodesSettings.push_back(node); } static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth) @@ -14964,7 +14947,7 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo node_settings.Pos = ImVec2ih(node->Pos); node_settings.Size = ImVec2ih(node->Size); node_settings.SizeRef = ImVec2ih(node->SizeRef); - dc->SettingsNodes.push_back(node_settings); + dc->NodesSettings.push_back(node_settings); if (node->ChildNodes[0]) DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1); if (node->ChildNodes[1]) @@ -14974,29 +14957,29 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = g.DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; // Gather settings data // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) - dc->SettingsNodes.resize(0); - dc->SettingsNodes.reserve(dc->Nodes.Data.Size); + dc->NodesSettings.resize(0); + dc->NodesSettings.reserve(dc->Nodes.Data.Size); for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (node->IsRootNode()) DockSettingsHandler_DockNodeToSettings(dc, node, 0); int max_depth = 0; - for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++) - max_depth = ImMax((int)dc->SettingsNodes[node_n].Depth, max_depth); + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) + max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth); // Write to text buffer buf->appendf("[%s][Data]\n", handler->TypeName); - for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++) + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) { const int line_start_pos = buf->size(); (void)line_start_pos; - const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n]; + const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[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->ParentNodeId) @@ -15722,7 +15705,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("Dock nodes")) { - ImGuiDockContext* dc = g.DockContext; + ImGuiDockContext* dc = &g.DockContext; ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes); if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ImGui::SameLine(); @@ -15777,14 +15760,15 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("SettingsDocking", "Settings packed data: Docking")) { + ImGuiDockContext* dc = &g.DockContext; ImGui::Text("In SettingsWindows:"); for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (settings->DockId != 0) ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId); ImGui::Text("In SettingsNodes:"); - for (int n = 0; n < g.DockContext->SettingsNodes.Size; n++) + for (int n = 0; n < dc->NodesSettings.Size; n++) { - ImGuiDockNodeSettings* settings = &g.DockContext->SettingsNodes[n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[n]; const char* selected_tab_name = NULL; if (settings->SelectedWindowId) { @@ -15871,8 +15855,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Overlay: Display Docking info if (show_docking_nodes && g.IO.KeyCtrl) { - for (int n = 0; n < g.DockContext->Nodes.Data.Size; n++) - if (ImGuiDockNode* node = (ImGuiDockNode*)g.DockContext->Nodes.Data[n].val_p) + ImGuiDockContext* dc = &g.DockContext; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) { ImGuiDockNode* root_node = DockNodeGetRootNode(node); if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos)) diff --git a/imgui_internal.h b/imgui_internal.h index 489e5011..54d731ca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -94,6 +94,7 @@ struct ImGuiColumns; // Storage data for a columns set struct ImGuiContext; // Main Dear ImGui context struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiDockContext; // Docking system context +struct ImGuiDockRequest; // Docking system dock/undock queued request struct ImGuiDockNode; // Docking system node (hold a list of Windows OR two child dock nodes) struct ImGuiDockNodeSettings; // Storage for a dock node in .ini file (we preserve those even if the associated dock node isn't active during the session) struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() @@ -1161,6 +1162,15 @@ struct ImGuiDockNode ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } }; +struct ImGuiDockContext +{ + ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes + ImVector Requests; + ImVector NodesSettings; + bool WantFullRebuild; + ImGuiDockContext() { WantFullRebuild = false; } +}; + #endif // #ifdef IMGUI_HAS_DOCK //----------------------------------------------------------------------------- @@ -1443,7 +1453,7 @@ struct ImGuiContext // Extensions // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? - ImGuiDockContext* DockContext; + ImGuiDockContext DockContext; // Settings bool SettingsLoaded; @@ -1597,8 +1607,6 @@ struct ImGuiContext PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX); PlatformImePosViewport = 0; - DockContext = NULL; - SettingsLoaded = false; SettingsDirtyTimer = 0.0f; From 39c978f499018bedc62257f2be18957e76f3990a Mon Sep 17 00:00:00 2001 From: "Mr. Metric" Date: Fri, 15 May 2020 01:51:51 -0700 Subject: [PATCH 043/223] Fix typo/bug introduced by 0679e056 (#3231, #3209, #1829, #946, #413) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 71153c20..e509c039 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2970,7 +2970,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); // Only mark as edited if new value is different - value_changed = memcmp(&data_type, p_data, data_type_size) != 0; + value_changed = memcmp(&data_backup, p_data, data_type_size) != 0; if (value_changed) MarkItemEdited(id); } From 3b3af6b73136a03dfcdb84872fc08542900a1aa8 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 May 2020 16:11:42 +0200 Subject: [PATCH 044/223] Docking: Fix extraneous function declaration (#3236) + moved some other declarations in imgui_internal to facilitate moving docking code. --- imgui.cpp | 17 +++++++---------- imgui_internal.h | 10 ++++++---- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fcebd5c0..31b5e10e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -921,7 +921,6 @@ static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For u //------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window); -static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); @@ -7137,7 +7136,7 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co window->Collapsed = collapsed; } -static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) +void ImGui::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(size); @@ -11679,7 +11678,6 @@ namespace ImGui 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 @@ -11707,7 +11705,6 @@ namespace ImGui 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; } - static int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } static int DockNodeGetTabOrder(ImGuiWindow* window); // ImGuiDockNode tree manipulations @@ -11781,11 +11778,11 @@ void ImGui::DockContextShutdown(ImGuiContext* ctx) IM_DELETE(node); } -void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references) +void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs) { IM_UNUSED(ctx); IM_ASSERT(ctx == GImGui); - DockBuilderRemoveNodeDockedWindows(root_id, clear_persistent_docking_references); + DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs); DockBuilderRemoveNodeChildNodes(root_id); } @@ -14351,12 +14348,12 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) } } -void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persistent_docking_references) +void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs) { // Clear references in settings ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; - if (clear_persistent_docking_references) + if (clear_settings_refs) { for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) { @@ -14379,8 +14376,8 @@ void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persi { const ImGuiID backup_dock_id = window->DockId; IM_UNUSED(backup_dock_id); - DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_references); - if (!clear_persistent_docking_references) + DockContextProcessUndockWindow(ctx, window, clear_settings_refs); + if (!clear_settings_refs) IM_ASSERT(window->DockId == backup_dock_id); } } diff --git a/imgui_internal.h b/imgui_internal.h index 9737578c..f7a2fbca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1978,6 +1978,7 @@ 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 SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window); @@ -2107,7 +2108,7 @@ namespace ImGui // (some functions are only declared in imgui.cpp, see Docking section) IMGUI_API void DockContextInitialize(ImGuiContext* ctx); IMGUI_API void DockContextShutdown(ImGuiContext* ctx); - IMGUI_API void DockContextOnLoadSettings(ImGuiContext* ctx); + IMGUI_API void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs); // Use root_id==0 to clear all IMGUI_API void DockContextRebuildNodes(ImGuiContext* ctx); IMGUI_API void DockContextUpdateUndocking(ImGuiContext* ctx); IMGUI_API void DockContextUpdateDocking(ImGuiContext* ctx); @@ -2116,8 +2117,9 @@ namespace ImGui 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; } - inline ImGuiDockNode* GetWindowDockNode() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockNode; } + inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } + inline int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } + inline ImGuiDockNode* GetWindowDockNode() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockNode; } IMGUI_API bool GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window); IMGUI_API void BeginDocked(ImGuiWindow* window, bool* p_open); IMGUI_API void BeginDockableDragDropSource(ImGuiWindow* window); @@ -2138,7 +2140,7 @@ namespace ImGui 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 = 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 DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_settings_refs = true); IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the remaining root node (node_id). IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); From 417ac68f82912ae4291e8e9b05abf38877a64b83 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 May 2020 11:55:36 +0200 Subject: [PATCH 045/223] Internals: AddPolyline: Add spaces for consistency, renaming. --- imgui_draw.cpp | 56 +++++++++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f566cbc5..2dfccf07 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -627,13 +627,12 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (points_count < 2) return; - const ImVec2 uv = _Data->TexUvWhitePixel; - + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; int count = points_count; if (!closed) count = points_count-1; - const bool thick_line = thickness > 1.0f; + const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) { // Anti-aliased stroke @@ -704,9 +703,9 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Add vertices for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; - _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; - _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; + _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; _VtxWritePtr += 3; } } @@ -715,22 +714,23 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; if (!closed) { + const int points_last = points_count - 1; temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); - temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); - temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); - temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); - temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); } // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; - unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment + const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -753,12 +753,12 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 out_vtx[3].y = points[i2].y - dm_out_y; // Add indexes - _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); - _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); - _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); - _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); - _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); - _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr += 18; idx1 = idx2; @@ -767,10 +767,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Add vertices for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; - _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; - _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; - _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans; _VtxWritePtr += 4; } } @@ -795,14 +795,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dx *= (thickness * 0.5f); dy *= (thickness * 0.5f); - _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; - _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; - _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; - _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; - _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); - _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3); _IdxWritePtr += 6; _VtxCurrentIdx += 4; } From 615e9ae34537df5324df2f71253eafd887a848d1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 May 2020 15:08:47 +0200 Subject: [PATCH 046/223] Docking: Fix undocking (#3243), amend 7b3d3798 (#1738) --- imgui.cpp | 15 ++++++++++----- imgui_widgets.cpp | 5 +++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 31b5e10e..bec67413 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6796,9 +6796,14 @@ void ImGui::FocusWindow(ImGuiWindow* window) IM_ASSERT(window == NULL || window->RootWindow != NULL); ImGuiWindow* focus_front_window = window ? window->RootWindowDockStop : NULL; ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; - - // Steal focus on active widgets - if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window) + ImGuiDockNode* dock_node = window ? window->DockNode : NULL; + bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow); + + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) + // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window && !active_id_window_is_dock_node_host) ClearActiveID(); // Passing NULL allow to disable keyboard focus @@ -6807,8 +6812,8 @@ void ImGui::FocusWindow(ImGuiWindow* window) window->LastFrameJustFocused = g.FrameCount; // Select in dock node - if (window->DockNode && window->DockNode->TabBar) - window->DockNode->TabBar->SelectedTabId = window->DockNode->TabBar->NextSelectedTabId = window->ID; + if (dock_node && dock_node->TabBar) + dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->ID; // Bring to front BringWindowToFocusFront(focus_front_window); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 74df4865..2c1c04e1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7289,6 +7289,11 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->NextSelectedTabId = id; hovered |= (g.HoveredId == id); + // Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() + // will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. + if (held && docked_window && g.ActiveId == id && g.ActiveIdIsJustActivated) + g.ActiveIdWindow = docked_window; + // 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) SetItemAllowOverlap(); From 75bbbda645c650a52783e8bd5c49da4b6905d81e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 May 2020 11:44:00 +0200 Subject: [PATCH 047/223] Examples: Update comments to get SDL2 package with msys2's pacman (#3251) --- examples/example_sdl_opengl2/Makefile | 2 +- examples/example_sdl_opengl3/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/example_sdl_opengl2/Makefile b/examples/example_sdl_opengl2/Makefile index ce29a249..9c57337e 100644 --- a/examples/example_sdl_opengl2/Makefile +++ b/examples/example_sdl_opengl2/Makefile @@ -8,7 +8,7 @@ # Mac OS X: # brew install sdl2 # MSYS2: -# pacman -S mingw-w64-i686-SDL +# pacman -S mingw-w64-i686-SDL2 # #CXX = g++ diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index ada77197..e8b2f566 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -8,7 +8,7 @@ # Mac OS X: # brew install sdl2 # MSYS2: -# pacman -S mingw-w64-i686-SDL +# pacman -S mingw-w64-i686-SDL2 # #CXX = g++ From f44962c01a0e5f5fdf9652cb28e775838fe0dbbc Mon Sep 17 00:00:00 2001 From: Espyo Date: Wed, 20 May 2020 16:48:21 +0100 Subject: [PATCH 048/223] Backends: Allegro: Don't call AddInputCharacter if the pressed key has no character. (#3252) --- examples/imgui_impl_allegro5.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 76f74a3f..2c7df9a9 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -357,7 +357,8 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT *ev) return true; case ALLEGRO_EVENT_KEY_CHAR: if (ev->keyboard.display == g_Display) - io.AddInputCharacter((unsigned int)ev->keyboard.unichar); + if (ev->keyboard.unichar != 0) + io.AddInputCharacter((unsigned int)ev->keyboard.unichar); return true; case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_UP: From c8cde28cf3fb5d1e86faa80edf9b2c48ccc2f8dc Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 May 2020 17:56:08 +0200 Subject: [PATCH 049/223] IO: AddInputCharacters function ignore 0 input. (#3252) Amend ef13d954 + c8ea0a01 (#2541, #2538, #2815) --- imgui.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 726b05f5..6a984849 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1142,17 +1142,21 @@ ImGuiIO::ImGuiIO() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(unsigned int c) { - InputQueueCharacters.push_back(c > 0 && c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); + if (c != 0) + InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); } // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so // we should save the high surrogate. void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c) { + if (c == 0 && InputQueueSurrogate == 0) + return; + if ((c & 0xFC00) == 0xD800) // High surrogate, must save { if (InputQueueSurrogate != 0) - InputQueueCharacters.push_back(0xFFFD); + InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID); InputQueueSurrogate = c; return; } @@ -1177,7 +1181,7 @@ void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) { unsigned int c = 0; utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL); - if (c > 0) + if (c != 0) InputQueueCharacters.push_back((ImWchar)c); } } From d29157ce584e731114ff09d448120e094307304f Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 24 May 2020 12:32:31 +0200 Subject: [PATCH 050/223] Moved static array with non-trivial constructors outside of function seems to remove requirement of linking with libstdc++ on some compilers. --- imgui.cpp | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6a984849..97b15411 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5064,6 +5064,21 @@ static const ImGuiResizeGripDef resize_grip_def[4] = { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused) }; +struct ImGuiResizeBorderDef +{ + ImVec2 InnerDir; + ImVec2 CornerPosN1, CornerPosN2; + float OuterAngle; +}; + +static const ImGuiResizeBorderDef resize_border_def[4] = +{ + { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top + { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right + { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom + { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left +}; + static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) { ImRect rect = window->Rect(); @@ -5229,19 +5244,6 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) int border_held = window->ResizeBorderHeld; if (border_held != -1) { - struct ImGuiResizeBorderDef - { - ImVec2 InnerDir; - ImVec2 CornerPosN1, CornerPosN2; - float OuterAngle; - }; - static const ImGuiResizeBorderDef resize_border_def[4] = - { - { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top - { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right - { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom - { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left - }; const ImGuiResizeBorderDef& def = resize_border_def[border_held]; ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle); From 39d17ca07f14d3e37b8e6a85ee65bc078abf023e Mon Sep 17 00:00:00 2001 From: Nicolas Burrus Date: Mon, 25 May 2020 07:34:12 +0200 Subject: [PATCH 051/223] Examples: Apple: catch events from the right and other mouse buttons when using Cocoa. (#3260) --- docs/CHANGELOG.txt | 6 +++-- .../Shared/ViewController.mm | 24 +++++++++++++++++++ examples/example_apple_opengl2/main.mm | 24 ++++++++++++------- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6730d29f..78719031 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,8 @@ Other Changes: - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] +- Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when + drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the @@ -62,8 +64,8 @@ Other Changes: - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] -- Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when - drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm + not forwarding right and center mouse clicks. (#3260) [@nburrus] ----------------------------------------------------------------------- diff --git a/examples/example_apple_metal/Shared/ViewController.mm b/examples/example_apple_metal/Shared/ViewController.mm index 73040add..3c79cc1c 100644 --- a/examples/example_apple_metal/Shared/ViewController.mm +++ b/examples/example_apple_metal/Shared/ViewController.mm @@ -72,14 +72,38 @@ ImGui_ImplOSX_HandleEvent(event, self.view); } +- (void)rightMouseDown:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseDown:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + - (void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } +- (void)rightMouseUp:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseUp:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + - (void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } +- (void)rightMouseDragged:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseDragged:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + - (void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index e8f2768b..7cbf3409 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -139,14 +139,22 @@ } // Forward Mouse/Keyboard events to dear imgui OSX back-end. It returns true when imgui is expecting to use the event. --(void)keyUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)keyDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)flagsChanged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)keyUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)keyDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)flagsChanged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } @end From 43f79aa21069485f27bf5dee3f9977464fd746e3 Mon Sep 17 00:00:00 2001 From: Nicolas Burrus Date: Mon, 25 May 2020 08:27:17 +0200 Subject: [PATCH 052/223] Backends: OSX: import the glfw workaround to avoid missing mouse clicks. (#3261) --- examples/imgui_impl_osx.mm | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 54b23d07..221fa562 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) +// 2020-05-25: Inputs: Added a fix for missing trackpad clicks when done with "soft tap". // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-10-11: Inputs: Fix using Backspace key. // 2019-07-21: Re-added clipboard handlers as they are not enabled by default in core imgui.cpp (reverted 2019-05-18 change). @@ -27,6 +28,8 @@ static CFAbsoluteTime g_Time = 0.0; static NSCursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {}; static bool g_MouseCursorHidden = false; +static bool g_MouseJustPressed[5] = { false, false, false, false, false }; +static bool g_MouseDown[5] = { false, false, false, false, false }; // Undocumented methods for creating cursors. @interface NSCursor() @@ -121,9 +124,17 @@ void ImGui_ImplOSX_Shutdown() { } -static void ImGui_ImplOSX_UpdateMouseCursor() +static void ImGui_ImplOSX_UpdateMouseCursorAndButtons() { ImGuiIO& io = ImGui::GetIO(); + + for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown) && i < IM_ARRAYSIZE(g_MouseJustPressed); 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. + io.MouseDown[i] = g_MouseJustPressed[i] || g_MouseDown[i]; + g_MouseJustPressed[i] = false; + } + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return; @@ -167,7 +178,7 @@ void ImGui_ImplOSX_NewFrame(NSView* view) io.DeltaTime = current_time - g_Time; g_Time = current_time; - ImGui_ImplOSX_UpdateMouseCursor(); + ImGui_ImplOSX_UpdateMouseCursorAndButtons(); } static int mapCharacterToKey(int c) @@ -197,16 +208,19 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(io.MouseDown)) - io.MouseDown[button] = true; + if (button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed)) + { + g_MouseJustPressed[button] = true; + g_MouseDown[button] = true; + } return io.WantCaptureMouse; } if (event.type == NSEventTypeLeftMouseUp || event.type == NSEventTypeRightMouseUp || event.type == NSEventTypeOtherMouseUp) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(io.MouseDown)) - io.MouseDown[button] = false; + if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown)) + g_MouseDown[button] = false; return io.WantCaptureMouse; } From 9c209d5a9070f8d2dfc3a311a15064daf2f81518 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 11:42:20 +0200 Subject: [PATCH 053/223] Minor amend 9028088 (#3261) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_glfw.cpp | 2 +- examples/imgui_impl_osx.mm | 15 ++++++--------- imgui.h | 2 +- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 78719031..3528c1e1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,7 @@ Other Changes: - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] +- Backends: OSX: Added workaround to avoid fast mouse clicks. (#3261, #1992, #2525) [@nburrus] - Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm not forwarding right and center mouse clicks. (#3260) [@nburrus] diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index c496232c..ef63c81f 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -68,7 +68,7 @@ enum GlfwClientApi 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 }; +static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {}; static GLFWcursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {}; static bool g_InstalledCallbacks = false; diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 221fa562..90501624 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -28,8 +28,8 @@ static CFAbsoluteTime g_Time = 0.0; static NSCursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {}; static bool g_MouseCursorHidden = false; -static bool g_MouseJustPressed[5] = { false, false, false, false, false }; -static bool g_MouseDown[5] = { false, false, false, false, false }; +static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {}; +static bool g_MouseDown[ImGuiMouseButton_COUNT] = {}; // Undocumented methods for creating cursors. @interface NSCursor() @@ -126,9 +126,9 @@ void ImGui_ImplOSX_Shutdown() static void ImGui_ImplOSX_UpdateMouseCursorAndButtons() { + // Update buttons ImGuiIO& io = ImGui::GetIO(); - - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown) && i < IM_ARRAYSIZE(g_MouseJustPressed); i++) + 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. io.MouseDown[i] = g_MouseJustPressed[i] || g_MouseDown[i]; @@ -208,11 +208,8 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed)) - { - g_MouseJustPressed[button] = true; - g_MouseDown[button] = true; - } + if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown)) + g_MouseDown[button] = g_MouseJustPressed[button] = true; return io.WantCaptureMouse; } diff --git a/imgui.h b/imgui.h index 788f74c9..1a8d7a40 100644 --- a/imgui.h +++ b/imgui.h @@ -1488,7 +1488,7 @@ struct ImGuiIO //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.) - bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends. bool KeyCtrl; // Keyboard modifier pressed: Control From a056603d8b8e2fd7f151844999cc077ac628097b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 12:05:11 +0200 Subject: [PATCH 054/223] Backends: Vulkan: Rename internal helper ImGui_ImplVulkanH_CreateWindow to ImGui_ImplVulkanH_CreateOrResizeWindow --- examples/example_glfw_vulkan/main.cpp | 11 ++++++----- examples/example_sdl_vulkan/main.cpp | 11 ++++++----- examples/imgui_impl_vulkan.cpp | 3 ++- examples/imgui_impl_vulkan.h | 2 +- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 910d4738..15ec2068 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -48,8 +48,9 @@ static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { - if (err == 0) return; - printf("VkResult %d\n", err); + if (err == 0) + return; + fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) abort(); } @@ -58,7 +59,7 @@ static void check_vk_result(VkResult err) static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments - fprintf(stderr, "[vulkan] ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); + fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } #endif // IMGUI_VULKAN_DEBUG_REPORT @@ -225,7 +226,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } static void CleanupVulkan() @@ -459,7 +460,7 @@ int main(int, char**) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); g_MainWindowData.FrameIndex = 0; } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index c4e529e1..53975516 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -40,8 +40,9 @@ static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { - if (err == 0) return; - printf("VkResult %d\n", err); + if (err == 0) + return; + fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) abort(); } @@ -50,7 +51,7 @@ static void check_vk_result(VkResult err) static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments - fprintf(stderr, "[vulkan] ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); + fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } #endif // IMGUI_VULKAN_DEBUG_REPORT @@ -217,7 +218,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } static void CleanupVulkan() @@ -456,7 +457,7 @@ int main(int, char**) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); g_MainWindowData.FrameIndex = 0; } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 652476c7..93c3b404 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -1155,7 +1155,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V } } -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) +// Create or resize window +void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) { (void)instance; ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index c85b5f28..0eb772e7 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -72,7 +72,7 @@ struct ImGui_ImplVulkanH_Frame; struct ImGui_ImplVulkanH_Window; // 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_CreateOrResizeWindow(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); From bb2529dd48f01d550afb00c3eff61a255e110282 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 12:23:49 +0200 Subject: [PATCH 055/223] Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_sdl.cpp | 3 +++ 2 files changed, 5 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3528c1e1..2ad7a085 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,8 @@ Other Changes: drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) +- Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, + making more render/clipping code use an early out path. - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) [@albertvaka] diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 9fd2cc48..695ac810 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) +// 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends. // 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2). // 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state). // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. @@ -348,6 +349,8 @@ void ImGui_ImplSDL2_NewFrame(SDL_Window* window) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + w = h = 0; SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) From 6b688561aa8f2b83a591c93c7d75d07a7beb24dd Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 25 May 2020 13:25:22 +0300 Subject: [PATCH 056/223] CI: Test building without C++ runtime on GCC/Clang. --- .github/workflows/build.yml | 15 +++++++++++++++ docs/CHANGELOG.txt | 5 ++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 03641749..8edef47b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -288,6 +288,14 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (without c++ runtime, Clang) + run: | + echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp + echo '#define IMGUI_DISABLE_DEMO_WINDOWS' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + clang++ -I. -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 @@ -324,6 +332,13 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp clang++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (without c++ runtime) + run: | + echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + clang++ -I. -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2ad7a085..da94c890 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,9 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, + static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). + Fixed a static contructor which led to this dependency on some compiler setups (unclear which). - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, @@ -67,7 +70,7 @@ Other Changes: - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Backends: OSX: Added workaround to avoid fast mouse clicks. (#3261, #1992, #2525) [@nburrus] -- Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm +- Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm not forwarding right and center mouse clicks. (#3260) [@nburrus] From 0fe5170bc400b789dcb3038eb0ead9d540927dfd Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 16:28:55 +0200 Subject: [PATCH 057/223] Viewports: Report minimized viewports as zero DisplaySize to be consistent with main branch + comments (#1542) --- imgui.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index bec67413..f580bc22 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4363,6 +4363,13 @@ void ImDrawDataBuilder::FlattenIntoSingleLayer() static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector* draw_lists) { + // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode, + // and to allow applications/back-ends to easily skip rendering. + // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure. + // This is because the work has been done already, and its wasted! We should fix that and add optimizations for + // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline. + const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0; + ImDrawData* draw_data = &viewport->DrawDataP; viewport->DrawData = draw_data; // Make publicly accessible draw_data->Valid = true; @@ -4370,7 +4377,7 @@ static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVectorCmdListsCount = draw_lists->Size; draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; draw_data->DisplayPos = viewport->Pos; - draw_data->DisplaySize = viewport->Size; + draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : 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++) From a06eb833590478276a3c186a7b66a9cf5082ebf4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 15:31:33 +0200 Subject: [PATCH 058/223] Examples: GLFW+Vulkan, SDL+Vulkan: Fix for handling of minimized windows. (#3259) --- docs/CHANGELOG.txt | 1 + examples/example_glfw_vulkan/main.cpp | 20 ++++++++++++-------- examples/example_sdl_vulkan/main.cpp | 23 +++++++++++++++-------- examples/imgui_impl_vulkan.cpp | 1 + 4 files changed, 29 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index da94c890..dff65283 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,7 @@ Other Changes: - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Backends: OSX: Added workaround to avoid fast mouse clicks. (#3261, #1992, #2525) [@nburrus] +- Examples: GLFW+Vulkan, SDL+Vulkan: Fix for handling of minimized windows. (#3259) - Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm not forwarding right and center mouse clicks. (#3260) [@nburrus] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 15ec2068..3ce1984a 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -248,7 +248,7 @@ static void CleanupVulkanWindow() ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } -static void FrameRender(ImGui_ImplVulkanH_Window* wd) +static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { VkResult err; @@ -286,8 +286,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* 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 dear imgui primitives into command buffer + ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -456,7 +456,8 @@ int main(int, char**) // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); - if (g_SwapChainRebuild) + // Resize swap chain? + if (g_SwapChainRebuild && g_SwapChainResizeWidth > 0 && g_SwapChainResizeHeight > 0) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); @@ -508,10 +509,13 @@ int main(int, char**) // Rendering ImGui::Render(); - memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); - FrameRender(wd); - - FramePresent(wd); + ImDrawData* draw_data = ImGui::GetDrawData(); + const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); + if (!is_minimized) + { + FrameRender(wd, draw_data); + FramePresent(wd); + } } // Cleanup diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 53975516..9eaea945 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -240,7 +240,7 @@ static void CleanupVulkanWindow() ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } -static void FrameRender(ImGui_ImplVulkanH_Window* wd) +static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { VkResult err; @@ -278,8 +278,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* 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 dear imgui primitives into command buffer + ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -447,13 +447,17 @@ int main(int, char**) done = true; if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) { + // Note: your own application may rely on SDL_WINDOWEVENT_MINIMIZED/SDL_WINDOWEVENT_RESTORED to skip updating all-together. + // Here ImGui_ImplSDL2_NewFrame() will set io.DisplaySize to zero which will disable rendering but let application run. + // Please note that you can't Present into a minimized window. g_SwapChainResizeWidth = (int)event.window.data1; g_SwapChainResizeHeight = (int)event.window.data2; g_SwapChainRebuild = true; } } - if (g_SwapChainRebuild) + // Resize swap chain? + if (g_SwapChainRebuild && g_SwapChainResizeWidth > 0 && g_SwapChainResizeHeight > 0) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); @@ -505,10 +509,13 @@ int main(int, char**) // Rendering ImGui::Render(); - memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); - FrameRender(wd); - - FramePresent(wd); + ImDrawData* draw_data = ImGui::GetDrawData(); + const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); + if (!is_minimized) + { + FrameRender(wd, draw_data); + FramePresent(wd); + } } // Cleanup diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 93c3b404..c65b2db0 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -999,6 +999,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; + wd->Swapchain = NULL; err = vkDeviceWaitIdle(device); check_vk_result(err); From 5ddf60d8ce57ad119833003f9afd777c0b1a3a74 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 18:28:25 +0200 Subject: [PATCH 059/223] Commit to facilitate branches merges --- imgui.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 97b15411..68b50827 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10158,8 +10158,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Debugging enums enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" }; - enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersDesired, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type - const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersDesired", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; + enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type + const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; // State static bool show_windows_rects = false; @@ -10433,7 +10433,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) } }; - // Tools if (ImGui::TreeNode("Tools")) { @@ -10504,7 +10503,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeTable(g.Tables.GetByIndex(n)); ImGui::TreePop(); } -#endif // #define IMGUI_HAS_TABLE +#endif // #ifdef IMGUI_HAS_TABLE // Details for Docking #ifdef IMGUI_HAS_DOCK @@ -10512,7 +10511,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) { ImGui::TreePop(); } -#endif // #define IMGUI_HAS_DOCK +#endif // #ifdef IMGUI_HAS_DOCK // Settings if (ImGui::TreeNode("Settings")) @@ -10548,10 +10547,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeTableSettings(settings); ImGui::TreePop(); } -#endif +#endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK -#endif +#endif // #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { @@ -10617,14 +10616,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGuiTable* table = g.Tables.GetByIndex(table_n); } } -#endif // #define IMGUI_HAS_TABLE +#endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK // Overlay: Display Docking info if (show_docking_nodes && g.IO.KeyCtrl) { } -#endif // #define IMGUI_HAS_DOCK +#endif // #ifdef IMGUI_HAS_DOCK ImGui::End(); } From 3f26a07ee1813cecaa87253436149e28fc11dc4e Mon Sep 17 00:00:00 2001 From: Giovanni Funchal Date: Thu, 21 May 2020 12:49:06 +0100 Subject: [PATCH 060/223] Backends: OpenGL: Fixed loader auto-detection to not interfere with ES2/ES3 defines. (#3246) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_opengl3.cpp | 20 ------------ examples/imgui_impl_opengl3.h | 57 ++++++++++++++++++++------------- 3 files changed, 36 insertions(+), 42 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dff65283..96d439be 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,7 @@ Other Changes: - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) [@albertvaka] +- Backends: OpenGL: Fixed loader auto-detection to not interfere with ES2/ES3 defines. (#3246) [@funchal] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 61131eb6..3ad04a41 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -79,27 +79,7 @@ #else #include // intptr_t #endif -#if defined(__APPLE__) -#include "TargetConditionals.h" -#endif -// Auto-enable GLES on matching platforms -#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) -#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" -#endif -#endif - -#if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) -#undef IMGUI_IMPL_OPENGL_LOADER_GL3W -#undef IMGUI_IMPL_OPENGL_LOADER_GLEW -#undef IMGUI_IMPL_OPENGL_LOADER_GLAD -#undef IMGUI_IMPL_OPENGL_LOADER_GLBINDING2 -#undef IMGUI_IMPL_OPENGL_LOADER_GLBINDING3 -#undef IMGUI_IMPL_OPENGL_LOADER_CUSTOM -#endif // GL includes #if defined(IMGUI_IMPL_OPENGL_ES2) diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index d55935a1..07d35219 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -12,7 +12,7 @@ // https://github.com/ocornut/imgui // About Desktop OpenGL function loaders: -// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. +// 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. @@ -36,36 +36,49 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); -// Specific OpenGL versions +// Specific OpenGL ES versions //#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten //#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android -// Desktop OpenGL: attempt to detect default GL loader based on available header files. +// Attempt to auto-detect the default Desktop GL loader based on available header files. // If auto-detection fails or doesn't select the same GL loader file as used by your application, // you are likely to get a crash in ImGui_ImplOpenGL3_Init(). -// You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. -#if !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ +// You can explicitly select a loader by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. +#if !defined(IMGUI_IMPL_OPENGL_ES2) \ + && !defined(IMGUI_IMPL_OPENGL_ES3) \ + && !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) - #if defined(__has_include) - #if __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLEW - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLAD - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GL3W - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING3 - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING2 - #else - #error "Cannot detect OpenGL loader!" - #endif - #else - #define IMGUI_IMPL_OPENGL_LOADER_GL3W // Default to GL3W - #endif + +// Try to detect GLES on matching platforms +#if defined(__APPLE__) +#include "TargetConditionals.h" #endif +#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" +// Otherwise try to detect supported Desktop OpenGL loaders.. +#elif defined(__has_include) +#if __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLEW +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLAD +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GL3W +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +#else + #error "Cannot detect OpenGL loader!" +#endif +#else + #define IMGUI_IMPL_OPENGL_LOADER_GL3W // Default to GL3W embedded in our repository +#endif + +#endif From 41e8837f5948fae98f5fb1892f0e408aa806a2f2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jun 2020 18:13:54 +0200 Subject: [PATCH 061/223] Comments, adding some spacing in ImVec2() constructors. --- imgui.cpp | 10 +++++----- imgui.h | 35 ++++++++++++++++++----------------- imgui_demo.cpp | 8 ++++---- imgui_draw.cpp | 2 +- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 10 +++++----- 6 files changed, 36 insertions(+), 35 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 68b50827..82de5dfb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -505,7 +505,7 @@ CODE - 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. - - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))' + - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))' - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. @@ -5083,10 +5083,10 @@ static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_ { ImRect rect = window->Rect(); if (thickness == 0.0f) rect.Max -= ImVec2(1,1); - if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top - if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right - if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom - if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left + if (border_n == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top + if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right + if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom + if (border_n == 3) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); } // Left IM_ASSERT(0); return ImRect(); } diff --git a/imgui.h b/imgui.h index 1a8d7a40..824c98de 100644 --- a/imgui.h +++ b/imgui.h @@ -268,9 +268,10 @@ namespace ImGui // Windows // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. - // - You may append multiple times to the same window during the same frame. // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, // which clicking will set the boolean to false when clicked. + // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. + // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, @@ -285,8 +286,8 @@ namespace ImGui // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. // Always call a matching EndChild() for each BeginChild() call, regardless of its return value [as with Begin: this is due to legacy reason and inconsistent with most BeginXXX functions apart from the regular Begin() which behaves like BeginChild().] - IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); - IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); IMGUI_API void EndChild(); // Windows Utilities @@ -302,7 +303,7 @@ namespace ImGui IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) // 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 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 (~ 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() @@ -310,7 +311,7 @@ namespace ImGui 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 override the Alpha component of 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 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. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). @@ -433,17 +434,17 @@ namespace ImGui // Widgets: Main // - Most widgets return true when the value has been changed or when pressed/selected // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. - IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button + 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, 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 + 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 IMGUI_API bool Checkbox(const char* label, bool* v); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer - IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1, 0), const char* overlay = NULL); IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses // Widgets: Combo Box @@ -498,7 +499,7 @@ namespace ImGui // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. // - 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 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); @@ -519,7 +520,7 @@ namespace ImGui 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); IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); - IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed. + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a colored square/button, hover for details, return true when pressed. IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. // Widgets: Trees @@ -545,14 +546,14 @@ namespace ImGui // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. - IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height - IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. // Widgets: List Boxes // - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them. IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); - IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards. + IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards. IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true! @@ -1487,7 +1488,7 @@ struct ImGuiIO // Input - Fill before calling NewFrame() //------------------------------------------------------------------ - ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.) + ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends. @@ -2158,7 +2159,7 @@ struct ImFontAtlasCustomRect float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset ImFont* Font; // Input // For custom font glyphs only: target font - ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } + ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } bool IsPacked() const { return X != 0xFFFF; } }; @@ -2239,7 +2240,7 @@ struct ImFontAtlas // Read docs/FONTS.txt for more details about using colorful icons. // Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } // [Internal] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 42f0844a..8cece7be 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2676,7 +2676,7 @@ static void ShowDemoWindowLayout() } if (show_child) { - ImGui::BeginChild("child", ImVec2(0,0), true); + ImGui::BeginChild("child", ImVec2(0, 0), true); ImGui::EndChild(); } ImGui::End(); @@ -4373,7 +4373,7 @@ struct ExampleAppLog Filter.Draw("Filter", -100.0f); ImGui::Separator(); - ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); + ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar); if (clear) Clear(); @@ -4646,7 +4646,7 @@ static void ShowExampleAppLongText(bool* p_open) case 1: { // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); ImGuiListClipper clipper(lines); while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) @@ -4656,7 +4656,7 @@ static void ShowExampleAppLongText(bool* p_open) } case 2: // Multiple calls to Text(), not clipped (slow) - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); for (int i = 0; i < lines; i++) ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); ImGui::PopStyleVar(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2dfccf07..057ddb65 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2873,7 +2873,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons const float line_height = size; const float scale = size / FontSize; - ImVec2 text_size = ImVec2(0,0); + ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; const bool word_wrap_enabled = (wrap_width > 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 2802f519..96e7b19e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1597,7 +1597,7 @@ struct IMGUI_API ImGuiWindow ImGuiCond SetWindowSizeAllowFlags; // store acceptable condition flags for SetNextWindowSize() use. ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use. 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. + 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. @@ -1920,7 +1920,7 @@ namespace ImGui // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); 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 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); @@ -1946,7 +1946,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 ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); 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 = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e509c039..07be3b36 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1225,7 +1225,7 @@ void ImGui::Spacing() ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - ItemSize(ImVec2(0,0)); + ItemSize(ImVec2(0, 0)); } void ImGui::Dummy(const ImVec2& size) @@ -1249,7 +1249,7 @@ void ImGui::NewLine() const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; window->DC.LayoutType = ImGuiLayoutType_Vertical; 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)); + ItemSize(ImVec2(0, 0)); else ItemSize(ImVec2(0.0f, g.FontSize)); window->DC.LayoutType = backup_layout_type; @@ -1611,7 +1611,7 @@ bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(voi // 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.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)) - SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); + SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) return false; @@ -3182,7 +3182,7 @@ 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, NULL, 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) @@ -3217,7 +3217,7 @@ static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* t const float line_height = g.FontSize; const float scale = line_height / font->FontSize; - ImVec2 text_size = ImVec2(0,0); + ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; const ImWchar* s = text_begin; From 5e976e9b0584878b5503fd86e81795c14981d1de Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Jun 2020 22:04:14 +0200 Subject: [PATCH 062/223] Title capitalization (#3280) --- docs/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/README.md b/docs/README.md index e8fa16f1..5536c5bc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,8 +1,8 @@ -dear imgui +Dear ImGui ===== [![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) -(This library is available under a free and permissive license, 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.) +(This library is available under a free and permissive license, 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.) Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts:
  _E-mail: contact @ dearimgui dot org_ @@ -86,7 +86,7 @@ Dear ImGui allows you to **create elaborate tools** as well as very short-lived Check out the Wiki's [About the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#About-the-IMGUI-paradigm) section if you want to understand the core principles behind the IMGUI paradigm. An IMGUI tries to minimize superfluous state duplication, state synchronization and state retention from the user's point of view. It is less error prone (less code and less bugs) than traditional retained-mode interfaces, and lends itself to create dynamic user interfaces. -Dear ImGui outputs vertex buffers and command lists that you can easily render in your application. The number of draw calls and state changes required to render them is fairly small. Because Dear ImGui doesn't know or touch graphics state directly, you can call its functions anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate dear imgui with your existing codebase. +Dear ImGui outputs vertex buffers and command lists that you can easily render in your application. The number of draw calls and state changes required to render them is fairly small. Because Dear ImGui doesn't know or touch graphics state directly, you can call its functions anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate Dear ImGui with your existing codebase. _A common misunderstanding is to mistake immediate mode gui for immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes as the gui functions are called. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely._ @@ -178,7 +178,7 @@ How to help **How can I help financing further development of Dear ImGui?** -Your contributions are keeping this project alive. The library is available under a free and permissive license, 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. Thank you! +Your contributions are keeping this project alive. The library is available under a free and permissive license, 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. Thank you! Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts:
  _E-mail: contact @ dearimgui dot org_ From 53dfccbe4b047539ed4a173fbfd95bf2f5856ea2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Jun 2020 17:53:41 +0200 Subject: [PATCH 063/223] imgui_freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. (#618) --- docs/CHANGELOG.txt | 1 + misc/freetype/imgui_freetype.cpp | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 96d439be..e7ff09d7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,7 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). Fixed a static contructor which led to this dependency on some compiler setups (unclear which). diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 69108e3e..20a3be0e 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -13,6 +13,7 @@ // - 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!) +// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. // Gamma Correct Blending: // FreeType assumes blending in linear space rather than gamma space. @@ -467,7 +468,6 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i]; const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint); - IM_ASSERT(metrics != NULL); if (metrics == NULL) continue; @@ -559,6 +559,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i]; stbrp_rect& pack_rect = src_tmp.Rects[glyph_i]; IM_ASSERT(pack_rect.was_packed); + if (pack_rect.w == 0 && pack_rect.h == 0) + continue; GlyphInfo& info = src_glyph.Info; IM_ASSERT(info.Width + padding <= pack_rect.w); From 79fbab543d229c8526d4d05078028f7fa0656c7b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Jun 2020 18:59:04 +0200 Subject: [PATCH 064/223] Minor fix to avoid undefined behavior sanitizer triggering (#3276) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 82de5dfb..b74f44cf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3516,7 +3516,7 @@ static void ImGui::UpdateMouseInputs() ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; - g.IO.MouseClickedTime[i] = -DBL_MAX; // so the third click isn't turned into a double-click + g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" so the third click isn't turned into a double-click } else { From 6eb66fbef3f6c65b9612170fae2ea150b6082b7a Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Fri, 5 Jun 2020 01:23:18 +0200 Subject: [PATCH 065/223] Backends: Win32: Cache the result of a windows version check. (#3283) This is not expected to change while the application is running :) --- examples/imgui_impl_win32.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index ae18eb6e..57d6e3ed 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -417,7 +417,8 @@ void ImGui_ImplWin32_EnableDpiAwareness() float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { UINT xdpi = 96, ydpi = 96; - if (IsWindows8Point1OrGreater()) + static BOOL bIsWindows8Point1OrGreater = IsWindows8Point1OrGreater(); + if (bIsWindows8Point1OrGreater) { static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor")) From dc49b14e2983547a165e5dc43edcee0e51b496c8 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 5 Jun 2020 14:47:49 +0300 Subject: [PATCH 066/223] Misc: Fix examples of using other OpenGL3 bindings in Makefiles. --- examples/example_glfw_opengl3/Makefile | 9 ++++++--- examples/example_sdl_opengl3/Makefile | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/examples/example_glfw_opengl3/Makefile b/examples/example_glfw_opengl3/Makefile index 7696eaae..3bc72b6f 100644 --- a/examples/example_glfw_opengl3/Makefile +++ b/examples/example_glfw_opengl3/Makefile @@ -35,7 +35,8 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glew ## (This assumes a system-wide installation) -# CXXFLAGS += -lGLEW -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# LIBS += -lGLEW ## Using OpenGL loader: glad # SOURCES += ../libs/glad/src/glad.c @@ -44,9 +45,11 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# LIBS += -lglbinding ## or the older version 2.x -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# LIBS += -lglbinding ##--------------------------------------------------------------------- ## BUILD FLAGS PER PLATFORM diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index e8b2f566..41826741 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -35,7 +35,8 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glew ## (This assumes a system-wide installation) -# CXXFLAGS += -lGLEW -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# LIBS += -lGLEW ## Using OpenGL loader: glad # SOURCES += ../libs/glad/src/glad.c @@ -44,9 +45,11 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# LIBS += -lglbinding ## or the older version 2.x -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# LIBS += -lglbinding ##--------------------------------------------------------------------- ## BUILD FLAGS PER PLATFORM From 5af8a8c7e83e735a1640d9347aa31c94d10e71fa Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 5 Jun 2020 13:04:55 +0300 Subject: [PATCH 067/223] CI: Extra warnings for builds with Clang. Backends: OpenGL3: Fix sign conversion warnings. --- examples/example_null/Makefile | 7 +++++-- examples/imgui_impl_opengl3.cpp | 26 +++++++++++++------------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 0ccee11b..15c547a5 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -40,7 +40,10 @@ endif ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" ifneq ($(WITH_EXTRA_WARNINGS), 0) - CXXFLAGS += -Wextra -pedantic + CXXFLAGS += -Wextra -Wpedantic + ifeq ($(shell $(CXX) -v 2>&1 | grep -c "clang version"), 1) + CXXFLAGS += -Wshadow -Wsign-conversion + endif endif CFLAGS = $(CXXFLAGS) endif @@ -56,7 +59,7 @@ endif ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) ECHO_MESSAGE = "MinGW" ifneq ($(WITH_EXTRA_WARNINGS), 0) - CXXFLAGS += -Wextra -pedantic + CXXFLAGS += -Wextra -Wpedantic endif CFLAGS = $(CXXFLAGS) endif diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 3ad04a41..028a704b 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -132,8 +132,8 @@ static GLuint g_GlVersion = 0; // Extracted at runtime usin static char g_GlslVersionString[32] = ""; // Specified by user or detected based on compile time GL settings. static GLuint g_FontTexture = 0; static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 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 GLint g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location +static GLuint g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location static unsigned int g_VboHandle = 0, g_ElementsHandle = 0; // Functions @@ -144,7 +144,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) GLint major, minor; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); - g_GlVersion = major * 100 + minor * 10; + g_GlVersion = (GLuint)(major * 100 + minor * 10); #else g_GlVersion = 200; // GLES 2 #endif @@ -292,14 +292,14 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Backup GL state GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); glActiveTexture(GL_TEXTURE0); - GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); - GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); + GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); #ifdef GL_SAMPLER_BINDING - GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler); + GLuint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); #endif - GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_ES2 - GLint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array_object); + GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object); #endif #ifdef GL_POLYGON_MODE GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); @@ -336,8 +336,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) const ImDrawList* cmd_list = draw_data->CmdLists[n]; // Upload vertex/index buffers - glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); + glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { @@ -643,9 +643,9 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); - g_AttribLocationVtxPos = glGetAttribLocation(g_ShaderHandle, "Position"); - g_AttribLocationVtxUV = glGetAttribLocation(g_ShaderHandle, "UV"); - g_AttribLocationVtxColor = glGetAttribLocation(g_ShaderHandle, "Color"); + g_AttribLocationVtxPos = (GLuint)glGetAttribLocation(g_ShaderHandle, "Position"); + g_AttribLocationVtxUV = (GLuint)glGetAttribLocation(g_ShaderHandle, "UV"); + g_AttribLocationVtxColor = (GLuint)glGetAttribLocation(g_ShaderHandle, "Color"); // Create buffers glGenBuffers(1, &g_VboHandle); From 78d5ccfb9012bdf9e25317aa11fc79e7e639c8fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 16:44:31 +0200 Subject: [PATCH 068/223] ImDrawList: PushColumnsBackground(): Fixed incorrect assert. (#3163) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 07be3b36..2ba7c6b4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7553,7 +7553,7 @@ void ImGui::PushColumnsBackground() 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 + IM_ASSERT(cmd_size >= window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } void ImGui::PopColumnsBackground() From e22e3f300af3b913e3209bde2a9dff91ed637807 Mon Sep 17 00:00:00 2001 From: thedmd Date: Sat, 6 Jun 2020 16:37:07 +0200 Subject: [PATCH 069/223] ImDrawList: Fixed an issue when draw command merging or cancelling while crossing the VtxOffset boundary would lead to draw command being emitted with wrong VtxOffset value. (#3129, #3163, #3232) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 +- imgui_draw.cpp | 32 ++++++++++++++++++++++---------- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e7ff09d7..54e5a113 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,9 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- ImDrawList: Fixed an issue when draw command merging or cancelling while crossing the VtxOffset + boundary would lead to draw command being emitted with wrong VtxOffset value. (#3129, #3163, #3232) + [@thedmd, @Shironekoben, @sergeyn, @ocornut] - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). diff --git a/imgui.cpp b/imgui.cpp index b74f44cf..0c2156d5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10267,7 +10267,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; char buf[300]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd: %4d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d triangles, Tex 0x%p, ClipRect (%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); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 057ddb65..0e56b3f4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -460,11 +460,17 @@ void ImDrawList::UpdateClipRect() } // Try to merge with previous command if it matches, else use current command - ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; - if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) - CmdBuffer.pop_back(); - else - curr_cmd->ClipRect = curr_clip_rect; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + { + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + } + + curr_cmd->ClipRect = curr_clip_rect; } void ImDrawList::UpdateTextureID() @@ -479,11 +485,17 @@ void ImDrawList::UpdateTextureID() } // Try to merge with previous command if it matches, else use current command - ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; - if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) - CmdBuffer.pop_back(); - else - curr_cmd->TextureId = curr_texture_id; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + { + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + } + + curr_cmd->TextureId = curr_texture_id; } #undef GetCurrentClipRect From 003153b3acbbb0022d35ea7fba4155c6706d801e Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 19:52:41 +0200 Subject: [PATCH 070/223] ImDrawList: Tweaks to make style consistent (using pointers, same local names). Added comments. Should be no-op. --- imgui.cpp | 8 ++++---- imgui.h | 20 ++++++++++---------- imgui_draw.cpp | 22 +++++++++++----------- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0c2156d5..01ceafe9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4077,15 +4077,15 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list) { - if (draw_list->CmdBuffer.empty()) + if (draw_list->CmdBuffer.Size == 0) return; // Remove trailing command if unused - ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); - if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) + ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.back(); + if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL) { draw_list->CmdBuffer.pop_back(); - if (draw_list->CmdBuffer.empty()) + if (draw_list->CmdBuffer.Size == 0) return; } diff --git a/imgui.h b/imgui.h index 824c98de..ebad93cb 100644 --- a/imgui.h +++ b/imgui.h @@ -1878,13 +1878,13 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c // is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bit 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_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bit 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. + unsigned int ElemCount; // 4 // 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; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + ImTextureID TextureId; // 4-8 // 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; // 4 // 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-bit indices. + unsigned int IdxOffset; // 4 // Start offset in index buffer. Always equal to sum of ElemCount drawn so far. + ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // 4-8 // The draw callback code can access this. ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; } }; @@ -1984,7 +1984,7 @@ struct ImDrawList ImVector _ClipRectStack; // [Internal] ImVector _TextureIdStack; // [Internal] ImVector _Path; // [Internal] current path building - ImDrawListSplitter _Splitter; // [Internal] for channels api + ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) // 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(); } @@ -2048,13 +2048,13 @@ struct ImDrawList // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) // - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place! - // Prefer using your own persistent copy of ImDrawListSplitter as you can stack them. + // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. 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 + // [Internal helpers] // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void Clear(); IMGUI_API void ClearFreeMemory(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0e56b3f4..91de2ae6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -434,14 +434,14 @@ void ImDrawList::AddDrawCmd() void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { - ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; - if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; + if (!curr_cmd || curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) { AddDrawCmd(); - current_cmd = &CmdBuffer.back(); + curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; } - current_cmd->UserCallback = callback; - current_cmd->UserCallbackData = callback_data; + curr_cmd->UserCallback = callback; + curr_cmd->UserCallbackData = callback_data; AddDrawCmd(); // Force a new command after us (see comment below) } @@ -452,7 +452,7 @@ void ImDrawList::UpdateClipRect() { // If current command is used with different settings we need to add a new command const ImVec4 curr_clip_rect = GetCurrentClipRect(); - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); @@ -477,7 +477,7 @@ void ImDrawList::UpdateTextureID() { // If current command is used with different settings we need to add a new command const ImTextureID curr_texture_id = GetCurrentTextureId(); - ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); @@ -559,8 +559,8 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) AddDrawCmd(); } - ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size - 1]; - draw_cmd.ElemCount += idx_count; + ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount += idx_count; int vtx_buffer_old_size = VtxBuffer.Size; VtxBuffer.resize(vtx_buffer_old_size + vtx_count); @@ -576,8 +576,8 @@ void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) { IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); - ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size - 1]; - draw_cmd.ElemCount -= idx_count; + ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount -= idx_count; VtxBuffer.shrink(VtxBuffer.Size - vtx_count); IdxBuffer.shrink(IdxBuffer.Size - idx_count); } From 0320e7257babeac02337771e1249317b44664a85 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 20:25:56 +0200 Subject: [PATCH 071/223] ImDrawList: Small refactor to create empty command when beginning the frame, allowing to simplify some functions. + Missing clearing two fields in ClearFreeMemory() (was hamrless) --- imgui.cpp | 6 +++--- imgui.h | 5 +++-- imgui_draw.cpp | 18 +++++++++++------- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 01ceafe9..07a832c4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3777,11 +3777,11 @@ void ImGui::NewFrame() if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; - g.BackgroundDrawList.Clear(); + g.BackgroundDrawList.ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); - g.ForegroundDrawList.Clear(); + g.ForegroundDrawList.ResetForNewFrame(); g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.ForegroundDrawList.PushClipRectFullScreen(); @@ -5860,7 +5860,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // DRAWING // Setup draw list and outer clipping rectangle - window->DrawList->Clear(); + window->DrawList->ResetForNewFrame(); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); diff --git a/imgui.h b/imgui.h index ebad93cb..7906ae07 100644 --- a/imgui.h +++ b/imgui.h @@ -1987,7 +1987,8 @@ struct ImDrawList ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) // 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(); } + ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; Flags = ImDrawListFlags_None; _VtxCurrentOffset = _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } + ~ImDrawList() { ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); @@ -2056,7 +2057,7 @@ struct ImDrawList // [Internal helpers] // NB: all primitives needs to be reserved via PrimReserve() beforehand! - IMGUI_API void Clear(); + IMGUI_API void ResetForNewFrame(); IMGUI_API void ClearFreeMemory(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 91de2ae6..d5844dbe 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -376,12 +376,13 @@ void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) } } -void ImDrawList::Clear() +// Initialize before use in a new frame. We always have a command ready in the buffer. +void ImDrawList::ResetForNewFrame() { CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); - Flags = _Data ? _Data->InitialFlags : ImDrawListFlags_None; + Flags = _Data->InitialFlags; _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; @@ -390,6 +391,7 @@ void ImDrawList::Clear() _TextureIdStack.resize(0); _Path.resize(0); _Splitter.Clear(); + CmdBuffer.push_back(ImDrawCmd()); } void ImDrawList::ClearFreeMemory() @@ -397,6 +399,8 @@ void ImDrawList::ClearFreeMemory() CmdBuffer.clear(); IdxBuffer.clear(); VtxBuffer.clear(); + Flags = ImDrawListFlags_None; + _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -434,8 +438,8 @@ void ImDrawList::AddDrawCmd() void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; - if (!curr_cmd || curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) { AddDrawCmd(); curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -452,8 +456,8 @@ void ImDrawList::UpdateClipRect() { // If current command is used with different settings we need to add a new command const ImVec4 curr_clip_rect = GetCurrentClipRect(); - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; - if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; @@ -477,7 +481,7 @@ void ImDrawList::UpdateTextureID() { // If current command is used with different settings we need to add a new command const ImTextureID curr_texture_id = GetCurrentTextureId(); - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); From 41f47c853bf300024a70482f3de76c6f2b68833c Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 20:35:29 +0200 Subject: [PATCH 072/223] ImDrawList: Amend 0320e72 removed an unnecessary test. --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d5844dbe..97a5c9f7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -482,7 +482,7 @@ void ImDrawList::UpdateTextureID() // If current command is used with different settings we need to add a new command const ImTextureID curr_texture_id = GetCurrentTextureId(); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; From f6120f8e16eefcdb37b63974e6915a3dd35414be Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 21:31:31 +0200 Subject: [PATCH 073/223] ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#259 --- docs/CHANGELOG.txt | 12 +++++++----- imgui_draw.cpp | 1 + 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 54e5a113..5f9f7b16 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,9 +56,11 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] -- ImDrawList: Fixed an issue when draw command merging or cancelling while crossing the VtxOffset - boundary would lead to draw command being emitted with wrong VtxOffset value. (#3129, #3163, #3232) +- ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the + VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current + VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). @@ -555,11 +557,11 @@ Other Changes: - 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-bit 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, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. (#2591) This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not support 32-bit 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. + This is provided for convenience and consistency with VtxOffset. (#2591) - 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. Combine @@ -571,7 +573,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, Metal, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes - (64k+ vertices) with 16-bit indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. + (64k+ vertices) with 16-bit indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. (#2591) - 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/imgui_draw.cpp b/imgui_draw.cpp index 97a5c9f7..e3455812 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1359,6 +1359,7 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) ImDrawCmd draw_cmd; draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); draw_cmd.TextureId = draw_list->_TextureIdStack.back(); + draw_cmd.VtxOffset = draw_list->_VtxCurrentOffset; _Channels[i]._CmdBuffer.push_back(draw_cmd); } } From 57191fe3d088b4895bbee75e8622413a4deeed90 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 14:17:49 +0200 Subject: [PATCH 074/223] Comments about limiting WindowRounding to a reasonable size. --- imgui.cpp | 7 ++++++- imgui.h | 2 +- imgui_internal.h | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 07a832c4..95dc22a6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1008,7 +1008,7 @@ ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window - WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. 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 @@ -5757,8 +5757,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Pos = ImFloor(window->Pos); // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + // Large values tend to lead to variety of artifacts and are not recommended. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; + // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts. + //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f); + // Apply window focus (new and reactivated windows are moved to front) bool want_focus = false; if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) diff --git a/imgui.h b/imgui.h index 7906ae07..8fcd5416 100644 --- a/imgui.h +++ b/imgui.h @@ -1371,7 +1371,7 @@ struct ImGuiStyle { 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 WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. 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. diff --git a/imgui_internal.h b/imgui_internal.h index 96e7b19e..7b15e63f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1561,7 +1561,7 @@ struct IMGUI_API ImGuiWindow 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 WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. float WindowBorderSize; // Window border size at the time of Begin(). int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)! ImGuiID MoveId; // == window->GetID("#MOVE") From a6bb047baba31c3a4038b9f1b06977e7c0feb08e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 15:22:44 +0200 Subject: [PATCH 075/223] ImDrawList: Store header/current ImDrawCmd in instance to simplify merging code. Amend 0320e72, toward #3163, #3129 --- imgui.h | 16 ++++---- imgui_draw.cpp | 102 +++++++++++++++++++++++-------------------------- 2 files changed, 57 insertions(+), 61 deletions(-) diff --git a/imgui.h b/imgui.h index 8fcd5416..45f3aa7c 100644 --- a/imgui.h +++ b/imgui.h @@ -1874,19 +1874,21 @@ 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_RendererHasVtxOffset' -// is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// - VtxOffset/IdxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, +// those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// Pre-1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. +// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). struct ImDrawCmd { - unsigned int ElemCount; // 4 // 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; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates ImTextureID TextureId; // 4-8 // 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; // 4 // 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-bit indices. + unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. unsigned int IdxOffset; // 4 // Start offset in index buffer. Always equal to sum of ElemCount drawn so far. + unsigned int ElemCount; // 4 // 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[]. ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // 4-8 // The draw callback code can access this. - ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; } + ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed }; // Vertex index, default to 16-bit @@ -1977,17 +1979,17 @@ 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 _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] ImVector _TextureIdStack; // [Internal] ImVector _Path; // [Internal] current path building + ImDrawCmd _CmdHeader; // [Internal] Template of active commands. Fields should match those of CmdBuffer.back(). ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) // 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; Flags = ImDrawListFlags_None; _VtxCurrentOffset = _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } + ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; Flags = ImDrawListFlags_None; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } ~ImDrawList() { ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e3455812..43daede2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -379,11 +379,17 @@ void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) // Initialize before use in a new frame. We always have a command ready in the buffer. void ImDrawList::ResetForNewFrame() { + // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. + // (those should be IM_STATIC_ASSERT() in theory but with our pre C++11 setup the whole check doesn't compile with GCC) + IM_ASSERT(IM_OFFSETOF(ImDrawCmd, ClipRect) == 0); + IM_ASSERT(IM_OFFSETOF(ImDrawCmd, TextureId) == sizeof(ImVec4)); + IM_ASSERT(IM_OFFSETOF(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID)); + CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); Flags = _Data->InitialFlags; - _VtxCurrentOffset = 0; + memset(&_CmdHeader, 0, sizeof(_CmdHeader)); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -400,7 +406,6 @@ void ImDrawList::ClearFreeMemory() IdxBuffer.clear(); VtxBuffer.clear(); Flags = ImDrawListFlags_None; - _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -420,16 +425,12 @@ ImDrawList* ImDrawList::CloneOutput() const return dst; } -// 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] : (ImTextureID)NULL) - void ImDrawList::AddDrawCmd() { ImDrawCmd draw_cmd; - draw_cmd.ClipRect = GetCurrentClipRect(); - draw_cmd.TextureId = GetCurrentTextureId(); - draw_cmd.VtxOffset = _VtxCurrentOffset; + draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy() + draw_cmd.TextureId = _CmdHeader.TextureId; + draw_cmd.VtxOffset = _CmdHeader.VtxOffset; draw_cmd.IdxOffset = IdxBuffer.Size; IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); @@ -450,68 +451,62 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) AddDrawCmd(); // Force a new command after us (see comment below) } +// Compare ClipRect, TextureId and VtxOffset with a single memcmp() +#define ImDrawCmd_HeaderSize (IM_OFFSETOF(ImDrawCmd, VtxOffset) + sizeof(unsigned int)) +#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset +#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset + // Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. // The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. void ImDrawList::UpdateClipRect() { // If current command is used with different settings we need to add a new command - const ImVec4 curr_clip_rect = GetCurrentClipRect(); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; } // Try to merge with previous command if it matches, else use current command - if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL) { - ImDrawCmd* prev_cmd = curr_cmd - 1; - if (memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) - { - CmdBuffer.pop_back(); - return; - } + CmdBuffer.pop_back(); + return; } - curr_cmd->ClipRect = curr_clip_rect; + curr_cmd->ClipRect = _CmdHeader.ClipRect; } void ImDrawList::UpdateTextureID() { // If current command is used with different settings we need to add a new command - const ImTextureID curr_texture_id = GetCurrentTextureId(); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; } // Try to merge with previous command if it matches, else use current command - if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL) { - ImDrawCmd* prev_cmd = curr_cmd - 1; - if (prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->UserCallback == NULL) - { - CmdBuffer.pop_back(); - return; - } + CmdBuffer.pop_back(); + return; } - curr_cmd->TextureId = curr_texture_id; + curr_cmd->TextureId = _CmdHeader.TextureId; } -#undef GetCurrentClipRect -#undef GetCurrentTextureId - // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) { ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); - if (intersect_with_current_clip_rect && _ClipRectStack.Size) + if (intersect_with_current_clip_rect) { - ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + ImVec4 current = _CmdHeader.ClipRect; if (cr.x < current.x) cr.x = current.x; if (cr.y < current.y) cr.y = current.y; if (cr.z > current.z) cr.z = current.z; @@ -521,6 +516,7 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_ cr.w = ImMax(cr.y, cr.w); _ClipRectStack.push_back(cr); + _CmdHeader.ClipRect = cr; UpdateClipRect(); } @@ -531,21 +527,22 @@ void ImDrawList::PushClipRectFullScreen() void ImDrawList::PopClipRect() { - IM_ASSERT(_ClipRectStack.Size > 0); _ClipRectStack.pop_back(); + _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1]; UpdateClipRect(); } void ImDrawList::PushTextureID(ImTextureID texture_id) { _TextureIdStack.push_back(texture_id); + _CmdHeader.TextureId = texture_id; UpdateTextureID(); } void ImDrawList::PopTextureID() { - IM_ASSERT(_TextureIdStack.Size > 0); _TextureIdStack.pop_back(); + _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1]; UpdateTextureID(); } @@ -558,7 +555,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { - _VtxCurrentOffset = VtxBuffer.Size; + _CmdHeader.VtxOffset = VtxBuffer.Size; _VtxCurrentIdx = 0; AddDrawCmd(); } @@ -1235,9 +1232,9 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, if (font_size == 0.0f) font_size = _Data->FontSize; - IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. - ImVec4 clip_rect = _ClipRectStack.back(); + ImVec4 clip_rect = _CmdHeader.ClipRect; if (cpu_fine_clip_rect) { clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); @@ -1258,7 +1255,7 @@ void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, cons if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; if (push_texture_id) PushTextureID(user_texture_id); @@ -1274,7 +1271,7 @@ void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, con if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; if (push_texture_id) PushTextureID(user_texture_id); @@ -1357,19 +1354,12 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) if (_Channels[i]._CmdBuffer.Size == 0) { ImDrawCmd draw_cmd; - draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); - draw_cmd.TextureId = draw_list->_TextureIdStack.back(); - draw_cmd.VtxOffset = draw_list->_VtxCurrentOffset; + ImDrawCmd_HeaderCopy(&draw_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset _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->VtxOffset == b->VtxOffset && !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. @@ -1390,12 +1380,16 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) 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 && last_cmd != NULL) { - // 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); // FIXME-OPT: Improve for multiple merges. + ImDrawCmd* next_cmd = &ch._CmdBuffer[0]; + if (ImDrawCmd_HeaderCompare(last_cmd, next_cmd) == 0 && last_cmd->UserCallback == NULL && next_cmd->UserCallback == NULL) + { + // Merge previous channel last draw command with current channel first draw command if matching. + last_cmd->ElemCount += next_cmd->ElemCount; + idx_offset += next_cmd->ElemCount; + ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges. + } } if (ch._CmdBuffer.Size > 0) last_cmd = &ch._CmdBuffer.back(); From 117d57df5bdddeaea8a286de8879879f5436a067 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 18:21:10 +0200 Subject: [PATCH 076/223] ImDrawList: Additional comments and extracted bits into ImDrawList::PopUnusedDrawCmd() --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 12 +++--------- imgui.h | 1 + imgui_draw.cpp | 19 ++++++++++++++++--- 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5f9f7b16..6ab1019d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,8 @@ Other Changes: [@thedmd, @Shironekoben, @sergeyn, @ocornut] - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after + a callback draw command would incorrectly override the callback draw command. - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). diff --git a/imgui.cpp b/imgui.cpp index 95dc22a6..1b190a6e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4077,18 +4077,12 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list) { + // Remove trailing command if unused. + // Technically we could return directly instead of popping, but this make things looks neat in Metrics window as well. + draw_list->PopUnusedDrawCmd(); if (draw_list->CmdBuffer.Size == 0) return; - // Remove trailing command if unused - ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.back(); - if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL) - { - draw_list->CmdBuffer.pop_back(); - if (draw_list->CmdBuffer.Size == 0) - 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. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); diff --git a/imgui.h b/imgui.h index 45f3aa7c..de4faf28 100644 --- a/imgui.h +++ b/imgui.h @@ -2061,6 +2061,7 @@ struct ImDrawList // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void ResetForNewFrame(); IMGUI_API void ClearFreeMemory(); + IMGUI_API void PopUnusedDrawCmd(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 43daede2..fb25fecb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -437,6 +437,17 @@ void ImDrawList::AddDrawCmd() CmdBuffer.push_back(draw_cmd); } +// Pop trailing draw command (used before merging or presenting to user) +// Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL +void ImDrawList::PopUnusedDrawCmd() +{ + if (CmdBuffer.Size == 0) + return; + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); +} + void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -1362,13 +1373,12 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) 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. + // 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(); + draw_list->PopUnusedDrawCmd(); // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; @@ -1378,8 +1388,11 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; + + // Equivalent of PopUnusedDrawCmd() for this channel's cmdbuffer and except we don't need to test for UserCallback. if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0) ch._CmdBuffer.pop_back(); + if (ch._CmdBuffer.Size > 0 && last_cmd != NULL) { ImDrawCmd* next_cmd = &ch._CmdBuffer[0]; From e35a813d5767397d211644385f0dee95df54acca Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 18:35:13 +0200 Subject: [PATCH 077/223] ImDrawList: Separating PrimXXX sections from more internals helper in the header file. --- imgui.h | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index de4faf28..70675189 100644 --- a/imgui.h +++ b/imgui.h @@ -2057,19 +2057,22 @@ struct ImDrawList 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 ResetForNewFrame(); - IMGUI_API void ClearFreeMemory(); - IMGUI_API void PopUnusedDrawCmd(); + // Advanced: Primitives allocations + // - We render triangles (three vertices) + // - All primitives needs to be reserved via PrimReserve() beforehand. IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); IMGUI_API void PrimQuadUV(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); - inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } - inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } - inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index + + // [Internal helpers] + IMGUI_API void ResetForNewFrame(); + IMGUI_API void ClearFreeMemory(); + IMGUI_API void PopUnusedDrawCmd(); IMGUI_API void UpdateClipRect(); IMGUI_API void UpdateTextureID(); }; From b1f2eacdf3b7ce64decbfd2e5e30819d05cf2ee1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 18:38:23 +0200 Subject: [PATCH 078/223] ImDrawList: Prefixed internal functions with underscore, renamed UpdateClipRect() to _OnChangedClipRect(), UpdateTextureID() -> _OnChangedTextureID() --- imgui.cpp | 14 +++++++------- imgui.h | 12 ++++++------ imgui_draw.cpp | 24 ++++++++++++------------ 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1b190a6e..43e71366 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2994,7 +2994,7 @@ void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window) window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity; window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity; window->IDStack.clear(); - window->DrawList->ClearFreeMemory(); + window->DrawList->_ClearFreeMemory(); window->DC.ChildWindows.clear(); window->DC.ItemFlagsStack.clear(); window->DC.ItemWidthStack.clear(); @@ -3777,11 +3777,11 @@ void ImGui::NewFrame() if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; - g.BackgroundDrawList.ResetForNewFrame(); + g.BackgroundDrawList._ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); - g.ForegroundDrawList.ResetForNewFrame(); + g.ForegroundDrawList._ResetForNewFrame(); g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.ForegroundDrawList.PushClipRectFullScreen(); @@ -4019,8 +4019,8 @@ void ImGui::Shutdown(ImGuiContext* context) g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); - g.BackgroundDrawList.ClearFreeMemory(); - g.ForegroundDrawList.ClearFreeMemory(); + g.BackgroundDrawList._ClearFreeMemory(); + g.ForegroundDrawList._ClearFreeMemory(); g.TabBars.Clear(); g.CurrentTabBarStack.clear(); @@ -4079,7 +4079,7 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d { // Remove trailing command if unused. // Technically we could return directly instead of popping, but this make things looks neat in Metrics window as well. - draw_list->PopUnusedDrawCmd(); + draw_list->_PopUnusedDrawCmd(); if (draw_list->CmdBuffer.Size == 0) return; @@ -5859,7 +5859,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // DRAWING // Setup draw list and outer clipping rectangle - window->DrawList->ResetForNewFrame(); + window->DrawList->_ResetForNewFrame(); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); diff --git a/imgui.h b/imgui.h index 70675189..b6c91a03 100644 --- a/imgui.h +++ b/imgui.h @@ -1991,7 +1991,7 @@ struct ImDrawList // 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; Flags = ImDrawListFlags_None; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } - ~ImDrawList() { ClearFreeMemory(); } + ~ImDrawList() { _ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); @@ -2070,11 +2070,11 @@ struct ImDrawList inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index // [Internal helpers] - IMGUI_API void ResetForNewFrame(); - IMGUI_API void ClearFreeMemory(); - IMGUI_API void PopUnusedDrawCmd(); - IMGUI_API void UpdateClipRect(); - IMGUI_API void UpdateTextureID(); + IMGUI_API void _ResetForNewFrame(); + IMGUI_API void _ClearFreeMemory(); + IMGUI_API void _PopUnusedDrawCmd(); + IMGUI_API void _OnChangedClipRect(); + IMGUI_API void _OnChangedTextureID(); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index fb25fecb..d0ea99fb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -377,7 +377,7 @@ void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) } // Initialize before use in a new frame. We always have a command ready in the buffer. -void ImDrawList::ResetForNewFrame() +void ImDrawList::_ResetForNewFrame() { // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. // (those should be IM_STATIC_ASSERT() in theory but with our pre C++11 setup the whole check doesn't compile with GCC) @@ -400,7 +400,7 @@ void ImDrawList::ResetForNewFrame() CmdBuffer.push_back(ImDrawCmd()); } -void ImDrawList::ClearFreeMemory() +void ImDrawList::_ClearFreeMemory() { CmdBuffer.clear(); IdxBuffer.clear(); @@ -439,7 +439,7 @@ void ImDrawList::AddDrawCmd() // Pop trailing draw command (used before merging or presenting to user) // Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL -void ImDrawList::PopUnusedDrawCmd() +void ImDrawList::_PopUnusedDrawCmd() { if (CmdBuffer.Size == 0) return; @@ -469,7 +469,7 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) // Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. // The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. -void ImDrawList::UpdateClipRect() +void ImDrawList::_OnChangedClipRect() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -490,7 +490,7 @@ void ImDrawList::UpdateClipRect() curr_cmd->ClipRect = _CmdHeader.ClipRect; } -void ImDrawList::UpdateTextureID() +void ImDrawList::_OnChangedTextureID() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -528,7 +528,7 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_ _ClipRectStack.push_back(cr); _CmdHeader.ClipRect = cr; - UpdateClipRect(); + _OnChangedClipRect(); } void ImDrawList::PushClipRectFullScreen() @@ -540,21 +540,21 @@ void ImDrawList::PopClipRect() { _ClipRectStack.pop_back(); _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1]; - UpdateClipRect(); + _OnChangedClipRect(); } void ImDrawList::PushTextureID(ImTextureID texture_id) { _TextureIdStack.push_back(texture_id); _CmdHeader.TextureId = texture_id; - UpdateTextureID(); + _OnChangedTextureID(); } void ImDrawList::PopTextureID() { _TextureIdStack.pop_back(); _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1]; - UpdateTextureID(); + _OnChangedTextureID(); } // Reserve space for a number of vertices and indices. @@ -1378,7 +1378,7 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) return; SetCurrentChannel(draw_list, 0); - draw_list->PopUnusedDrawCmd(); + draw_list->_PopUnusedDrawCmd(); // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; @@ -1427,8 +1427,8 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) 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. - draw_list->UpdateTextureID(); + draw_list->_OnChangedClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. + draw_list->_OnChangedTextureID(); _Count = 1; } From 3bef743df464c5dbbf527981c7f50be7a0f7f719 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 19:06:55 +0200 Subject: [PATCH 079/223] ImDrawList: Clarifying and guarateeing that CmdBuffer.back()->UserCallback should be always be NULL. --- imgui_draw.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d0ea99fb..0af2c3c5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -451,7 +451,8 @@ void ImDrawList::_PopUnusedDrawCmd() void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if (curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) + IM_ASSERT(curr_cmd->UserCallback == NULL); + if (curr_cmd->ElemCount != 0) { AddDrawCmd(); curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -473,11 +474,12 @@ void ImDrawList::_OnChangedClipRect() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + if (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) { AddDrawCmd(); return; } + IM_ASSERT(curr_cmd->UserCallback == NULL); // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = curr_cmd - 1; @@ -494,11 +496,12 @@ void ImDrawList::_OnChangedTextureID() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) || curr_cmd->UserCallback != NULL) + if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) { AddDrawCmd(); return; } + IM_ASSERT(curr_cmd->UserCallback == NULL); // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = curr_cmd - 1; @@ -1427,6 +1430,11 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } } draw_list->_IdxWritePtr = idx_write; + + // Ensure there's always a non-callback draw command trailing the command-buffer + if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL) + draw_list->AddDrawCmd(); + draw_list->_OnChangedClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. draw_list->_OnChangedTextureID(); _Count = 1; @@ -1437,6 +1445,7 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) 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() memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); From 84862ec78e0c2a249c94575a4ee39105e4061e68 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 20:53:11 +0200 Subject: [PATCH 080/223] ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where changing channels with different TextureId, VtxOffset would incorrectly apply new settings to draw channels. (#3129, #3163) --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ab1019d..1ae96e46 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,9 @@ Other Changes: - ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where changing channels with different + TextureId, VtxOffset would incorrectly apply new settings to draw channels. (#3129, #3163) + [@ocornut, @thedmd, @Shironekoben] - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0af2c3c5..94f223ba 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1435,8 +1435,13 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL) draw_list->AddDrawCmd(); - draw_list->_OnChangedClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. - draw_list->_OnChangedTextureID(); + // If current command is used with different settings we need to add a new command + ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount == 0) + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); + _Count = 1; } @@ -1453,6 +1458,13 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int 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; + + // If current command is used with different settings we need to add a new command + ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount == 0) + ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); } //----------------------------------------------------------------------------- From 9b3ce494fdee20f56ee672febe2f9d737a3927cc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 22:38:19 +0200 Subject: [PATCH 081/223] Columns: Lower overhead on column switches and switching to background channel (some stress tests in debug builds went 3->2 ms). (#125) This change benefits Columns but was primarily made with Tables in mind. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 7 ++++++- imgui_internal.h | 1 + imgui_widgets.cpp | 29 +++++++++++++++++++++++++---- 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1ae96e46..459bf25c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,8 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) +- Columns: Lower overhead on column switches and switching to background channel (some of our stress + tests in debug builds went 3->2 ms). Benefits Columns but was primarily made with Tables in mind! - Style: Added style.TabMinWidthForUnselectedCloseButton settings. Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). diff --git a/imgui.cpp b/imgui.cpp index 43e71366..fd84ed03 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4167,7 +4167,12 @@ static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_da } } -// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +// - When using this function it is sane to ensure that float are perfectly rounded to integer values, +// so that e.g. (int)(max.x-min.x) in user's render produce correct result. +// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): +// some frequently called functions which to modify both channels and clipping simultaneously tend to use a more +// specialized code path to added extraneous updates of the underlying ImDrawCmd. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/imgui_internal.h b/imgui_internal.h index 7b15e63f..b07c5568 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -435,6 +435,7 @@ struct IMGUI_API ImRect void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } + ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } }; // Helper: ImBitArray diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ba7c6b4..7d5bc5cf 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7549,6 +7549,11 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop + //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PushColumnsBackground()\n"); + window->DrawList->_CmdHeader.ClipRect = columns->HostClipRect.ToVec4(); + columns->Splitter.SetCurrentChannel(window->DrawList, 0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); @@ -7562,6 +7567,12 @@ void ImGui::PopColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop + //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PopColumnsBackground()\n"); + ImVec4 pop_clip_rect = window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 2]; + window->DrawList->_CmdHeader.ClipRect = pop_clip_rect; + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); PopClipRect(); } @@ -7684,11 +7695,22 @@ void ImGui::NextColumn() return; } PopItemWidth(); - PopClipRect(); + + // Next column + if (++columns->Current == columns->Count) + columns->Current = 0; + + // As a small optimization, to avoid doing PopClipRect() + SetCurrentChannel() + PushClipRect() + // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), + // We use a shortcut: we override ClipRect in window and drawlist's CmdHeader + SetCurrentChannel(). + ImGuiColumnData* column = &columns->Columns[columns->Current]; + window->ClipRect = column->ClipRect; + window->DrawList->_CmdHeader.ClipRect = column->ClipRect.ToVec4(); + //PopClipRect(); const float column_padding = g.Style.ItemSpacing.x; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (++columns->Current < columns->Count) + if (columns->Current > 0) { // Columns 1+ ignore IndentX (by canceling it out) // FIXME-COLUMNS: Unnecessary, could be locked? @@ -7701,7 +7723,6 @@ void ImGui::NextColumn() // Column 0 honor IndentX window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); columns->Splitter.SetCurrentChannel(window->DrawList, 1); - columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -7709,7 +7730,7 @@ void ImGui::NextColumn() window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = 0.0f; - PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? + //PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. float offset_0 = GetColumnOffset(columns->Current); From a72754886f703fd73048afc86c3eb1fce844e259 Mon Sep 17 00:00:00 2001 From: Scott Date: Tue, 9 Jun 2020 16:10:37 +0200 Subject: [PATCH 082/223] Docs: Initial draft of fonts documentation (#2861) --- docs/{FONTS.txt => FONTS.md} | 282 ++++++++++++++++------------------- 1 file changed, 127 insertions(+), 155 deletions(-) rename docs/{FONTS.txt => FONTS.md} (59%) diff --git a/docs/FONTS.txt b/docs/FONTS.md similarity index 59% rename from docs/FONTS.txt rename to docs/FONTS.md index e3690f14..9f5c7d7f 100644 --- a/docs/FONTS.txt +++ b/docs/FONTS.md @@ -1,85 +1,134 @@ -dear imgui -FONTS DOCUMENTATION - -Also read https://www.dearimgui.org/faq for more fonts related infos. +## Fonts The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), -a 13 pixels high, pixel-perfect font used by default. -We embed it font in source code so you can use Dear ImGui without any file system access. +a 13 pixels high, pixel-perfect font used by default. We embed it font in source code so you can use Dear ImGui without any file system access. -You may also load external .TTF/.OTF files. -The files in this folder are suggested fonts, provided as a convenience. +You may also load external .TTF/.OTF files. The files in this folder are suggested fonts, provided as a convenience. -Please read the FAQ: https://www.dearimgui.org/faq -Please use the Discord server: http://discord.dearimgui.org and not the Github issue tracker for basic font loading questions. +Fonts are rasterized in a single texture at the time of calling either of +- `io.Fonts->GetTexDataAsAlpha8()` ---------------------------------------- - INDEX: ---------------------------------------- +- `GetTexDataAsRGBA32()/Build()` -- Readme First / FAQ -- Fonts Loading Instructions -- Using Icons -- Using FreeType rasterizer -- Building Custom Glyph Ranges -- Using custom colorful icons -- Embedding Fonts in Source Code -- Credits/Licences for fonts included in repository -- Fonts Links +**Please read the FAQ:** https://www.dearimgui.org/faq +Please use the Discord server: http://discord.dearimgui.org and not the GitHub issue tracker for basic font loading questions. --------------------------------------- - README FIRST / FAQ +| Index | +|:---------------------------------------| +| [Readme First](#readme-first) | +| [Using Icons](#using-icons) | +| [Fonts Loading Instructions](#font-loading-instructions) | +| [FreeType Rasterizer, Small Font Sizes](#freeType-rasterizer-small-font-sizes) | +| [Building Custom Glyph Ranges](#building-custom-glyph-ranges) | +| [Using Custom Colorful Icons](#using-custom-colorful-icons) | +| [Embedding Fonts In Source Code](#embedding-fonts-in-source-code) | +| [Credits/Licenses For Fonts Included In This Folder](#creditslicenses-for-fonts-included-in-this-folder) | +| [Font Links](#font-links) | + + --------------------------------------- + ## Readme First - 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. -- Fonts are rasterized in a single texture at the time of calling either of io.Fonts->GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build(). -- Make sure your font ranges data are persistent and available at the time the font atlas is being built. +- 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" u8"こんにちは" // this will be encoded as UTF-8 -- If you want to include a backslash \ character in your string literal, you need to double them e.g. "folder\\filename". - Read FAQ for details. + ``` +- If you want to include a backslash \ character in your string literal, you need to double them e.g. "folder\\\filename". --------------------------------------- - FONTS LOADING INSTRUCTIONS ---------------------------------------- + ## Using Icons -Load default font: +- Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. +- A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth. +- To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: + https://github.com/juliettef/IconFontCppHeaders + +**The C++11 version of those files uses the u8"" utf-8 encoding syntax + \u** + + ` #define ICON_FA_SEARCH u8"\uf002" ` +**The pre-C++11 version has the values directly encoded as utf-8:** + + ` #define ICON_FA_SEARCH "\xEF\x80\x82" ` + +Example Setup: +```cpp + // Merge icons into default tool font + #include "IconsFontAwesome.h" ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontDefault(); -Load .TTF/.OTF file with: + ImFontConfig config; + config.MergeMode = true; + config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced + static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; + io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); +``` +Example Usage: +```cpp + // Usage, e.g. + ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); + ImGui::Button(ICON_FA_SEARCH " Search"); + // C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" + // ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" +``` +See Links below for other icons fonts and related tools. - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); -Load multiple fonts: +--------------------------------------- + ## Font Loading Instructions +Load default font: +```cpp + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontDefault(); +``` +Load .TTF/.OTF file with: +```cpp ImGuiIO& io = ImGui::GetIO(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); // Select font at runtime - ImGui::Text("Hello"); // use the default font (which is the first loaded font) + ImGui::Text("Hello"); // use the default font (which is the first loaded font) ImGui::PushFont(font2); ImGui::Text("Hello with another font"); ImGui::PopFont(); - +``` For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally): - +```cpp ImFontConfig config; 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)** -Combine two fonts into one: +- 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 set OversampleH/OversampleV to 1 and use a small font size. +- Mind the fact that some graphics drivers have texture size limitation. +- If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. + +Some solutions: + + 1. Reduce glyphs ranges by calculating them from source localization data. + You can use ImFontGlyphRangesBuilder for this purpose, this will be the biggest win! + 2. You may reduce oversampling, e.g. config.OversampleH = config.OversampleV = 1, this will largely reduce your texture size. + 3. Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function). + 4. Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two. +Combine two fonts into one: +```cpp // Load a first font ImFont* font = io.Fonts->AddFontDefault(); @@ -92,28 +141,9 @@ Combine two fonts into one: io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); io.Fonts->Build(); - -Font atlas is too large? - -- 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 set OversampleH/OversampleV to 1 and use a small font size. -- Mind the fact that some graphics drivers have texture size limitation. -- If you are building a PC application, mind the fact that users may run on hardware with lower specs than yours. - -Some solutions: - - - 1) Reduce glyphs ranges by calculating them from source localization data. - You can use ImFontGlyphRangesBuilder for this purpose, this will be the biggest win! - - 2) You may reduce oversampling, e.g. config.OversampleH = config.OversampleV = 1, this will largely reduce your texture size. - - 3) Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function). - - 4) Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two. - - Read about oversampling here: https://github.com/nothings/stb/blob/master/tests/oversample - - +``` Add a fourth parameter to bake specific font ranges only: - +```cpp // Basic Latin, Extended Latin io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); @@ -122,79 +152,31 @@ Add a fourth parameter to bake specific font ranges only: // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); - -See "BUILDING CUSTOM GLYPH RANGES" section to create your own ranges. +``` +See [Building Custom Glyph Ranges](#building-custom-glyph-ranges) section to create your own ranges. Offset font vertically by altering the io.Font->DisplayOffset value: - +```cpp ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); font->DisplayOffset.y = 1; // Render 1 pixel down +``` - ---------------------------------------- - USING ICONS --------------------------------------- + ## Freetype Rasterizer, Small Font Sizes -Using an icon font (such as FontAwesome: http://fontawesome.io or OpenFontIcons. https://github.com/traverseda/OpenFontIcons) -is an easy and practical way to use icons in your Dear ImGui application. -A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without -having to change fonts back and forth. - -To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: - - https://github.com/juliettef/IconFontCppHeaders - -Those files contains a bunch of named #define which you can use to refer to specific icons of the font, e.g.: - - #define ICON_FA_MUSIC "\xef\x80\x81" - #define ICON_FA_SEARCH "\xef\x80\x82" - -Example Setup: +- Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. +- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder. +- FreeType supports auto-hinting which tends to improve the readability of small fonts. - // Merge icons into default tool font - #include "IconsFontAwesome.h" - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontDefault(); - - ImFontConfig config; - config.MergeMode = true; - config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced - static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; - io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); - -Example Usage: - - // Usage, e.g. - ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); - ImGui::Button(ICON_FA_SEARCH " Search"); - -Important to understand: C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" -ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" - -See Links below for other icons fonts and related tools. +**Note** +- This code currently creates textures that are unoptimally too large (could be fixed with some work). +- Also note that correct sRGB space blending will have an important effect on your font rendering quality. --------------------------------------- - FREETYPE RASTERIZER, SMALL FONT SIZES ---------------------------------------- - -Dear ImGui uses imstb_truetype.h to rasterize fonts (with optional oversampling). -This technique and its implementation are not ideal for fonts rendered at _small sizes_, which may appear a -little blurry or hard to read. - -There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder. - -FreeType supports auto-hinting which tends to improve the readability of small fonts. -Note that this code currently creates textures that are unoptimally too large (could be fixed with some work). -Also note that correct sRGB space blending will have an important effect on your font rendering quality. - - ---------------------------------------- - BUILDING CUSTOM GLYPH RANGES ---------------------------------------- - -You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input. -For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. + ## Building Custom Glyph Ranges +You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. +```cpp ImVector ranges; ImFontGlyphRangesBuilder builder; builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) @@ -204,21 +186,18 @@ For example: for a game where your script is known, if you can feed your entire io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. +``` - ---------------------------------------- - USING CUSTOM COLORFUL ICONS --------------------------------------- +## 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. +**(This is a BETA api, use if you are familiar with dear imgui and with your rendering back-end)** -Pseudo-code: +- 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 two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font ImFont* font = io.Fonts->AddFontDefault(); int rect_ids[2]; @@ -247,29 +226,25 @@ Pseudo-code: } } } +``` - ---------------------------------------- - EMBEDDING FONTS IN SOURCE CODE --------------------------------------- + ## Embedding Fonts In Source Code -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 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. +- 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 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, ...); -or: - ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); + ` ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); ` +or + `ImFont* font = io.Fonts- AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); + ` --------------------------------------- - CREDITS/LICENSES FOR FONTS INCLUDED IN REPOSITORY ---------------------------------------- - -Some fonts are available in the misc/fonts/ folder: + ## Credits/Licenses For Fonts Included In This Folder Roboto-Medium.ttf @@ -309,10 +284,9 @@ Karla-Regular.ttf --------------------------------------- - FONTS LINKS ---------------------------------------- + ## Font Links -ICON FONTS +#### ICON FONTS C/C++ header for icon fonts (#define with code points to use in source code string literals) https://github.com/juliettef/IconFontCppHeaders @@ -332,7 +306,7 @@ ICON FONTS IcoMoon - Custom Icon font builder https://icomoon.io/app -REGULAR FONTS +#### REGULAR FONTS Google Noto Fonts (worldwide languages) https://www.google.com/get/noto/ @@ -343,17 +317,15 @@ REGULAR FONTS (Japanese) M+ fonts by Coji Morishita are free http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html -MONOSPACE FONTS (PIXEL PERFECT) +#### MONOSPACE FONTS - Proggy Fonts, by Tristan Grimmer + (Pixel Perfect) Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net - Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) + (Pixel Perfect) Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font Also include .inl file to use directly in dear imgui. -MONOSPACE FONTS (REGULAR) - Google Noto Mono Fonts https://www.google.com/get/noto/ From 40b799023b6dc3820c9040df55723d8d4a801897 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Jun 2020 16:29:00 +0200 Subject: [PATCH 083/223] Docs: Update fonts.md (#2861) + update all references to FONTS.txt --- docs/FAQ.md | 8 +- docs/FONTS.md | 479 +++++++++++----------- examples/example_allegro5/main.cpp | 2 +- examples/example_emscripten/main.cpp | 2 +- examples/example_glfw_opengl2/main.cpp | 2 +- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_glfw_vulkan/main.cpp | 2 +- examples/example_glut_opengl2/main.cpp | 2 +- examples/example_marmalade/main.cpp | 2 +- examples/example_sdl_directx11/main.cpp | 2 +- examples/example_sdl_opengl2/main.cpp | 2 +- examples/example_sdl_opengl3/main.cpp | 2 +- examples/example_sdl_vulkan/main.cpp | 2 +- examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- examples/example_win32_directx12/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 2 +- imgui.cpp | 2 +- imgui.h | 4 +- imgui_demo.cpp | 12 +- 20 files changed, 271 insertions(+), 264 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 6c140760..15e2cd73 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -454,7 +454,7 @@ Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear img (Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.) -(Read the [docs/FONTS.txt](https://github.com/ocornut/imgui/blob/master/docs/FONTS.txt) file for more details about font loading.) +(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file for more details about font loading.) New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash "\\": @@ -473,9 +473,9 @@ io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT The most convenient and practical way is to merge an icon font such as FontAwesome inside you 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 [docs/FONTS.txt](https://github.com/ocornut/imgui/blob/master/docs/FONTS.txt) file for more details about icons font loading.) +(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) 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 docs/FONTS.txt about using the AddCustomRectFontGlyph API. +and copying your own graphics data into it. See docs/FONTS.md about using the AddCustomRectFontGlyph API. ##### [Return to Index](#index) @@ -483,7 +483,7 @@ and copying your own graphics data into it. See docs/FONTS.txt about using the A ### Q: How can I load multiple fonts? Use the font atlas to pack them into a single texture: -(Read the [docs/FONTS.txt](https://github.com/ocornut/imgui/blob/master/docs/FONTS.txt) file and the code in ImFontAtlas for more details.) +(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file and the code in ImFontAtlas for more details.) ```cpp ImGuiIO& io = ImGui::GetIO(); diff --git a/docs/FONTS.md b/docs/FONTS.md index 9f5c7d7f..d2f40f2b 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -1,272 +1,306 @@ -## Fonts +## Dear ImGui: Using Fonts -The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), -a 13 pixels high, pixel-perfect font used by default. We embed it font in source code so you can use Dear ImGui without any file system access. - -You may also load external .TTF/.OTF files. The files in this folder are suggested fonts, provided as a convenience. - -Fonts are rasterized in a single texture at the time of calling either of +(You may browse this document at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer.) -- `io.Fonts->GetTexDataAsAlpha8()` - -- `GetTexDataAsRGBA32()/Build()` +The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), +a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions. -**Please read the FAQ:** https://www.dearimgui.org/faq -Please use the Discord server: http://discord.dearimgui.org and not the GitHub issue tracker for basic font loading questions. +You may also load external .TTF/.OTF files. +In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience. +**Read the FAQ:** https://www.dearimgui.org/faq (there is a Fonts section!) ---------------------------------------- -| Index | -|:---------------------------------------| -| [Readme First](#readme-first) | -| [Using Icons](#using-icons) | -| [Fonts Loading Instructions](#font-loading-instructions) | -| [FreeType Rasterizer, Small Font Sizes](#freeType-rasterizer-small-font-sizes) | -| [Building Custom Glyph Ranges](#building-custom-glyph-ranges) | -| [Using Custom Colorful Icons](#using-custom-colorful-icons) | -| [Embedding Fonts In Source Code](#embedding-fonts-in-source-code) | -| [Credits/Licenses For Fonts Included In This Folder](#creditslicenses-for-fonts-included-in-this-folder) | -| [Font Links](#font-links) | +**Use the Discord server**: http://discord.dearimgui.org and not the GitHub issue tracker for basic font loading questions. +## Index +- [Readme First](#readme-first) +- [Fonts Loading Instructions](#font-loading-instructions) +- [Using Icons](#using-icons) +- [Using FreeType Rasterizer](#using-freetype-rasterizer) +- [Using Custom Glyph Ranges](#using-custom-glyph-ranges) +- [Using Custom Colorful Icons](#using-custom-colorful-icons) +- [Using Font Data Embedded In Source Code](#using-font-data-embedded-in-source-code) +- [About filenames](#about-filenames) +- [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository) +- [Font Links](#font-links) --------------------------------------- ## Readme First -- 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" - u8"こんにちは" // this will be encoded as UTF-8 - ``` -- If you want to include a backslash \ character in your string literal, you need to double them e.g. "folder\\\filename". - +- All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas. ---------------------------------------- - ## Using Icons +- 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. You can also reach it in `Demo->Tools->Style Editor->Fonts`: -- Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. -- A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth. -- To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: - https://github.com/juliettef/IconFontCppHeaders +![imgui_capture_0008](https://user-images.githubusercontent.com/8225057/84162822-1a731f00-aa71-11ea-9b6b-89c2332aa161.png) -**The C++11 version of those files uses the u8"" utf-8 encoding syntax + \u** +- Make sure your font ranges data are persistent (available during the calls to `GetTexDataAsAlpha8()`/`GetTexDataAsRGBA32()/`Build()`. - ` #define ICON_FA_SEARCH u8"\uf002" ` +- Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.: +```cpp +u8"hello" +u8"こんにちは" // this will be encoded as UTF-8 +``` -**The pre-C++11 version has the values directly encoded as utf-8:** +##### [Return to Index](#index) - ` #define ICON_FA_SEARCH "\xEF\x80\x82" ` +## Font Loading Instructions -Example Setup: +**Load default font:** ```cpp - // Merge icons into default tool font - #include "IconsFontAwesome.h" - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontDefault(); - - ImFontConfig config; - config.MergeMode = true; - config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced - static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; - io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontDefault(); ``` -Example Usage: + +**Load .TTF/.OTF file with:** ```cpp - // Usage, e.g. - ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); - ImGui::Button(ICON_FA_SEARCH " Search"); - // C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" - // ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ``` -See Links below for other icons fonts and related tools. +If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully. +**Load multiple fonts:** +```cpp +ImGuiIO& io = ImGui::GetIO(); +ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); +ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); + +// Select font at runtime +ImGui::Text("Hello"); // use the default font (which is the first loaded font) +ImGui::PushFont(font2); +ImGui::Text("Hello with another font"); +ImGui::PopFont(); +``` ---------------------------------------- - ## Font Loading Instructions +**For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** +```cpp +ImFontConfig config; +config.OversampleH = 2; +config.OversampleV = 1; +config.GlyphExtraSpacing.x = 1.0f; +ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); +``` -Load default font: +**Combine multiple fonts into one:** ```cpp - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontDefault(); +// Load a first font +ImFont* font = io.Fonts->AddFontDefault(); + +// Add character ranges and merge into the previous font +// The ranges array is not copied by the AddFont* functions and is used lazily +// so ensure it is available at the time of building or calling GetTexDataAsRGBA32(). +static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope. +ImFontConfig config; +config.MergeMode = true; +io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge into first font +io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); // Merge into first font +io.Fonts->Build(); ``` -Load .TTF/.OTF file with: + +**Add a fourth parameter to bake specific font ranges only:** ```cpp - ImGuiIO& io = ImGui::GetIO(); - ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); - ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); - - // Select font at runtime - ImGui::Text("Hello"); // use the default font (which is the first loaded font) - ImGui::PushFont(font2); - ImGui::Text("Hello with another font"); - ImGui::PopFont(); +// Basic Latin, Extended Latin +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); + +// Default + Selection of 2500 Ideographs used by Simplified Chinese +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); + +// Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); ``` -For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally): +See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges. + +**Offset font vertically by altering the `io.Font->DisplayOffset` value:** ```cpp - ImFontConfig config; - config.OversampleH = 2; - config.OversampleV = 1; - config.GlyphExtraSpacing.x = 1.0f; - ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); +ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); +font->DisplayOffset.y = 1; // Render 1 pixel down ``` -**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 set OversampleH/OversampleV to 1 and use a small font size. +**Font Atlas too large?** + +- 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 set `OversampleH`/`OversampleV` to 1 and use a small font size. - Mind the fact that some graphics drivers have texture size limitation. - If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. Some solutions: - 1. Reduce glyphs ranges by calculating them from source localization data. - You can use ImFontGlyphRangesBuilder for this purpose, this will be the biggest win! - 2. You may reduce oversampling, e.g. config.OversampleH = config.OversampleV = 1, this will largely reduce your texture size. - 3. Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function). - 4. Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two. +1. Reduce glyphs ranges by calculating them from source localization data. + You can use the `ImFontGlyphRangesBuilder` for this purpose, this will be the biggest win! +2. You may reduce oversampling, e.g. `font_config.OversampleH = font_config.OversampleV = 1`, this will largely reduce your texture size. +3. Set `io.Fonts.TexDesiredWidth` to specify a texture width to minimize texture height (see comment in `ImFontAtlas::Build()` function). +4. Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. +5. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample). -Combine two fonts into one: -```cpp - // Load a first font - ImFont* font = io.Fonts->AddFontDefault(); - - // Add character ranges and merge into the previous font - // The ranges array is not copied by the AddFont* functions and is used lazily - // so ensure it is available at the time of building or calling GetTexDataAsRGBA32(). - static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope. - ImFontConfig config; - config.MergeMode = true; - io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); - io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); - io.Fonts->Build(); -``` -Add a fourth parameter to bake specific font ranges only: -```cpp - // Basic Latin, Extended Latin - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); +##### [Return to Index](#index) + +## Using Icons + +Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. +A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth. - // Default + Selection of 2500 Ideographs used by Simplified Chinese - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); +To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: https://github.com/juliettef/IconFontCppHeaders. + +So you can use `ICON_FA_SEARCH` as a string that will render as a "Search" icon. - // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); +Example Setup: +```cpp +// Merge icons into default tool font +#include "IconsFontAwesome.h" +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontDefault(); + +ImFontConfig config; +config.MergeMode = true; +config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced +static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; +io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); ``` -See [Building Custom Glyph Ranges](#building-custom-glyph-ranges) section to create your own ranges. -Offset font vertically by altering the io.Font->DisplayOffset value: +Example Usage: ```cpp - ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); - font->DisplayOffset.y = 1; // Render 1 pixel down +// Usage, e.g. +ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); +ImGui::Button(ICON_FA_SEARCH " Search"); +// C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" +// ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" ``` +See Links below for other icons fonts and related tools. ---------------------------------------- - ## Freetype Rasterizer, Small Font Sizes +Here's an application using icons ("Avoyd", https://www.avoyd.com): +![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg) + +##### [Return to Index](#index) + +## Using FreeType Rasterizer - Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. -- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder. +- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. - FreeType supports auto-hinting which tends to improve the readability of small fonts. +- Read documentation in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. +- Correct sRGB space blending will have an important effect on your font rendering quality. -**Note** -- This code currently creates textures that are unoptimally too large (could be fixed with some work). -- Also note that correct sRGB space blending will have an important effect on your font rendering quality. +##### [Return to Index](#index) +## Using Custom Glyph Ranges ---------------------------------------- - ## Building Custom Glyph Ranges - -You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. +You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. ```cpp - ImVector ranges; - ImFontGlyphRangesBuilder builder; - builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) - builder.AddChar(0x7262); // Add a specific character - builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges - builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) - - io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); - io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. +ImVector ranges; +ImFontGlyphRangesBuilder builder; +builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) +builder.AddChar(0x7262); // Add a specific character +builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges +builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) + +io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); +io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. ``` ---------------------------------------- +##### [Return to Index](#index) + ## 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. +- 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. +- This API is beta because it is likely to change in order to support multi-dpi (multiple viewports on multiple monitors with varying DPI scale). #### Pseudo-code: -``` - // Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font - ImFont* font = io.Fonts->AddFontDefault(); - 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(); - - // Retrieve texture in RGBA format - unsigned char* tex_pixels = NULL; - int tex_width, tex_height; - io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); - - for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) - { - int rect_id = rects_ids[rect_n]; - if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) - { - // 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); - } - } - } +```cpp +// Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font +ImFont* font = io.Fonts->AddFontDefault(); +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(); + +// Retrieve texture in RGBA format +unsigned char* tex_pixels = NULL; +int tex_width, tex_height; +io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); + +for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) +{ + int rect_id = rects_ids[rect_n]; + if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) + { + // 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); + } + } +} ``` ---------------------------------------- - ## Embedding Fonts In Source Code +##### [Return to Index](#index) + +## Using Font Data Embedded In Source Code -- 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). +- Compile and use [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/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](https://github.com/ocornut/imgui/blob/master/misc/fonts/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](https://github.com/ocornut/imgui/blob/master/docs/README.md)). - 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, ...); ` +```cpp +ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); +``` or - `ImFont* font = io.Fonts- AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); - ` +```cpp +ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); +``` +##### [Return to Index](#index) ---------------------------------------- - ## Credits/Licenses For Fonts Included In This Folder +## About filenames -Roboto-Medium.ttf +**Please note that many new C/C++ users have issues their files _because the filename they provide is wrong_.** + +Two things to watch for: +- Make sure your IDE/debugger settings starts your executable from the right working directory. In Visual Studio you can change your working directory in project `Properties > General > Debugging > Working Directory`. People assume that their execution will start from the root folder of the project, where by default it oftens start from the folder where object or executable files are stored. +```cpp +// Relative filename depends on your Working Directory when running your program! +io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); + +// Load from the parent folder of your Working Directory +io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); +``` +- In C/C++ and most programming languages if you want to use a backslash `\` within a string literal, you need to write it double backslash `\\`. At it happens, Windows uses backslashes as a path separator, so be mindful. +```cpp +io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!! +io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT +``` +In some situations, you may also use `/` path separator under Windows. + +##### [Return to Index](#index) + +## Credits/Licenses For Fonts Included In Repository + +Some fonts files are available in the `misc/fonts/` folder: +``` +Roboto-Medium.ttf Apache License 2.0 - by Christian Robertson + by Christian Robetson https://fonts.google.com/specimen/Roboto Cousine-Regular.ttf - by Steve Matteson Digitized data copyright (c) 2010 Google Corporation. Licensed under the SIL Open Font License, Version 1.1 https://fonts.google.com/specimen/Cousine DroidSans.ttf - Copyright (c) Steve Matteson Apache License, version 2.0 https://www.fontsquirrel.com/fonts/droid-sans ProggyClean.ttf - Copyright (c) 2004, 2005 Tristan Grimmer MIT License recommended loading setting: Size = 13.0, DisplayOffset.Y = +1 @@ -281,68 +315,41 @@ ProggyTiny.ttf Karla-Regular.ttf Copyright (c) 2012, Jonathan Pinhorn SIL OPEN FONT LICENSE Version 1.1 +``` +##### [Return to Index](#index) ---------------------------------------- - ## Font Links +## Font Links #### ICON FONTS - C/C++ header for icon fonts (#define with code points to use in source code string literals) - https://github.com/juliettef/IconFontCppHeaders - - FontAwesome - https://fortawesome.github.io/Font-Awesome - - OpenFontIcons - https://github.com/traverseda/OpenFontIcons - - Google Icon Fonts - https://design.google.com/icons/ - - Kenney Icon Font (Game Controller Icons) - https://github.com/nicodinh/kenney-icon-font - - IcoMoon - Custom Icon font builder - https://icomoon.io/app +- C/C++ header for icon fonts (#define with code points to use in source code string literals) https://github.com/juliettef/IconFontCppHeaders +- FontAwesome https://fortawesome.github.io/Font-Awesome +- OpenFontIcons https://github.com/traverseda/OpenFontIcons +- Google Icon Fonts https://design.google.com/icons/ +- Kenney Icon Font (Game Controller Icons) https://github.com/nicodinh/kenney-icon-font +- IcoMoon - Custom Icon font builder https://icomoon.io/app #### REGULAR FONTS - Google Noto Fonts (worldwide languages) - https://www.google.com/get/noto/ - - Open Sans Fonts - https://fonts.google.com/specimen/Open+Sans - - (Japanese) M+ fonts by Coji Morishita are free - http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html +- Google Noto Fonts (worldwide languages) https://www.google.com/get/noto/ +- Open Sans Fonts https://fonts.google.com/specimen/Open+Sans +- (Japanese) M+ fonts by Coji Morishita http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html #### MONOSPACE FONTS - (Pixel Perfect) Proggy Fonts, by Tristan Grimmer - http://www.proggyfonts.net or http://upperbounds.net - - (Pixel Perfect) Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) - 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 - - Programmation fonts - http://s9w.github.io/font_compare/ - - Inconsolata - http://www.levien.com/type/myfonts/inconsolata.html - - Adobe Source Code Pro: Monospaced font family for user interface and coding environments - https://github.com/adobe-fonts/source-code-pro +Pixel Perfect: +- Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net +- Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font (also include an .inl file to use directly in dear imgui.) - Monospace/Fixed Width Programmer's Fonts - http://www.lowing.org/fonts/ +Regular: +- Google Noto Mono Fonts https://www.google.com/get/noto/ +- Typefaces for source code beautification https://github.com/chrissimpkins/codeface +- Programmation fonts http://s9w.github.io/font_compare/ +- Inconsolata http://www.levien.com/type/myfonts/inconsolata.html +- Adobe Source Code Pro: Monospaced font family for ui & coding environments https://github.com/adobe-fonts/source-code-pro +- Monospace/Fixed Width Programmer's Fonts http://www.lowing.org/fonts/ +Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing). - Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing). +##### [Return to Index](#index) diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 5a026840..c32125b6 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -40,7 +40,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index f0eb3a2b..6867b4cd 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -81,7 +81,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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 \\ ! // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details. //io.Fonts->AddFontDefault(); diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index a50b4637..411062fa 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -59,7 +59,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 8df734bd..6a3592f1 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -119,7 +119,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 3ce1984a..80763a01 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -401,7 +401,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index d36c1f84..997eeaef 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -125,7 +125,7 @@ int main(int argc, char** argv) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_marmalade/main.cpp b/examples/example_marmalade/main.cpp index 82435f20..9f2ef798 100644 --- a/examples/example_marmalade/main.cpp +++ b/examples/example_marmalade/main.cpp @@ -34,7 +34,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp index eadf8ff7..61a93070 100644 --- a/examples/example_sdl_directx11/main.cpp +++ b/examples/example_sdl_directx11/main.cpp @@ -69,7 +69,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index ff54ec41..fcd9ae32 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -57,7 +57,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index ae794ef4..3146084d 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -114,7 +114,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 9eaea945..0a2ea9ee 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -385,7 +385,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 41833cb5..f6b8b215 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -62,7 +62,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 05de7433..2cc36a7f 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -62,7 +62,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 8642ad45..6ea896bc 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -96,7 +96,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 33123625..c8ad69f1 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -60,7 +60,7 @@ int main(int, char**) // - 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 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' 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); diff --git a/imgui.cpp b/imgui.cpp index fd84ed03..2d740d1b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -769,7 +769,7 @@ CODE Q: How can I easily use icons in my application? Q: How can I load multiple fonts? Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? - >> See https://www.dearimgui.org/faq and docs/FONTS.txt + >> See https://www.dearimgui.org/faq (docs/FAQ.md) docs/FONTS.md Q&A: Concerns ============= diff --git a/imgui.h b/imgui.h index b6c91a03..3f25e81e 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,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.77 WIP" -#define IMGUI_VERSION_NUM 17601 +#define IMGUI_VERSION_NUM 17602 #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) @@ -2244,7 +2244,7 @@ struct ImFontAtlas // 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 docs/FONTS.txt for more details about using colorful icons. + // Read docs/FONTS.md for more details about using colorful icons. // Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8cece7be..ace91fd0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -152,7 +152,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 docs/FONTS.txt) +// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) static void HelpMarker(const char* desc) { ImGui::TextDisabled("(?)"); @@ -861,7 +861,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("UTF-8 Text")) { // UTF-8 test with Japanese characters - // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.txt for details.) + // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you // can save your source files as 'UTF-8 without signature'). @@ -873,7 +873,7 @@ static void ShowDemoWindowWidgets() ImGui::TextWrapped( "CJK text will only appears if the font was loaded with the appropriate CJK character ranges. " "Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. " - "Read docs/FONTS.txt for details."); + "Read docs/FONTS.md for details."); ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); // Normally we would use u8"blah blah" with the proper characters directly in the string. ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; @@ -3538,7 +3538,7 @@ void ImGui::ShowFontSelector(const char* label) 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 docs/FONTS.txt for more details.\n" + "- Read FAQ and docs/FONTS.md for more details.\n" "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); } @@ -3766,7 +3766,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { // Tips: in a real user application, you may want to merge and use an icon font into the main font, // so instead of "Save"/"Revert" you'd use icons! - // Read the FAQ and docs/FONTS.txt about using icon fonts. It's really easy and super convenient! + // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; } ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; } } @@ -3784,7 +3784,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGuiIO& io = ImGui::GetIO(); ImFontAtlas* atlas = io.Fonts; - HelpMarker("Read FAQ and docs/FONTS.txt for details on font loading."); + HelpMarker("Read FAQ and docs/FONTS.md for details on font loading."); ImGui::PushItemWidth(120); for (int i = 0; i < atlas->Fonts.Size; i++) { From 53f0f972737a42472fce671864cb9b5fa4514562 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Jun 2020 17:29:26 +0200 Subject: [PATCH 084/223] Added FAQ entry about DPI. Added Japanese font loading example. --- docs/CHANGELOG.txt | 2 ++ docs/FAQ.md | 28 ++++++++++++++++++++++++++-- docs/FONTS.md | 34 ++++++++++++++++++++++++++++++++++ imgui.cpp | 3 ++- 4 files changed, 64 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 459bf25c..90e06972 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other Changes: - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after a callback draw command would incorrectly override the callback draw command. - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. +- Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. + Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). Fixed a static contructor which led to this dependency on some compiler setups (unclear which). diff --git a/docs/FAQ.md b/docs/FAQ.md index 15e2cd73..5e824b86 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -27,6 +27,7 @@ or view this file with any Markdown viewer. | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | | [How can I display custom shapes? (using low-level ImDrawList API)](#q-how-can-i-display-custom-shapes-using-low-level-imdrawlist-api) | | **Q&A: Fonts, Text** | +| [How should I handle DPi in my application?](#q-how-should-i-handle-dpi-in-my-application) | | [How can I load a different font than the default?](#q-how-can-i-load-a-different-font-than-the-default) | | [How can I easily use icons in my application?](#q-how-can-i-easily-use-icons-in-my-application) | | [How can I load multiple fonts?](#q-how-can-i-load-multiple-fonts) | @@ -441,10 +442,33 @@ ImGui::End(); # Q&A: Fonts, Text +### Q: How should I handle DPI in my application? + +The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. + +Your application may want to detect DPI change and reload the font and reset style being frames. + +Your ui code should avoid using hardcoded constants for size and positioning. Prefer to express values as multiple of reference values such as `ImGui::GetFontSize()` or `ImGui::GetFrameHeight()`. So e.g. instead of seeing a hardcoded height of 500 for a given item/window, you may want to use `30*ImGui::GetFontSize()` instead. + +Down the line Dear ImGui will provide a variety of standardized reference values to facilitate using this. + +Applications in the `examples/` folder are not DPI aware partly because they are unable to load a custom font from the file-system (may change that in the future). + +The reason DPI is not auto-magically solved in stock examples is that we don't yet have a satisfying solution for the "multi-dpi" problem (using the `docking` branch: when multiple viewport windows are over multiple monitors using different DPI scale). The current way to handle this on the application side is: +- Create and maintain one font atlas per active DPI scale (e.g. by iterating `platform_io.Monitors[]` before `NewFrame()`). +- Hook `platform_io.OnChangedViewport()` to detect when a `Begin()` call makes a Dear ImGui window change monitor (and therefore DPI). +- In the hook: swap atlas, swap style with correctly sized one, remap the current font from one atlas to the other (may need to maintain a remapping table of your fonts at variying DPI scale). + +This approach is relatively easy and functional but come with two issues: +- It's not possibly to reliably size or position a window ahead of `Begin()` without knowing on which monitor it'll land. +- Style override may be lost during the `Begin()` call crossing monitor boundaries. You may need to do some custom scaling mumbo-jumbo if you want your `OnChangedViewport()` handler to preserve style overrides. + +Please note that if you are not using multi-viewports with multi-monitors using different DPI scale, you can ignore all of this and use the simpler technique recommended at the top. + ### Q: How can I load a different font than the default? Use the font atlas to load the TTF/OTF file you want: -```c +```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() @@ -459,7 +483,7 @@ Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear img New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash "\\": -```c +```cpp io.Fonts->AddFontFromFileTTF("MyFolder\MyFont.ttf", size); // WRONG (you are escaping the M here!) io.Fonts->AddFontFromFileTTF("MyFolder\\MyFont.ttf", size; // CORRECT io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT diff --git a/docs/FONTS.md b/docs/FONTS.md index d2f40f2b..158e08ab 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -14,6 +14,7 @@ In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) fo ## Index - [Readme First](#readme-first) +- [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application) - [Fonts Loading Instructions](#font-loading-instructions) - [Using Icons](#using-icons) - [Using FreeType Rasterizer](#using-freetype-rasterizer) @@ -43,6 +44,13 @@ u8"こんにちは" // this will be encoded as UTF-8 ##### [Return to Index](#index) +## How should I handle DPI in my application? + +See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application). + +##### [Return to Index](#index) + + ## Font Loading Instructions **Load default font:** @@ -51,6 +59,7 @@ ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontDefault(); ``` + **Load .TTF/.OTF file with:** ```cpp ImGuiIO& io = ImGui::GetIO(); @@ -58,6 +67,7 @@ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ``` If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully. + **Load multiple fonts:** ```cpp ImGuiIO& io = ImGui::GetIO(); @@ -71,6 +81,7 @@ ImGui::Text("Hello with another font"); ImGui::PopFont(); ``` + **For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** ```cpp ImFontConfig config; @@ -80,6 +91,7 @@ config.GlyphExtraSpacing.x = 1.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); ``` + **Combine multiple fonts into one:** ```cpp // Load a first font @@ -97,6 +109,7 @@ io.Fonts->Build(); ``` **Add a fourth parameter to bake specific font ranges only:** + ```cpp // Basic Latin, Extended Latin io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); @@ -109,6 +122,27 @@ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRa ``` See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges. + +**Example loading and using a Japanese font:** + +```cpp +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); +``` +```cpp +ImGui::Text(u8"こんにちは!テスト %d", 123); +if (ImGui::Button(u8"ロード")) +{ + // do stuff +} +ImGui::InputText("string", buf, IM_ARRAYSIZE(buf)); +ImGui::SliderFloat("float", &f, 0.0f, 1.0f); +``` + +![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png) +
_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_ + + **Offset font vertically by altering the `io.Font->DisplayOffset` value:** ```cpp ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); diff --git a/imgui.cpp b/imgui.cpp index 2d740d1b..b05f969a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -765,11 +765,12 @@ CODE Q&A: Fonts, Text ================ + Q: How should I handle DPI in my application? Q: How can I load a different font than the default? Q: How can I easily use icons in my application? Q: How can I load multiple fonts? Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? - >> See https://www.dearimgui.org/faq (docs/FAQ.md) docs/FONTS.md + >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md Q&A: Concerns ============= From 16da8e6da6ae58c9ab639eb678d69bd22e729528 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Jun 2020 17:54:19 +0200 Subject: [PATCH 085/223] Revert "Columns: Lower overhead on column switches and switching to background channel (some stress tests in debug builds went 3->2 ms). (#125)" This reverts commit 9b3ce494fdee20f56ee672febe2f9d737a3927cc. --- docs/CHANGELOG.txt | 2 -- imgui.cpp | 7 +------ imgui_internal.h | 1 - imgui_widgets.cpp | 29 ++++------------------------- 4 files changed, 5 insertions(+), 34 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 90e06972..9ca3d387 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,8 +46,6 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) -- Columns: Lower overhead on column switches and switching to background channel (some of our stress - tests in debug builds went 3->2 ms). Benefits Columns but was primarily made with Tables in mind! - Style: Added style.TabMinWidthForUnselectedCloseButton settings. Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). diff --git a/imgui.cpp b/imgui.cpp index b05f969a..4f66fda2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4168,12 +4168,7 @@ static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_da } } -// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. -// - When using this function it is sane to ensure that float are perfectly rounded to integer values, -// so that e.g. (int)(max.x-min.x) in user's render produce correct result. -// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): -// some frequently called functions which to modify both channels and clipping simultaneously tend to use a more -// specialized code path to added extraneous updates of the underlying ImDrawCmd. +// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/imgui_internal.h b/imgui_internal.h index b07c5568..7b15e63f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -435,7 +435,6 @@ struct IMGUI_API ImRect void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } - ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } }; // Helper: ImBitArray diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7d5bc5cf..2ba7c6b4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7549,11 +7549,6 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; - - // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop - //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PushColumnsBackground()\n"); - window->DrawList->_CmdHeader.ClipRect = columns->HostClipRect.ToVec4(); - columns->Splitter.SetCurrentChannel(window->DrawList, 0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); @@ -7567,12 +7562,6 @@ void ImGui::PopColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; - - // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop - //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PopColumnsBackground()\n"); - ImVec4 pop_clip_rect = window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 2]; - window->DrawList->_CmdHeader.ClipRect = pop_clip_rect; - columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); PopClipRect(); } @@ -7695,22 +7684,11 @@ void ImGui::NextColumn() return; } PopItemWidth(); - - // Next column - if (++columns->Current == columns->Count) - columns->Current = 0; - - // As a small optimization, to avoid doing PopClipRect() + SetCurrentChannel() + PushClipRect() - // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), - // We use a shortcut: we override ClipRect in window and drawlist's CmdHeader + SetCurrentChannel(). - ImGuiColumnData* column = &columns->Columns[columns->Current]; - window->ClipRect = column->ClipRect; - window->DrawList->_CmdHeader.ClipRect = column->ClipRect.ToVec4(); - //PopClipRect(); + PopClipRect(); const float column_padding = g.Style.ItemSpacing.x; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (columns->Current > 0) + if (++columns->Current < columns->Count) { // Columns 1+ ignore IndentX (by canceling it out) // FIXME-COLUMNS: Unnecessary, could be locked? @@ -7723,6 +7701,7 @@ void ImGui::NextColumn() // Column 0 honor IndentX window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); columns->Splitter.SetCurrentChannel(window->DrawList, 1); + columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -7730,7 +7709,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? // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. float offset_0 = GetColumnOffset(columns->Current); From 64d8d302fb379dd9d7fbe5475a32bd6d61004db5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Jun 2020 19:16:06 +0200 Subject: [PATCH 086/223] ImDrawList: Fixed VtxOffset change leading to unnecessary leading empty ImDrawCmd in certain cases. --- imgui.h | 1 + imgui_draw.cpp | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 3f25e81e..4de17899 100644 --- a/imgui.h +++ b/imgui.h @@ -2075,6 +2075,7 @@ struct ImDrawList IMGUI_API void _PopUnusedDrawCmd(); IMGUI_API void _OnChangedClipRect(); IMGUI_API void _OnChangedTextureID(); + IMGUI_API void _OnChangedVtxOffset(); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 94f223ba..5b0a9855 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -514,6 +514,21 @@ void ImDrawList::_OnChangedTextureID() curr_cmd->TextureId = _CmdHeader.TextureId; } +void ImDrawList::_OnChangedVtxOffset() +{ + // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this. + _VtxCurrentIdx = 0; + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); + if (curr_cmd->ElemCount != 0) + { + AddDrawCmd(); + return; + } + IM_ASSERT(curr_cmd->UserCallback == NULL); + curr_cmd->VtxOffset = _CmdHeader.VtxOffset; +} + // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) { @@ -570,8 +585,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { _CmdHeader.VtxOffset = VtxBuffer.Size; - _VtxCurrentIdx = 0; - AddDrawCmd(); + _OnChangedVtxOffset(); } ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; From a933cc4f4d366340eff5c6dcb3a927478c9006a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Jun 2020 09:52:46 +0200 Subject: [PATCH 087/223] Documentation update --- docs/FAQ.md | 11 +++++++++-- docs/README.md | 29 ++++++++++++++++------------- imgui.cpp | 3 ++- 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 5e824b86..1401486a 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -20,6 +20,7 @@ or view this file with any Markdown viewer. | [How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)](#q-how-can-i-use-this-on-a-machine-without-mouse-keyboard-or-screen-input-share-remote-display) | | [I integrated Dear ImGui in my engine and the text or lines are blurry..](#q-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..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | +| [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | **Q&A: Usage** | | **[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?](#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)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| @@ -27,7 +28,7 @@ or view this file with any Markdown viewer. | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | | [How can I display custom shapes? (using low-level ImDrawList API)](#q-how-can-i-display-custom-shapes-using-low-level-imdrawlist-api) | | **Q&A: Fonts, Text** | -| [How should I handle DPi in my application?](#q-how-should-i-handle-dpi-in-my-application) | +| [How should I handle DPI in my application?](#q-how-should-i-handle-dpi-in-my-application) | | [How can I load a different font than the default?](#q-how-can-i-load-a-different-font-than-the-default) | | [How can I easily use icons in my application?](#q-how-can-i-easily-use-icons-in-my-application) | | [How can I load multiple fonts?](#q-how-can-i-load-multiple-fonts) | @@ -78,6 +79,9 @@ You may use the [docking](https://github.com/ocornut/imgui/tree/docking) branch Many projects are using this branch and it is kept in sync with master regularly. +You may merge in the [tables](https://github.com/ocornut/imgui/tree/tables) branch which includes: +- [Table features](https://github.com/ocornut/imgui/issues/2957) + ##### [Return to Index](#index) ---- @@ -144,11 +148,14 @@ Also make sure your orthographic projection matrix and io.DisplaySize matches yo --- ### Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. +### Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. You are probably mishandling the clipping rectangles in your render function. -Rectangles provided by ImGui are defined as +Each draw command needs the triangle rendered using the clipping rectangle provided in the ImDrawCmd structure (`ImDrawCmd->CllipRect`). +Rectangles provided by Dear ImGui are defined as `(x1=left,y1=top,x2=right,y2=bottom)` and **NOT** as `(x1,y1,width,height)` +Refer to rendering back-ends in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder for references of how to handle the `ClipRect` field. ##### [Return to Index](#index) diff --git a/docs/README.md b/docs/README.md index 5536c5bc..df32b9c2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,7 +5,7 @@ Dear ImGui (This library is available under a free and permissive license, 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.) Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts: -
  _E-mail: contact @ dearimgui dot org_ +
  _E-mail: contact @ dearimgui dot com_ Individuals: support continued maintenance and development with [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). @@ -99,7 +99,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas 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-20190715.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows binaries, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). -The demo applications are not 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()`. +The demo applications are not 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()` (see [FAQ](https://www.dearimgui.org/faq)). ### Integration @@ -122,11 +122,11 @@ Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. ### Upcoming Changes Some of the goals for 2020 are: -- Finish work on docking, tabs. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/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](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) -- Finish work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) -- Finish work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957)) -- Add an automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) +- Work on docking. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch) +- Work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) +- Work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) +- Work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957)) +- Work on automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) - Make the examples look better, improve styles, improve font support, make the examples hi-DPI and multi-DPI aware. ### Gallery @@ -154,7 +154,7 @@ If you are new to Dear ImGui and have issues with: compiling, linking, adding fo 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. -Paid private support is available for business customers (E-mail: _contact @ dearimgui dot org_). +Private support is available for paying business customers (E-mail: _contact @ dearimgui dot com_). **Which version should I get?** @@ -174,14 +174,14 @@ How to help - You may participate in the [Discord server](http://discord.dearimgui.org), [GitHub forum/issues](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. -- Have your company financially support this project. +- Have your company financially support this project (please reach by e-mail) **How can I help financing further development of Dear ImGui?** Your contributions are keeping this project alive. The library is available under a free and permissive license, 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. Thank you! Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts: -
  _E-mail: contact @ dearimgui dot org_ +
  _E-mail: contact @ dearimgui.com_ Individuals: support continued maintenance and development with [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). @@ -194,7 +194,7 @@ Ongoing Dear ImGui development is financially supported by users and private spo - [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui/) *Double-chocolate and Salty caramel sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) +- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [RAD Game Tools](http://www.radgametools.com/), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors). @@ -208,9 +208,12 @@ Dear ImGui is using software and services provided free of charge for open sourc 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) (PS Vita). +Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect [contributors](https://github.com/ocornut/imgui/graphs/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) (PS Vita). -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. +Recurring contributors (2020): Omar Cornut [@ocornut](https://github.com/ocornut), Rokas Kupstys [@rokups](https://github.com/rokups), Ben Carter [@ShironekoBen](https://github.com/ShironekoBen). +A large portion of work on automation systems, regression tests and other features are currently unpublished. + +"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). diff --git a/imgui.cpp b/imgui.cpp index 4f66fda2..fcdcfd3a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -633,7 +633,8 @@ CODE Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - >> See https://www.dearimgui.org/faq + Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. +>> See https://www.dearimgui.org/faq Q&A: Usage ---------- From d3b37180a3ff186b481d93d09664bb244a428d10 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Sat, 13 Jun 2020 14:14:07 +0200 Subject: [PATCH 088/223] ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra unrequired vertex. Amend 5363af7f47573c8a9231bc44bc6252188affea08, 051ce0765ef8569729c9ae9b3d466132f9010b89 --- docs/CHANGELOG.txt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9ca3d387..9feee86e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,19 +56,21 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] -- ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the +- ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where changing channels with different TextureId, VtxOffset would incorrectly apply new settings to draw channels. (#3129, #3163) [@ocornut, @thedmd, @Shironekoben] -- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after a callback draw command would incorrectly override the callback draw command. +- ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would + generate an extra unrequired vertex. [@ShironekoBen] - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. -- Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. - Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] +- Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. + Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). Fixed a static contructor which led to this dependency on some compiler setups (unclear which). From 90c0c0c163b48b6bb274a4153f96870e9e4dd727 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Jun 2020 15:48:05 +0200 Subject: [PATCH 089/223] Columns: Lower overhead on column switches and switching to background channel. (second attempt for 9b3ce49) Internals: Bits, comments, added ImRect::ToVec4() --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 7 ++++++- imgui_internal.h | 5 ++++- imgui_widgets.cpp | 49 ++++++++++++++++++++++++++++++++-------------- 4 files changed, 46 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9feee86e..9852e5bd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,8 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- Columns: Lower overhead on column switches and switching to background channel. + Benefits Columns but was primarily made with Tables in mind! - ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index fcdcfd3a..c84247a2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4169,7 +4169,12 @@ static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_da } } -// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +// - When using this function it is sane to ensure that float are perfectly rounded to integer values, +// so that e.g. (int)(max.x-min.x) in user's render produce correct result. +// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): +// some frequently called functions which to modify both channels and clipping simultaneously tend to use the +// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/imgui_internal.h b/imgui_internal.h index 7b15e63f..f8ec2fdf 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -435,6 +435,7 @@ struct IMGUI_API ImRect void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } + ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } }; // Helper: ImBitArray @@ -1012,7 +1013,8 @@ struct ImGuiColumns float LineMinY, LineMaxY; 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 HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() + ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns() ImVector Columns; ImDrawListSplitter Splitter; @@ -1894,6 +1896,7 @@ namespace ImGui IMGUI_API bool IsDragDropPayloadBeingAccepted(); // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) + IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect); 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); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ba7c6b4..7fd76823 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7398,6 +7398,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. // In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. //------------------------------------------------------------------------- +// - SetWindowClipRectBeforeSetChannel() [Internal] // - GetColumnIndex() // - GetColumnCount() // - GetColumnOffset() @@ -7415,6 +7416,18 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // - Columns() //------------------------------------------------------------------------- +// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +// they would meddle many times with the underlying ImDrawCmd. +// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +// the subsequent single call to SetCurrentChannel() does it things once. +void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect) +{ + ImVec4 clip_rect_vec4 = clip_rect.ToVec4(); + window->ClipRect = clip_rect; + window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4; + window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4; +} + int ImGui::GetColumnIndex() { ImGuiWindow* window = GetCurrentWindowRead(); @@ -7549,11 +7562,11 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + columns->HostBackupClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect); columns->Splitter.SetCurrentChannel(window->DrawList, 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() @@ -7562,8 +7575,10 @@ void ImGui::PopColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect); columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); - PopClipRect(); } ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) @@ -7611,7 +7626,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->HostInitialClipRect = window->ClipRect; columns->HostWorkRect = window->WorkRect; // Set state for first column @@ -7683,25 +7698,31 @@ void ImGui::NextColumn() IM_ASSERT(columns->Current == 0); return; } + + // Next column + if (++columns->Current == columns->Count) + columns->Current = 0; + PopItemWidth(); - PopClipRect(); + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), + ImGuiColumnData* column = &columns->Columns[columns->Current]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); const float column_padding = g.Style.ItemSpacing.x; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (++columns->Current < columns->Count) + if (columns->Current > 0) { // 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 + column_padding; - columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); } else { - // New row/line - // Column 0 honor IndentX + // New row/line: column 0 honor IndentX. window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); - columns->Splitter.SetCurrentChannel(window->DrawList, 1); - columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -7709,8 +7730,6 @@ void ImGui::NextColumn() 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); From c658cba22b67af4de3da948e4ac39ce9b852a967 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jun 2020 16:18:30 +0200 Subject: [PATCH 090/223] Comments, reworded some !(xxx && xxx) complex expression to be a little less confusing. --- imgui_draw.cpp | 2 +- imgui_widgets.cpp | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5b0a9855..750bf9f6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2906,7 +2906,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c } // Allow wrapping after punctuation. - inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); + inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\"'); } // We ignore blank width at the end of the line (they can be skipped) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7fd76823..bb69d888 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -557,7 +557,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool if ((flags & ImGuiButtonFlags_PressedOnRelease) && mouse_button_released != -1) { // Repeat mode trumps on release behavior - if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay)) + const bool has_repeated_at_least_once = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; + if (!has_repeated_at_least_once) pressed = true; ClearActiveID(); } @@ -3469,18 +3470,22 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f // Generic named filters if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific)) { + // Allow 0-9 . - + * / if (flags & ImGuiInputTextFlags_CharsDecimal) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; + // Allow 0-9 . - + * / e E if (flags & ImGuiInputTextFlags_CharsScientific) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) return false; + // Allow 0-9 a-F A-F if (flags & ImGuiInputTextFlags_CharsHexadecimal) if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return false; + // Turn a-z into A-Z if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') *p_char = (c += (unsigned int)('A'-'a')); @@ -4283,7 +4288,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ PopFont(); // Log as text - if (g.LogEnabled && !(is_password && !is_displaying_hint)) + if (g.LogEnabled && (!is_password || is_displaying_hint)) LogRenderedText(&draw_pos, buf_display, buf_display_end); if (label_size.x > 0) @@ -7157,7 +7162,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) tab_contents_visible = true; - if (tab_appearing && !(tab_bar_appearing && !tab_is_new)) + // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted + // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. + if (tab_appearing && (!tab_bar_appearing || tab_is_new)) { PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true); ItemAdd(ImRect(), id); @@ -7275,7 +7282,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. -// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem() +// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem(). +// Tabs closed by the close button will automatically be flagged to avoid this issue. +// FIXME: We should aim to support calling SetTabItemClosed() after the tab submission (for next frame) void ImGui::SetTabItemClosed(const char* label) { ImGuiContext& g = *GImGui; From 99ab521024ae68d72b8479f66ea2f052e54f2cac Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jun 2020 22:06:45 +0200 Subject: [PATCH 091/223] Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). + Removed CalcItemRectClosestPoint() entry point --- docs/CHANGELOG.txt | 2 ++ docs/TODO.txt | 1 - imgui.cpp | 6 ++++-- imgui.h | 5 +++-- imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 10 +++++----- 6 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9852e5bd..2d70bc8d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,6 +38,8 @@ Breaking Changes: - Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. +- Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). +- Removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. Other Changes: diff --git a/docs/TODO.txt b/docs/TODO.txt index 75438a6a..955fa31a 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -203,7 +203,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i !- 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 - - popups: reopening context menu at new position should be the behavior by default? (equivalent to internal OpenPopupEx() with reopen_existing=true) (~#1497) - popups: if the popup functions took explicit ImGuiID it would allow the user to manage the scope of those ID. (#331) - popups: clicking outside (to close popup) and holding shouldn't drag window below. - popups: add variant using global identifier similar to Begin/End (#402) diff --git a/imgui.cpp b/imgui.cpp index c84247a2..23795c58 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,7 +372,9 @@ 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. - - 2020/04/23 (1.77) - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). + - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). + - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. + - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead. - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value. @@ -7842,7 +7844,7 @@ void ImGui::EndPopup() g.WithinEndChild = false; } -bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) diff --git a/imgui.h b/imgui.h index 4de17899..be56fa35 100644 --- a/imgui.h +++ b/imgui.h @@ -609,7 +609,7 @@ namespace ImGui IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! - IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack. IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. @@ -1632,6 +1632,8 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.77 (from June 2020) + static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1) { return OpenPopupContextItem(str_id, mouse_button); } // OBSOLETED in 1.72 (from July 2019) static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.71 (from June 2019) @@ -1652,7 +1654,6 @@ namespace ImGui // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } - static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { IM_UNUSED(on_edge); IM_UNUSED(outward); IM_ASSERT(0); return pos; } } typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ace91fd0..4c48ade5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2829,11 +2829,11 @@ static void ShowDemoWindowPopups() ImGui::EndPopup(); } - // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the + // We can also use OpenPopupContextItem() 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 open the same popup as above.)"); - ImGui::OpenPopupOnItemClick("item context menu", 1); + ImGui::OpenPopupContextItem("item context menu", 1); // When used after an item that has an ID (e.g.Button), we can skip providing an ID to BeginPopupContextItem(). // BeginPopupContextItem() will use the last item ID as the popup ID. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bb69d888..7ed51369 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4435,7 +4435,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); } } else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) @@ -4460,7 +4460,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); } ImGuiWindow* picker_active_window = NULL; @@ -4481,7 +4481,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag } } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); if (BeginPopup("picker")) { @@ -4701,7 +4701,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl } } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { @@ -4714,7 +4714,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl value_changed = value_changed_sv = true; } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); // Hue bar logic SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); From 1dfd0634cbe70a52a78f1ff247df1db491b745ed Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jun 2020 19:06:20 +0200 Subject: [PATCH 092/223] Internals: Allow ItemHoverable() to be used with id==0 to facilitate high-level read-only hover test in widget code. --- imgui.cpp | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 23795c58..8c0afd06 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3172,17 +3172,22 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) 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(); + // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level + // hover test in widgets code. We could also decide to split this function is two. + if (id != 0) + { + 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; } From d31fe97f741ae57600cc0762804eb5fcf79cbc97 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 16:50:28 +0200 Subject: [PATCH 093/223] Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 36 ++++++++++++++++++++++++++---------- imgui_internal.h | 3 ++- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2d70bc8d..ad078258 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,8 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Popups: Fix an edge case where programatically closing a popup while clicking on its empty space + would attempt to focus it and close other popups. (#2880) - Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index 8c0afd06..07c2ea10 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3449,17 +3449,22 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (g.NavWindow && g.NavWindow->Appearing) return; - // Click to focus window and start moving (after we're done with all our widgets) + // Click on empty space to focus window and start moving (after we're done with all our widgets) if (g.IO.MouseClicked[0]) { - if (g.HoveredRootWindow != NULL) + // Handle the edge case of a popup being closed while clicking in its empty space. + // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. + ImGuiWindow* root_window = g.HoveredRootWindow; + const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpenAtAnyLevel(root_window->PopupId); + + if (root_window != NULL && !is_closed_popup) { StartMouseMovingWindow(g.HoveredWindow); - if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar)) - if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) + if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) + if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; } - else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL) + else if (root_window != NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { // Clicking on void disable focus FocusWindow(NULL); @@ -3700,7 +3705,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) - g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); + g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (g.OpenPopupStack.Size > 0); mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down]) @@ -3718,7 +3723,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() 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()); + g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.OpenPopupStack.Size > 0); // 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) @@ -7610,6 +7615,15 @@ 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); } +bool ImGui::IsPopupOpenAtAnyLevel(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + for (int n = 0; n < g.OpenPopupStack.Size; n++) + if (g.OpenPopupStack[n].PopupId == id) + return true; + return false; +} + ImGuiWindow* ImGui::GetTopMostPopupModal() { ImGuiContext& g = *GImGui; @@ -7661,8 +7675,8 @@ void ImGui::OpenPopupEx(ImGuiID id) else { // Close child popups if any, then flag popup for open/reopen - g.OpenPopupStack.resize(current_stack_size + 1); - g.OpenPopupStack[current_stack_size] = popup_ref; + ClosePopupToLevel(current_stack_size, false); + g.OpenPopupStack.push_back(popup_ref); } // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). @@ -7675,7 +7689,7 @@ void ImGui::OpenPopupEx(ImGuiID id) void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; - if (g.OpenPopupStack.empty()) + if (g.OpenPopupStack.Size == 0) return; // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. @@ -7714,6 +7728,8 @@ void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_ { ImGuiContext& g = *GImGui; IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); + + // Trim open popup stack ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow; ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window; g.OpenPopupStack.resize(remaining); diff --git a/imgui_internal.h b/imgui_internal.h index f8ec2fdf..3e88b054 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1581,7 +1581,7 @@ struct IMGUI_API ImGuiWindow bool WantCollapseToggle; 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 Hidden; // Do not display (== HiddenFrames*** > 0) bool IsFallbackWindow; // Set on the "Debug##Default" window. 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) @@ -1853,6 +1853,7 @@ namespace ImGui 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 at current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! + IMGUI_API bool IsPopupOpenAtAnyLevel(ImGuiID id); IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); From 37eb89371b7ee8b0728b07b2ab437c6281bc8261 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 18:46:14 +0200 Subject: [PATCH 094/223] Popups: Internals: Added IsAnyPopupOpen(). --- imgui.cpp | 22 ++++++++++++++++++---- imgui.h | 5 +++-- imgui_demo.cpp | 2 +- imgui_internal.h | 3 ++- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 07c2ea10..7358b22a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7603,12 +7603,14 @@ void ImGui::SetTooltip(const char* fmt, ...) // [SECTION] POPUPS //----------------------------------------------------------------------------- +// Return true if the popup is open at the current BeginPopup() level of the popup stack bool ImGui::IsPopupOpen(ImGuiID id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; } +// Return true if the popup is open at the current BeginPopup() level of the popup stack bool ImGui::IsPopupOpen(const char* str_id) { ImGuiContext& g = *GImGui; @@ -7624,6 +7626,14 @@ bool ImGui::IsPopupOpenAtAnyLevel(ImGuiID id) return false; } +// Return true if any popup is open at the current BeginPopup() level of the popup stack +// This may be used to e.g. test for another popups already opened in the same frame to handle popups priorities at the same level. +bool ImGui::IsAnyPopupOpen() +{ + ImGuiContext& g = *GImGui; + return g.OpenPopupStack.Size > g.BeginPopupStack.Size; +} + ImGuiWindow* ImGui::GetTopMostPopupModal() { ImGuiContext& g = *GImGui; @@ -7879,8 +7889,10 @@ bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_butt } // This is a helper to handle the simplest case of associating one named popup to one given widget. -// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). -// You can pass a NULL str_id to use the identifier of the last item. +// - You can pass a NULL str_id to use the identifier of the last item. +// - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +// - This is essentially the same as calling OpenPopupContextItem() + BeginPopupEx() but written to avoid +// computing the ID twice because BeginPopupContextXXX functions are called very frequently. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; @@ -7895,9 +7907,10 @@ bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_but bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items) { + ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "window_context"; - ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + ImGuiID id = window->GetID(str_id); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(id); @@ -7906,9 +7919,10 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_b bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button) { + ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "void_context"; - ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + ImGuiID id = window->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); diff --git a/imgui.h b/imgui.h index be56fa35..13657d74 100644 --- a/imgui.h +++ b/imgui.h @@ -602,6 +602,7 @@ namespace ImGui // (*1) You can bypass that restriction and detect hovering even when normally blocked by a popup. // To do this use the ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). // This is what BeginPopupContextItem() and BeginPopupContextWindow() are doing already, allowing a right-click to reopen another popups without losing the click. + // - The BeginPopupContextXXX functions are essentially helpers to do an OpenPopup() in some condition + BeginPopup(). IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! @@ -609,8 +610,8 @@ namespace ImGui IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! - IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. - IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack. + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. // Columns diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4c48ade5..65d24bbd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2813,7 +2813,7 @@ static void ShowDemoWindowPopups() if (ImGui::TreeNode("Context menus")) { // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: - // if (IsItemHovered() && IsMouseReleased(0)) + // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) // OpenPopup(id); // return BeginPopup(id); // For more advanced uses you may want to replicate and customize this code. diff --git a/imgui_internal.h b/imgui_internal.h index 3e88b054..4f101920 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1852,8 +1852,9 @@ namespace ImGui IMGUI_API void OpenPopupEx(ImGuiID id); 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 at current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! + IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id at the current BeginPopup() level of the popup stack (this doesn't scan the whole popup stack!) IMGUI_API bool IsPopupOpenAtAnyLevel(ImGuiID id); + IMGUI_API bool IsAnyPopupOpen(); // Return true if any popup is open at the current BeginPopup() level of the popup stack IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); From 6e138504c1dc097a3b492da193101a9df950f260 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 19:32:21 +0200 Subject: [PATCH 095/223] Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) --- 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 ad078258..47995a88 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Other Changes: Set to an intermediary value to toggle behavior based on width (same as Firefox). - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) +- Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) - Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index 7358b22a..496e71b7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7924,7 +7924,8 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_but str_id = "void_context"; ImGuiID id = window->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) - OpenPopupEx(id); + if (GetTopMostPopupModal() == NULL) + OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } From 078571b7a99d87d83140d5e13f101c5528e25c48 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 23:05:01 +0200 Subject: [PATCH 096/223] Popups: added comments, reorganized the functions in imgui.h --- docs/CHANGELOG.txt | 3 ++- docs/TODO.txt | 4 +++- imgui.cpp | 2 +- imgui.h | 50 ++++++++++++++++++++++++++-------------------- 4 files changed, 34 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 47995a88..a110a596 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,7 +55,7 @@ Other Changes: - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) -- Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] +- Popups: Clarified some of the comments and function prototypes. - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] @@ -63,6 +63,7 @@ Other Changes: drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Columns: Lower overhead on column switches and switching to background channel. Benefits Columns but was primarily made with Tables in mind! +- Fonts: Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] diff --git a/docs/TODO.txt b/docs/TODO.txt index 955fa31a..213d1d35 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -202,11 +202,13 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - 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 + - modals: make modal title bar blink when trying to click outside the modal + - modals: technically speaking, we could make Begin() with ImGuiWindowFlags_Modal work without involving popup. May help untangle a few things, as modals are more like regular windows than popups. - popups: if the popup functions took explicit ImGuiID it would allow the user to manage the scope of those ID. (#331) - popups: clicking outside (to close popup) and holding shouldn't drag window below. - popups: add variant using global identifier similar to Begin/End (#402) - popups: border options. richer api like BeginChild() perhaps? (#197) + - popups/modals: although it is sometimes convenient that popups/modals lifetime is owned by imgui, we could also a bool-owned-by-user api as long as Begin() return value testing is enforced. - tooltip: drag and drop with tooltip near monitor edges lose/changes its last direction instead of locking one. The drag and drop tooltip should always follow without changing direction. - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred direction" and may teleport when moving mouse. diff --git a/imgui.cpp b/imgui.cpp index 496e71b7..584b7a85 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7891,7 +7891,7 @@ bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_butt // This is a helper to handle the simplest case of associating one named popup to one given widget. // - You can pass a NULL str_id to use the identifier of the last item. // - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). -// - This is essentially the same as calling OpenPopupContextItem() + BeginPopupEx() but written to avoid +// - This is essentially the same as calling OpenPopupContextItem() + BeginPopup() but written to avoid // computing the ID twice because BeginPopupContextXXX functions are called very frequently. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) { diff --git a/imgui.h b/imgui.h index 13657d74..fd852a5d 100644 --- a/imgui.h +++ b/imgui.h @@ -591,28 +591,34 @@ namespace ImGui IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); // Popups, Modals - // The properties of popups windows are: - // - They block normal mouse hovering detection outside them. (*1) - // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. - // Because hovering detection is disabled outside the popup, when clicking outside the click will not be seen by underlying widgets! (*1) - // - 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(), CloseCurrentPopup() etc. - // - We default to use the right mouse (ImGuiMouseButton_Right=1) for the Popup Context functions. - // Those three properties are connected: we need to retain popup visibility state in the library because popups may be closed as any time. - // (*1) You can bypass that restriction and detect hovering even when normally blocked by a popup. - // To do this use the ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). - // This is what BeginPopupContextItem() and BeginPopupContextWindow() are doing already, allowing a right-click to reopen another popups without losing the click. - // - The BeginPopupContextXXX functions are essentially helpers to do an OpenPopup() in some condition + BeginPopup(). - IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). - IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! - IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! - IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window. - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). - IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) - IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! - IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) - IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack - IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. + // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. + // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. + // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. + // This is sometimes leading to confusing mistakes. May rework this in the future. + // Popups: begin/end functions + // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window. + // - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar. + IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. + IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! + // Popups: open/close functions + // - OpenPopup(): set popup state to open. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. + // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). + IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. + IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack + // Popups: open+begin combined functions helpers + // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. + // - They are convenient to easily create context menus, hence the name. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1, bool also_over_items = true); // open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked in void (where there are no windows). // Columns // - You can also use SameLine(pos_x) to mimic simplified columns. From b1d8309abcbe67755b2a7e96c1f4a0123db2882e Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Thu, 18 Jun 2020 15:18:14 +0200 Subject: [PATCH 097/223] Added ImGuiTabItemFlags_NoTooltip for individual Tab Item. --- docs/CHANGELOG.txt | 2 ++ imgui.h | 3 ++- imgui_widgets.cpp | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a110a596..b479a333 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,8 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item + (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) diff --git a/imgui.h b/imgui.h index fd852a5d..eb2a611b 100644 --- a/imgui.h +++ b/imgui.h @@ -913,7 +913,8 @@ enum ImGuiTabItemFlags_ 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 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() + ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoTooltip = 1 << 4 // Disable tooltip for the given tab }; // Flags for ImGui::IsWindowFocused() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7ed51369..0ce3de71 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7275,7 +7275,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer) // 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)) + if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip)) SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); return tab_contents_visible; From 704723744e1515784cce6ac18d43f62fa84545fa Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Jun 2020 16:19:51 +0200 Subject: [PATCH 098/223] Disabled latest overzealous warnings from Clang --- imgui.cpp | 25 ++++++++++++++----------- imgui_demo.cpp | 3 +++ imgui_draw.cpp | 21 ++++++++++++--------- imgui_internal.h | 3 +++ imgui_widgets.cpp | 20 +++++++++++++------- 5 files changed, 45 insertions(+), 27 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 584b7a85..648c265e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -864,20 +864,23 @@ CODE // Clang/GCC warnings with -Weverything #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. -#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 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' +#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. +#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 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' #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 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") -#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. +#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 +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #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. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 65d24bbd..e173058c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -98,6 +98,9 @@ Index of this file: #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier #endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#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 diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 750bf9f6..71d98327 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -57,21 +57,24 @@ Index of this file: // Clang/GCC warnings with -Weverything #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. -#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#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. +#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 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wcomma") -#pragma clang diagnostic ignored "-Wcomma" // warning : possible misuse of comma operator here // +#pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here #endif #if __has_warning("-Wreserved-id-macro") -#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier #endif #if __has_warning("-Wdouble-promotion") -#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. +#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 +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind @@ -108,7 +111,7 @@ namespace IMGUI_STB_NAMESPACE #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" -#pragma clang diagnostic ignored "-Wcast-qual" // warning : cast from 'const xxxx *' to 'xxx *' drops const qualifier // +#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier #endif #if defined(__GNUC__) diff --git a/imgui_internal.h b/imgui_internal.h index 4f101920..ddca9fff 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -66,6 +66,9 @@ Index of this file: #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" #endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#endif #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0ce3de71..12a8c08f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -58,18 +58,24 @@ Index of this file: // Clang/GCC warnings with -Weverything #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. -#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#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. +#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 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") -#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. +#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 +#if __has_warning("-Wenum-enum-conversion") +#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') #endif #if __has_warning("-Wdeprecated-enum-enum-conversion") -#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind From 8ead38c10067954ff51076d0b59ad3b12c790240 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Jun 2020 16:33:23 +0200 Subject: [PATCH 099/223] Clang: Reduce uses of __has_warning for overall sanity, as compilers are hostile to software targetting multiple compiler version. --- imgui.cpp | 11 ++++------- imgui_demo.cpp | 45 ++++++++++++++++++++++----------------------- imgui_draw.cpp | 14 ++++---------- imgui_internal.h | 16 +++++++--------- imgui_widgets.cpp | 14 ++++---------- 5 files changed, 41 insertions(+), 59 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 648c265e..f4a1c205 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -864,7 +864,10 @@ CODE // Clang/GCC warnings with -Weverything #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! +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #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. @@ -873,15 +876,9 @@ CODE #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' -#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 -#if __has_warning("-Wdouble-promotion") #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 -#if __has_warning("-Wimplicit-int-float-conversion") #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#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 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e173058c..33d069dc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -79,35 +79,34 @@ Index of this file: #include // intptr_t #endif +// Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif + +// Clang/GCC warnings with -Weverything #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.. // 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 -#pragma clang diagnostic ignored "-Wformat-security" // 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: 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 -#if __has_warning("-Wdouble-promotion") -#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 -#if __has_warning("-Wreserved-id-macro") -#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier -#endif -#if __has_warning("-Wimplicit-int-float-conversion") -#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! #endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#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.. // 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 +#pragma clang diagnostic ignored "-Wformat-security" // 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: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #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 -#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. +#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 +#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 (Update: May 2018, Notepad now supports Unix-style carriage returns!) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 71d98327..0e7c294e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -57,25 +57,19 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #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. #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 -#endif -#if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here -#endif -#if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier -#endif -#if __has_warning("-Wdouble-promotion") #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 -#if __has_warning("-Wimplicit-int-float-conversion") #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#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 diff --git a/imgui_internal.h b/imgui_internal.h index ddca9fff..9e0fe99e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -57,18 +57,16 @@ Index of this file: // 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 +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#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" -#endif -#if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" -#endif -#if __has_warning("-Wimplicit-int-float-conversion") -#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#endif +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 12a8c08f..70ab9e3d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -58,25 +58,19 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #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. #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 -#endif -#if __has_warning("-Wdouble-promotion") #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 -#if __has_warning("-Wenum-enum-conversion") #pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') -#endif -#if __has_warning("-Wdeprecated-enum-enum-conversion") #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated -#endif -#if __has_warning("-Wimplicit-int-float-conversion") #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#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 From 9c2a36f5732d8031a410bf656a0f41e9e3775b13 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 10:08:05 +0200 Subject: [PATCH 100/223] Internals: clarified the code for ClampWindowRect(). As a side-effect, some rounding error may be neutralized however this isn't the intent. (#3309) --- imgui.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f4a1c205..9bb5f9d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5239,11 +5239,13 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s return ret_auto_fit; } -static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding) +static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& viewport_rect, const ImVec2& padding) { ImGuiContext& g = *GImGui; - ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size; - window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping); + ImVec2 size_for_clamping = window->Size; + if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + size_for_clamping.y = window->TitleBarHeight(); + window->Pos = ImClamp(window->Pos, viewport_rect.Min + padding - size_for_clamping, viewport_rect.Max - padding); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) From 99f68d79581deef58d1edc5d07a92ad7806cabd6 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 10:56:54 +0200 Subject: [PATCH 101/223] Docs: Added FAQ entries removed old one which is misleading today. Misc tweaks. --- docs/FAQ.md | 20 +++++++++++++++----- docs/README.md | 4 ++-- docs/TODO.txt | 3 ++- examples/README.txt | 41 +++++++++++++++++++++++------------------ imgui.cpp | 11 +++++++---- 5 files changed, 49 insertions(+), 30 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 1401486a..55e7ebeb 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -15,12 +15,13 @@ or view this file with any Markdown viewer. | [What is this library called?](#q-what-is-this-library-called) | | [Which version should I get?](#q-which-version-should-i-get) | | **Q&A: Integration** | +| **[How to get started?](#q-how-to-get-started)** | | **[How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?](#q-how-can-i-tell-whether-to-dispatch-mousekeyboard-to-dear-imgui-or-to-my-application)** | | [How can I enable keyboard or gamepad controls?](#q-how-can-i-enable-keyboard-or-gamepad-controls) | | [How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)](#q-how-can-i-use-this-on-a-machine-without-mouse-keyboard-or-screen-input-share-remote-display) | -| [I integrated Dear ImGui in my engine and the text or lines are blurry..](#q-i-integrated-dear-imgui-in-my-engine-and-the-text-or-lines-are-blurry) | +| [I integrated Dear ImGui in my engine and little squares are showing instead of text..](#q-i-integrated-dear-imgui-in-my-engine-and-little-squares-are-showing-instead-of-text) | | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | -| [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) +| [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | **Q&A: Usage** | | **[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?](#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)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| @@ -88,6 +89,15 @@ You may merge in the [tables](https://github.com/ocornut/imgui/tree/tables) bran # Q&A: Integration +### Q: How to get started? + +Read `PROGRAMMER GUIDE` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp). +Read [examples/README.txt](https://github.com/ocornut/imgui/tree/master/examples/README.txt). + +##### [Return to Index](#index) + +--- + ### Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application? You can read the `io.WantCaptureMouse`, `io.WantCaptureKeyboard` and `io.WantTextInput` flags from the ImGuiIO structure. @@ -139,9 +149,9 @@ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-lik --- -### Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. -In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). -Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. +### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. +This usually means that: your font texture wasn't uploaded into GPU, or your shader or other rendering state are not reading from the right texture (e.g. texture wasn't bound). +If this happens using the standard back-ends it is probably that the texture failed to upload, which could happens if for some reason your texture is too big. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). ##### [Return to Index](#index) diff --git a/docs/README.md b/docs/README.md index df32b9c2..a0ca6483 100644 --- a/docs/README.md +++ b/docs/README.md @@ -96,7 +96,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas ![screenshot demo](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png) -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: +You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: - [imgui-demo-binaries-20190715.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows binaries, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). The demo applications are not 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()` (see [FAQ](https://www.dearimgui.org/faq)). @@ -158,7 +158,7 @@ Private support is available for paying business customers (E-mail: _contact @ d **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. +We 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. Many projects are using this branch and it is kept in sync with master regularly. diff --git a/docs/TODO.txt b/docs/TODO.txt index 213d1d35..71969690 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -382,6 +382,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: window minimize, maximize (#583) - examples: provide a zero frame-rate/idle example. - examples: dx11/dx12: try to use new swapchain blit models (#2970) + - backends: report it better when not able to create texture? - backends: apple: example_apple should be using modern GL3. - backends: 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) - backends: opengl: rename imgui_impl_opengl2 to impl_opengl_legacy and imgui_impl_opengl3 to imgui_impl_opengl? (#1900) @@ -392,7 +393,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - backends: bgfx: https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - backends: mscriptem: 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) - - optimization: replace vsnprintf with stb_printf? or enable the defines/infrastructure to allow it (#1038) + - optimization: replace vsnprintf with stb_printf? using IMGUI_USE_STB_SPRINTF.(#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) - optimization: fully covered window (covered by another with non-translucent bg + WindowRounding worth of padding) may want to clip rendering. diff --git a/examples/README.txt b/examples/README.txt index 3356b546..0933a6ba 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -32,29 +32,34 @@ You can find binaries of some of those example applications at: --------------------------------------- - MISC COMMENTS AND SUGGESTIONS + GETTING STARTED --------------------------------------- - - Read FAQ at http://dearimgui.org/faq - - Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. Please read the comments and instruction at the top of each file. + Please read FAQ at http://www.dearimgui.org/faq - - If you are using of the backend provided here, so you can copy the imgui_impl_xxx.cpp/h files + - If you are using of the backend provided here, you can add the imgui_impl_xxx.cpp/h files to your project and use them unmodified. Each imgui_impl_xxxx.cpp comes with its own individual - ChangeLog at the top of the .cpp files, so if you want to update them later it will be easier to + Changelog at the top of the .cpp files, so if you want to update them later it will be easier to catch up with what changed. - - Dear ImGui has 0 to 1 frame of lag for most behaviors, at 60 FPS your experience should be pleasant. - However, consider that OS mouse cursors are typically drawn through a specific hardware accelerated path - and will feel smoother than common GPU rendered contents (including Dear ImGui windows). - You may experiment with the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor itself, - to visualize the lag between a hardware cursor and a software cursor. However, rendering a mouse cursor - at 60 FPS will feel slow. It might be beneficial to the user experience to switch to a software rendered - cursor only when an interactive drag is in progress. - Note that some setup or GPU drivers are likely to be causing extra lag depending on their settings. - If you feel that dragging windows feels laggy and you are not sure who to blame: try to build an - application drawing a shape directly under the mouse cursor. + - Dear ImGui has no particular extra lag for most behaviors, e.g. the value of 'io.MousePos' provided in + NewFrame() will result at the time of EndFrame()/Render() in a moved windows rendered following that mouse + movement. At 60 FPS your experience should be pleasant. + However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated + path and will feel smoother than the majority of contents rendererd via regular graphics API (including, + but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane as + the mouse, that disconnect may be jarring to particularly sensitive users. + You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor + using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a + regularly rendered software cursor. + However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at + all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ + when an interactive drag is in progress. + Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. + If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple + drawing a flat 2D shape directly under the mouse cursor. --------------------------------------- @@ -155,12 +160,12 @@ Those will allow you to create portable applications and will solve and abstract Building: Unfortunately in 2020 it is still tedious to create and maintain portable build files using external libraries (the kind we're using here to create a window and render 3D triangles) without relying on - third party software. For most examples here I choose to provide: + third party software. For most examples here we choose to provide: - Makefiles for Linux/OSX - Batch files for Visual Studio 2008+ - - A .sln project file for Visual Studio 2010+ + - A .sln project file for Visual Studio 2012+ - Xcode project files for the Apple examples - Please let me know if they don't work with your setup! + Please let us know if they don't work with your setup! You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those directly with a command-line compiler. diff --git a/imgui.cpp b/imgui.cpp index 9bb5f9d2..2df5ce1e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -18,7 +18,7 @@ // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // See LICENSE.txt for copyright and licensing details (standard MIT License). -// This library is free but I need your support to sustain development and maintenance. +// This library is free but needs your support to sustain development and maintenance. // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org". // Individuals: you can support continued development via donations. See docs/README or web page. @@ -169,7 +169,7 @@ CODE --------------------------------------------------------------- - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. - In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder. - - Add the Dear ImGui source files to your projects or using your preferred build system. + - Add the Dear ImGui source files + selected back-end 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 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. @@ -622,18 +622,21 @@ CODE Q: What is this library called? Q: Which version should I get? >> This library is called "Dear ImGui", please don't call it "ImGui" :) - >> See https://www.dearimgui.org/faq + >> See https://www.dearimgui.org/faq for details. Q&A: Integration ================ + Q: How to get started? + A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt. + Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application? A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! >> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this. Q. How can I enable keyboard controls? Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) - Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. + Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. >> See https://www.dearimgui.org/faq From 1a1dcea1a02c4e1542b6e2619111fe2d20e22383 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 20 Jun 2020 22:03:50 +0200 Subject: [PATCH 102/223] Internals: Initialize drawlist earlier in Begin() to facilitate detecting accidental draw earlier than legal. (#3311) --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 2df5ce1e..c9146e13 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5606,6 +5606,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->HasCloseButton = (p_open != NULL); window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->IDStack.resize(1); + window->DrawList->_ResetForNewFrame(); // Restore buffer capacity when woken from a compacted state, to avoid if (window->MemoryCompacted) @@ -5883,7 +5884,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // DRAWING // Setup draw list and outer clipping rectangle - window->DrawList->_ResetForNewFrame(); + IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); From 76e40fe5d1059733ddcdd88236ee5c5743ed64b7 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 20 Jun 2020 22:06:44 +0200 Subject: [PATCH 103/223] Docking: Fix misuse of PushClipRect in UpdateWindowManualResize(). (#3311) --- imgui.cpp | 5 ++--- imgui.h | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ff6722af..08c86496 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5502,9 +5502,10 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // 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). + // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration); if (clip_with_viewport_rect) - PushClipRect(window->Viewport->Pos, window->Viewport->Pos + window->Viewport->Size, true); // Won't incur a draw command as we are not drawing here. + window->ClipRect = window->Viewport->GetMainRect(); // Resize grips and borders are on layer 1 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; @@ -5568,8 +5569,6 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s } } PopID(); - if (clip_with_viewport_rect) - PopClipRect(); // Restore nav layer window->DC.NavLayerCurrent = ImGuiNavLayer_Main; diff --git a/imgui.h b/imgui.h index 980fbf16..c283070f 100644 --- a/imgui.h +++ b/imgui.h @@ -1697,7 +1697,7 @@ struct ImGuiSizeCallbackData // Important: the content of this class is still highly WIP and likely to change and be refactored // before we stabilize Docking features. Please be mindful if using this. // Provide hints: -// - To the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +// - To the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) // - To the platform back-end for OS level parent/child relationships of viewport. // - To the docking system for various options and filtering. struct ImGuiWindowClass @@ -1707,7 +1707,7 @@ struct ImGuiWindowClass 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. ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) - ImGuiDockNodeFlags DockNodeFlagsOverrideClear; // [EXPERIMENTAL] + ImGuiDockNodeFlags DockNodeFlagsOverrideClear; // [EXPERIMENTAL] bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (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. From e0ec69d84be361611a4fdd5e853f25a04a59c8b0 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 15:47:07 +0200 Subject: [PATCH 104/223] Internals: Added ImageButtonEx() helper to temporarily bypass ID issues (#2464, #1390) --- imgui_internal.h | 1 + imgui_widgets.cpp | 45 ++++++++++++++++++++++++++------------------- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 9e0fe99e..a00a3418 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1958,6 +1958,7 @@ namespace ImGui IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); 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 bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col); IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowResizeID(ImGuiWindow* window, int n); // 0..3: corners, 4..7: borders diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 70ab9e3d..bda694a5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -981,28 +981,16 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& } } -// frame_padding < 0: uses FramePadding from style (default) -// frame_padding = 0: no framing -// frame_padding > 0: set framing size -// The color used are the button colors. -bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +// ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390) +// We provide this internal helper to write your own variant while we figure out how to redesign the public ImageButton() API. +bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col) { + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; - - // Default to using texture ID as ID. User can still push string/integer prefixes. - // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. - PushID((void*)(intptr_t)user_texture_id); - const ImGuiID id = window->GetID("#image"); - PopID(); - - const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2); - const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, id)) return false; @@ -1013,14 +1001,33 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); - RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); + RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding)); if (bg_col.w > 0.0f) - window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); - window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); + window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); + window->DrawList->AddImage(texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); return pressed; } +// frame_padding < 0: uses FramePadding from style (default) +// frame_padding = 0: no framing +// frame_padding > 0: set framing size +bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + // Default to using texture ID as ID. User can still push string/integer prefixes. + PushID((void*)(intptr_t)user_texture_id); + const ImGuiID id = window->GetID("#image"); + PopID(); + + const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : g.Style.FramePadding; + return ImageButtonEx(id, user_texture_id, size, uv0, uv1, padding, bg_col, tint_col); +} + bool ImGui::Checkbox(const char* label, bool* v) { ImGuiWindow* window = GetCurrentWindow(); From 68389200c4aaaa0e723f6d8e11064ca68c3b061d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 16:12:19 +0200 Subject: [PATCH 105/223] Internals: Comments about CalcWrapWidthForPos() (#778) --- imgui.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index c9146e13..942b5122 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3255,11 +3255,21 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) if (wrap_pos_x < 0.0f) return 0.0f; - ImGuiWindow* window = GImGui->CurrentWindow; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; if (wrap_pos_x == 0.0f) + { + // We could decide to setup a default wrapping max point for auto-resizing windows, + // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? + //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) + // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x); + //else 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 + } return ImMax(wrap_pos_x - pos.x, 1.0f); } From b83a1f3b002a630ba4d3e8d15c895fde2a016205 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 17:52:13 +0200 Subject: [PATCH 106/223] BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. (#915, #3091) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 10 ++++++---- imgui_demo.cpp | 4 ++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b479a333..00dbbceb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,10 @@ Other Changes: would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) - Popups: Clarified some of the comments and function prototypes. +- Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will + not always be auto-centered. Note that modals are more similar to regular windows than they are to + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] diff --git a/imgui.cpp b/imgui.cpp index 942b5122..bb5d8a91 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5748,7 +5748,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (window_just_activated_by_user) { window->AutoPosLastDirection = ImGuiDir_None; - if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos() window->Pos = g.BeginPopupStack.back().OpenPopupPos; } @@ -7807,6 +7807,7 @@ void ImGui::CloseCurrentPopup() window->DC.NavHideHighlightOneFrame = true; } +// Attention! BeginPopup() adds default flags which BeginPopupEx()! bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; @@ -7855,12 +7856,13 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla return false; } - // Center modal windows by default + // Center modal windows by default for increased visibility + // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) - SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); - flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings; + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse; const bool is_open = Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 33d069dc..0c9b6e23 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2865,6 +2865,10 @@ static void ShowDemoWindowPopups() if (ImGui::Button("Delete..")) ImGui::OpenPopup("Delete?"); + // Always center this window when appearing + ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); From a616ff5d4a7bb72ccbe9906d3220d0938c1915cf Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 17:52:13 +0200 Subject: [PATCH 107/223] BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. (#915, #3091) # Conflicts: # imgui.cpp --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 10 ++++++---- imgui_demo.cpp | 4 ++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ead04e53..11f0c052 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -127,6 +127,10 @@ Other Changes: would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) - Popups: Clarified some of the comments and function prototypes. +- Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will + not always be auto-centered. Note that modals are more similar to regular windows than they are to + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] diff --git a/imgui.cpp b/imgui.cpp index 08c86496..4a57b478 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6191,7 +6191,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (window_just_activated_by_user) { window->AutoPosLastDirection = ImGuiDir_None; - if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos() window->Pos = g.BeginPopupStack.back().OpenPopupPos; } @@ -8547,6 +8547,7 @@ void ImGui::CloseCurrentPopup() window->DC.NavHideHighlightOneFrame = true; } +// Attention! BeginPopup() adds default flags which BeginPopupEx()! bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; @@ -8595,15 +8596,16 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla return false; } - // Center modal windows by default + // Center modal windows by default for increased visibility + // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) { ImGuiViewportP* viewport = window->WasActive ? window->Viewport : (ImGuiViewportP*)GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport? - SetNextWindowPos(viewport->GetMainRect().GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + SetNextWindowPos(viewport->GetMainRect().GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); } - flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking; + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; const bool is_open = Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 42a6320d..2202cbf3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2922,6 +2922,10 @@ static void ShowDemoWindowPopups() if (ImGui::Button("Delete..")) ImGui::OpenPopup("Delete?"); + // Always center this window when appearing + ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); From e1d7e1471702ed0f50cf11bccb3877df05f45134 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 18:31:44 +0200 Subject: [PATCH 108/223] Viewports: used main viewport for centering (wip), clarified the meaning of how ImGuiPlatformMonitor WorkPos/WorkSize should be set if unknown, added asserts. --- imgui.cpp | 5 ++--- imgui.h | 5 +++-- imgui_demo.cpp | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4a57b478..9e19f946 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7590,9 +7590,8 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() 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.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly."); + IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them."); IM_ASSERT(mon.DpiScale != 0.0f); } } diff --git a/imgui.h b/imgui.h index c283070f..dc37773c 100644 --- a/imgui.h +++ b/imgui.h @@ -2570,7 +2570,7 @@ struct ImGuiPlatformIO struct ImGuiPlatformMonitor { ImVec2 MainPos, MainSize; // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) - ImVec2 WorkPos, WorkSize; // (Optional) Coordinates without task bars / side bars / menu bars. imgui uses this to avoid positioning popups/tooltips inside this region. + ImVec2 WorkPos, WorkSize; // Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. float DpiScale; // 1.0f = 96 DPI ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; } }; @@ -2621,7 +2621,8 @@ struct ImGuiViewport ImGuiViewport() { ID = 0; Flags = 0; DpiScale = 0.0f; DrawData = NULL; ParentViewportId = 0; RendererUserData = PlatformUserData = PlatformHandle = PlatformHandleRaw = NULL; PlatformRequestMove = PlatformRequestResize = PlatformRequestClose = false; } ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); } - // Access work-area rectangle + // Access work-area rectangle with GetWorkXXX functions (see comments above) + ImVec2 GetCenter() { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } ImVec2 GetWorkPos() { return ImVec2(Pos.x + WorkOffsetMin.x, Pos.y + WorkOffsetMin.y); } ImVec2 GetWorkSize() { return ImVec2(Size.x - WorkOffsetMin.x + WorkOffsetMax.x, Size.y - WorkOffsetMin.y + WorkOffsetMax.y); } // This not clamped }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2202cbf3..c6dec7a2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2923,8 +2923,8 @@ static void ShowDemoWindowPopups() ImGui::OpenPopup("Delete?"); // Always center this window when appearing - ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f); - ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { From 7538bbabb62da3105b62ca596827407f638c2e27 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 19:01:40 +0200 Subject: [PATCH 109/223] Demo: Commented out ideas on another way to center a window. --- imgui_demo.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c6dec7a2..b43f5981 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2923,8 +2923,11 @@ static void ShowDemoWindowPopups() ImGui::OpenPopup("Delete?"); // Always center this window when appearing - ImGuiViewport* viewport = ImGui::GetMainViewport(); - ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + //ImVec2 parent_pos = ImGui::GetWindowPos(); + //ImVec2 parent_size = ImGui::GetWindowSize(); + //ImVec2 center(parent_pos.x + parent_size.x * 0.5f, parent_pos.y + parent_size.y * 0.5f); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { From 1c35750ee0fdf9b631429e6d9e57928f57ba705e Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 19:45:31 +0200 Subject: [PATCH 110/223] Added ImGuiCond_None for consistency and for generated bindings needing this for enums mapping. --- imgui.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index eb2a611b..cedc8618 100644 --- a/imgui.h +++ b/imgui.h @@ -1277,7 +1277,8 @@ enum ImGuiMouseCursor_ // 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_ { - ImGuiCond_Always = 1 << 0, // Set the variable + ImGuiCond_None = 0, // No condition (always set the variable), same as _Always + ImGuiCond_Always = 1 << 0, // No condition (always set the variable) ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will 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) From 5acf6d861ae075e12b03c47fea8eb26e4c48bbeb Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 15:17:56 +0200 Subject: [PATCH 111/223] Popups: Added ImGuiPopupFlags type, ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(). # Conflicts: # docs/CHANGELOG.txt --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 64 +++++++++++++++++++++++++++------------------- imgui.h | 16 +++++++++++- imgui_internal.h | 4 +-- imgui_widgets.cpp | 6 ++--- 5 files changed, 59 insertions(+), 34 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 00dbbceb..8882f0af 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,9 @@ Other Changes: Set to an intermediary value to toggle behavior based on width (same as Firefox). - Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] +- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), + allowing to check if any popup is open at the current level, if a given popup is open at any popup + level, if any popup is open at all. - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) diff --git a/imgui.cpp b/imgui.cpp index bb5d8a91..f2e77c79 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3468,7 +3468,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() // Handle the edge case of a popup being closed while clicking in its empty space. // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. ImGuiWindow* root_window = g.HoveredRootWindow; - const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpenAtAnyLevel(root_window->PopupId); + const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel); if (root_window != NULL && !is_closed_popup) { @@ -7619,35 +7619,45 @@ void ImGui::SetTooltip(const char* fmt, ...) // [SECTION] POPUPS //----------------------------------------------------------------------------- -// Return true if the popup is open at the current BeginPopup() level of the popup stack -bool ImGui::IsPopupOpen(ImGuiID id) +// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel +bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; - return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; -} - -// Return true if the popup is open at the current BeginPopup() level of the popup stack -bool ImGui::IsPopupOpen(const char* str_id) -{ - ImGuiContext& g = *GImGui; - return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); -} - -bool ImGui::IsPopupOpenAtAnyLevel(ImGuiID id) -{ - ImGuiContext& g = *GImGui; - for (int n = 0; n < g.OpenPopupStack.Size; n++) - if (g.OpenPopupStack[n].PopupId == id) - return true; - return false; + if (popup_flags & ImGuiPopupFlags_AnyPopupId) + { + // Return true if any popup is open at the current BeginPopup() level of the popup stack + // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level. + IM_ASSERT(id == 0); + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + return g.OpenPopupStack.Size > 0; + else + return g.OpenPopupStack.Size > g.BeginPopupStack.Size; + } + else + { + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + { + // Return true if the popup is open anywhere in the popup stack + for (int n = 0; n < g.OpenPopupStack.Size; n++) + if (g.OpenPopupStack[n].PopupId == id) + return true; + return false; + } + else + { + // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query) + return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; + } + } } -// Return true if any popup is open at the current BeginPopup() level of the popup stack -// This may be used to e.g. test for another popups already opened in the same frame to handle popups priorities at the same level. -bool ImGui::IsAnyPopupOpen() +bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; - return g.OpenPopupStack.Size > g.BeginPopupStack.Size; + ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id); + if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0) + IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally + return IsPopupOpen(id, popup_flags); } ImGuiWindow* ImGui::GetTopMostPopupModal() @@ -7674,7 +7684,7 @@ void ImGui::OpenPopupEx(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; - int current_stack_size = g.BeginPopupStack.Size; + const int current_stack_size = g.BeginPopupStack.Size; 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; @@ -7811,7 +7821,7 @@ void ImGui::CloseCurrentPopup() bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; - if (!IsPopupOpen(id)) + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; @@ -7850,7 +7860,7 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(name); - if (!IsPopupOpen(id)) + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; diff --git a/imgui.h b/imgui.h index cedc8618..63bfc270 100644 --- a/imgui.h +++ b/imgui.h @@ -161,6 +161,7 @@ typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: f typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super) +typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() @@ -612,13 +613,17 @@ namespace ImGui IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. - IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack // Popups: open+begin combined functions helpers // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. // - They are convenient to easily create context menus, hence the name. IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1, bool also_over_items = true); // open+begin popup when clicked on current window. IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked in void (where there are no windows). + // Popups: test function + // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. + IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. // Columns // - You can also use SameLine(pos_x) to mimic simplified columns. @@ -865,6 +870,15 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog }; +// Flags for IsPopupOpen() function. +enum ImGuiPopupFlags_ +{ + ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) + ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel +}; + // Flags for ImGui::Selectable() enum ImGuiSelectableFlags_ { diff --git a/imgui_internal.h b/imgui_internal.h index a00a3418..d0c8bbcb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1853,9 +1853,7 @@ namespace ImGui IMGUI_API void OpenPopupEx(ImGuiID id); 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 at the current BeginPopup() level of the popup stack (this doesn't scan the whole popup stack!) - IMGUI_API bool IsPopupOpenAtAnyLevel(ImGuiID id); - IMGUI_API bool IsAnyPopupOpen(); // Return true if any popup is open at the current BeginPopup() level of the popup stack + IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bda694a5..79144ee9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1492,7 +1492,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF bool hovered, held; bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); - bool popup_open = IsPopupOpen(id); + bool popup_open = IsPopupOpen(id, ImGuiPopupFlags_None); 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); @@ -6288,7 +6288,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - bool menu_is_open = IsPopupOpen(id); + bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None); // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus; @@ -6414,7 +6414,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true; - if (want_close && IsPopupOpen(id)) + if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None)) ClosePopupToLevel(g.BeginPopupStack.Size, true); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0)); From fed80b95375f716536ceaa3c5e8b21c96e150bff Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 15:26:02 +0200 Subject: [PATCH 112/223] Popups: Changed 'int mouse_buttons' to ImGuiPopupFlags. Added ImGuiPopupFlags_NoOpenOverExistingPopup, ImGuiPopupFlags_NoOpenOverItems. Refactored signature of BeginPopupContextWindow(). --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 34 ++++++++++++++++++++++------------ imgui.h | 31 +++++++++++++++++++++++-------- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 5 files changed, 56 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8882f0af..5b33b11d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,8 @@ Breaking Changes: - Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). +- Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor + of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - Removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. Other Changes: @@ -54,6 +56,13 @@ Other Changes: Set to an intermediary value to toggle behavior based on width (same as Firefox). - Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] +- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new + ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward + compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. +- Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions + to first test for the presence of another popup at the same level. +- Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing + for !IsAnyItemHovered() prior to doing an OpenPopup. - Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. diff --git a/imgui.cpp b/imgui.cpp index f2e77c79..07c5ea4a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,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. + - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). @@ -7670,21 +7671,26 @@ ImGuiWindow* ImGui::GetTopMostPopupModal() return NULL; } -void ImGui::OpenPopup(const char* str_id) +void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; - OpenPopupEx(g.CurrentWindow->GetID(str_id)); + OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags); } // Mark popup as open (toggle toward open state). // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) -void ImGui::OpenPopupEx(ImGuiID id) +void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; const int current_stack_size = g.BeginPopupStack.Size; + + if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup) + if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId)) + return; + 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; @@ -7903,14 +7909,15 @@ void ImGui::EndPopup() g.WithinEndChild = false; } -bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { 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) - OpenPopupEx(id); + OpenPopupEx(id, popup_flags); return true; } return false; @@ -7921,39 +7928,42 @@ bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_butt // - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // - This is essentially the same as calling OpenPopupContextItem() + BeginPopup() but written to avoid // computing the ID twice because BeginPopupContextXXX functions are called very frequently. -bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { 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) + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) - OpenPopupEx(id); + OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } -bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items) +bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "window_context"; ImGuiID id = window->GetID(str_id); + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) - if (also_over_items || !IsAnyItemHovered()) - OpenPopupEx(id); + if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) + OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } -bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "void_context"; ImGuiID id = window->GetID(str_id); + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) if (GetTopMostPopupModal() == NULL) - OpenPopupEx(id); + OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } diff --git a/imgui.h b/imgui.h index 63bfc270..c443ca75 100644 --- a/imgui.h +++ b/imgui.h @@ -606,19 +606,22 @@ namespace ImGui IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! // Popups: open/close functions - // - OpenPopup(): set popup state to open. + // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). - IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). - IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). + IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. // Popups: open+begin combined functions helpers // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. // - They are convenient to easily create context menus, hence the name. - IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! - IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1, bool also_over_items = true); // open+begin popup when clicked on current window. - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked in void (where there are no windows). + // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. + // - We exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter. Passing a mouse button to ImGuiPopupFlags is guaranteed to be legal. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). // Popups: test function // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. @@ -870,10 +873,21 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog }; -// Flags for IsPopupOpen() function. +// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat +// small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. +// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. +// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. enum ImGuiPopupFlags_ { ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranted to always be == 0 (same as ImGuiMouseButton_Left) + ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranted to always be == 1 (same as ImGuiMouseButton_Right) + ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranted to always be == 2 (same as ImGuiMouseButton_Middle) + ImGuiPopupFlags_MouseButtonMask_ = 0x1F, + ImGuiPopupFlags_MouseButtonDefault_ = 1, + ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + ImGuiPopupFlags_NoOpenOverItems = 1 << 6, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel @@ -1656,7 +1670,8 @@ struct ImGuiPayload namespace ImGui { // OBSOLETED in 1.77 (from June 2020) - static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1) { return OpenPopupContextItem(str_id, mouse_button); } + static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupContextItem(str_id, mb); } // Passing a mouse button to ImGuiPopupFlags is legal + static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } // OBSOLETED in 1.72 (from July 2019) static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.71 (from June 2019) diff --git a/imgui_internal.h b/imgui_internal.h index d0c8bbcb..9ec0760d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1850,7 +1850,7 @@ namespace ImGui // Popups, Modals, Tooltips IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags); - IMGUI_API void OpenPopupEx(ImGuiID id); + IMGUI_API void OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None); 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, ImGuiPopupFlags popup_flags); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 79144ee9..ec0bcc74 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1517,7 +1517,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF { if (window->DC.NavLayerCurrent == 0) window->NavLastIds[0] = id; - OpenPopupEx(id); + OpenPopupEx(id, ImGuiPopupFlags_None); popup_open = true; } From 45a7cf47ab12c7fe9f239a213b279e1803041ca6 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Jun 2020 16:44:06 +0200 Subject: [PATCH 113/223] FAQ update, removed redundant block in imgui.cpp --- docs/CHANGELOG.txt | 5 +- docs/FAQ.md | 13 +++-- imgui.cpp | 128 +++------------------------------------------ 3 files changed, 19 insertions(+), 127 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5b33b11d..35265e30 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,12 +36,13 @@ HOW TO UPDATE? Breaking Changes: -- Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please +- Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. -- Removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. + Kept inline redirection function (will obsolete). +- Removed obsoleted CalcItemRectClosestPoint() entry point (has been asserting since December 2017). Other Changes: diff --git a/docs/FAQ.md b/docs/FAQ.md index 55e7ebeb..adce4d40 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -23,7 +23,7 @@ or view this file with any Markdown viewer. | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | **Q&A: Usage** | -| **[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?](#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)** | +| **[How can I have widgets with an empty label?
How can I have multiple widgets with the same label?
Why are multiple widgets reacting when I interact with one?](#q-how-can-i-have-widgets-with-an-empty-label)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| | [How can I use my own math types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-math-types-instead-of-imvec2imvec4) | | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | @@ -173,7 +173,9 @@ Refer to rendering back-ends in the [examples/](https://github.com/ocornut/imgui # Q&A: Usage -### 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: How can I have widgets with an empty label? +### Q: How can I have multiple widgets with the same label? +### Q: Why are multiple widgets reacting when I interact with one? A primer on labels and the ID Stack... @@ -295,11 +297,12 @@ if (TreeNode("node")) // <-- this function call will do a PushID() for you (unl TreePop(); } ``` -- When working with trees, ID are used to preserve the open/close state of each tree node. + +When working with trees, ID are used to preserve the open/close state of each tree node. Depending on your use cases you may want to use strings, indices or pointers as ID. -e.g. when following a single pointer that may change over time, using a static string as ID +- e.g. when following a single pointer that may change over time, using a static string as ID will preserve your node open/closed state when the targeted object change. -e.g. when displaying a list of objects, using indices or pointers as ID will preserve the +- e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. See what makes more sense in your situation! ##### [Return to Index](#index) diff --git a/imgui.cpp b/imgui.cpp index 07c5ea4a..a4ec7178 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -601,7 +601,10 @@ CODE FREQUENTLY ASKED QUESTIONS (FAQ) ================================ - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer) + Read all answers online: + https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) + Read all answers locally (with a text editor or ideally a Markdown viewer): + docs/FAQ.md Some answers are copied down here to facilitate searching in code. Q&A: Basics @@ -640,130 +643,15 @@ CODE Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. ->> See https://www.dearimgui.org/faq + >> See https://www.dearimgui.org/faq Q&A: Usage ---------- - 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? - A: A primer on labels and the ID Stack... - - Dear ImGui internally need to uniquely identify UI elements. - Elements that are typically not clickable (such as calls to the Text functions) don't need an ID. - Interactive widgets (such as calls to Button buttons) need a unique ID. - Unique ID are used internally to track active widgets and occasionally associate state to widgets. - Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element. - - - Unique ID are often derived from a string label: - - Button("OK"); // Label = "OK", ID = hash of (..., "OK") - Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel") - - - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having - two buttons labeled "OK" in different windows or different tree locations is fine. - We used "..." above to signify whatever was already pushed to the ID stack previously: - - Begin("MyWindow"); - Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK") - End(); - Begin("MyOtherWindow"); - Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK") - End(); - - - If you have a same ID twice in the same location, you'll have a conflict: - - Button("OK"); - Button("OK"); // ID collision! Interacting with either button will trigger the first one. - - Fear not! this is easy to solve and there are many ways to solve it! - - - Solving ID conflict in a simple/local context: - When passing a label you can optionally specify extra ID information within string itself. - Use "##" to pass a complement to the ID that won't be visible to the end-user. - This helps solving the simple collision cases when you know e.g. at compilation time which items - are going to be created: - - Begin("MyWindow"); - Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play") - Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above - Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above - End(); - - - If you want to completely hide the label, but still need an ID: - - Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox! - - - Occasionally/rarely you might want change a label while preserving a constant ID. This allows - you to animate labels. For example you may want to include varying information in a window title bar, - but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID: - - Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID") - Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different - - sprintf(buf, "My game (%f FPS)###MyGame", fps); - Begin(buf); // Variable title, ID = hash of "MyGame" - - - Solving ID conflict in a more general manner: - Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts - within the same window. This is the most convenient way of distinguishing ID when iterating and - creating many UI elements programmatically. - You can push a pointer, a string or an integer value into the ID stack. - Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack. - At each level of the stack we store the seed used for items at this level of the ID stack. - - Begin("Window"); - for (int i = 0; i < 100; i++) - { - PushID(i); // Push i to the id tack - Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click") - PopID(); - } - for (int i = 0; i < 100; i++) - { - MyObject* obj = Objects[i]; - PushID(obj); - Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click") - PopID(); - } - for (int i = 0; i < 100; i++) - { - MyObject* obj = Objects[i]; - PushID(obj->Name); - Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click") - PopID(); - } - End(); - - - You can stack multiple prefixes into the ID stack: - - Button("Click"); // Label = "Click", ID = hash of (..., "Click") - PushID("node"); - Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") - PushID(my_ptr); - Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click") - PopID(); - PopID(); - - - Tree nodes implicitly creates a scope for you by calling PushID(). - - Button("Click"); // Label = "Click", ID = hash of (..., "Click") - if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag) - { - Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") - TreePop(); - } - - - When working with trees, ID are used to preserve the open/close state of each tree node. - Depending on your use cases you may want to use strings, indices or pointers as ID. - e.g. when following a single pointer that may change over time, using a static string as ID - will preserve your node open/closed state when the targeted object change. - e.g. when displaying a list of objects, using indices or pointers as ID will preserve the - node open/closed state differently. See what makes more sense in your situation! - + Q: How can I have widgets with an empty label? + Q: How can I have multiple widgets with the same label? + Q: Why are multiple widgets reacting when I interact with one? Q: How can I display an image? What is ImTextureID, how does it works? - >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - Q: How can I use my own math types instead of ImVec2/ImVec4? Q: How can I interact with standard C++ types (such as std::string and std::vector)? Q: How can I display custom shapes? (using low-level ImDrawList API) From 6b0cf2e6aed04209015a4636ed4302323f12ea83 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 24 Jun 2020 14:00:35 +0300 Subject: [PATCH 114/223] Windows: Fix unintended window size changes when resizing windows close to main viewport edges. --- docs/CHANGELOG.txt | 13 +++++++------ imgui.cpp | 7 +++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 35265e30..c145e368 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,17 +55,18 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). -- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item +- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] -- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new - ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward +- Windows: Fix unintended feedback loops when resizing windows close to main viewport edges. [@rokups] +- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new + ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. - Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions to first test for the presence of another popup at the same level. - Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing for !IsAnyItemHovered() prior to doing an OpenPopup. -- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), - allowing to check if any popup is open at the current level, if a given popup is open at any popup +- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), + allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) @@ -73,7 +74,7 @@ Other Changes: - Popups: Clarified some of the comments and function prototypes. - Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. Note that modals are more similar to regular windows than they are to - popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index a4ec7178..3135ca48 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5071,6 +5071,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) @@ -5096,6 +5099,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left + ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } @@ -5117,6 +5123,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); + nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); From d7ef56dca211fce88c797068b29e1112867c25e4 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 24 Jun 2020 14:00:35 +0300 Subject: [PATCH 115/223] Windows: Fix unintended window size changes when resizing windows close to main viewport edges. --- docs/CHANGELOG.txt | 13 +++++++------ imgui.cpp | 7 +++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f7128b4a..8d5a69bd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -123,17 +123,18 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). -- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item +- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] -- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new - ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward +- Windows: Fix unintended feedback loops when resizing windows close to main viewport edges. [@rokups] +- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new + ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. - Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions to first test for the presence of another popup at the same level. - Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing for !IsAnyItemHovered() prior to doing an OpenPopup. -- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), - allowing to check if any popup is open at the current level, if a given popup is open at any popup +- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), + allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) @@ -141,7 +142,7 @@ Other Changes: - Popups: Clarified some of the comments and function prototypes. - Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. Note that modals are more similar to regular windows than they are to - popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index 52bb7790..0666b404 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5551,6 +5551,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) @@ -5576,6 +5579,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left + ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } @@ -5597,6 +5603,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); + nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); From dd02a180b52130df0747bcb61ed6faf8b95e14a9 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Jun 2020 22:58:23 +0200 Subject: [PATCH 116/223] Windows: Amend 6b0cf2e6 to facilitate working in viewport branch + handle safe area padding and ConfigWindowsMoveFromTitleBarOnly. --- imgui.cpp | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3135ca48..5b7cbe8b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -852,7 +852,7 @@ static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateTabFocus(); static void UpdateDebugToolItemPicker(); -static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); +static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); 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); @@ -5019,7 +5019,7 @@ ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n) // Handle resize for: Resize Grips, Borders, Gamepad // Return true when using auto-fit (double click on resize grip) -static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) +static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; @@ -5071,8 +5071,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip - ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX); corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } @@ -5099,8 +5099,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left - ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX); border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } @@ -5123,7 +5123,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); - nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); + nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); @@ -5148,13 +5148,13 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s return ret_auto_fit; } -static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& viewport_rect, const ImVec2& padding) +static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = window->Size; if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) size_for_clamping.y = window->TitleBarHeight(); - window->Pos = ImClamp(window->Pos, viewport_rect.Min + padding - size_for_clamping, viewport_rect.Max - padding); + window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) @@ -5668,17 +5668,17 @@ 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); + // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. + ImRect viewport_rect(GetViewportRect()); + ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + ImRect visibility_rect(viewport_rect.Min + visibility_padding, viewport_rect.Max - visibility_padding); + // 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) - { - ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); - if (viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) - { - ClampWindowRect(window, viewport_rect, clamp_padding); - } - } + if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f) + ClampWindowRect(window, visibility_rect); window->Pos = ImFloor(window->Pos); // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) @@ -5705,7 +5705,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (!window->Collapsed) - if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0])) + if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true; window->ResizeBorderHeld = (signed char)border_held; From f4f04cb5ec83168a9d1917ebeed11ac185b37a76 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Jun 2020 22:58:23 +0200 Subject: [PATCH 117/223] Windows: Amend 6b0cf2e6 to facilitate working in viewport branch + handle safe area padding and ConfigWindowsMoveFromTitleBarOnly. # Conflicts: # imgui.cpp --- imgui.cpp | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0666b404..d265886c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -975,7 +975,7 @@ static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateTabFocus(); static void UpdateDebugToolItemPicker(); -static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); +static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); @@ -5489,7 +5489,7 @@ ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n) // Handle resize for: Resize Grips, Borders, Gamepad // Return true when using auto-fit (double click on resize grip) -static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) +static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; @@ -5551,8 +5551,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip - ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX); corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } @@ -5579,8 +5579,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left - ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX); border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } @@ -5603,7 +5603,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); - nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); + nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); @@ -5628,13 +5628,13 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s return ret_auto_fit; } -static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& viewport_rect, const ImVec2& padding) +static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = window->Size; if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) size_for_clamping.y = window->TitleBarHeight(); - window->Pos = ImClamp(window->Pos, viewport_rect.Min + padding - size_for_clamping, viewport_rect.Max - padding); + window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) @@ -6318,16 +6318,21 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Viewport->Flags = viewport_flags; } + // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. + ImRect viewport_rect(window->Viewport->GetMainRect()); + ImRect viewport_work_rect(window->Viewport->GetWorkRect()); + ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding); + // 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. // FIXME: Similar to code in GetWindowAllowedExtentRect() - ImRect viewport_rect = window->Viewport->GetMainRect(); if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) { - ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) { - ClampWindowRect(window, window->Viewport->GetWorkRect(), clamp_padding); + ClampWindowRect(window, visibility_rect); } else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0) { @@ -6339,7 +6344,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) else { ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->Viewport->PlatformMonitor]; - ClampWindowRect(window, ImRect(monitor.WorkPos, monitor.WorkPos + monitor.WorkSize), clamp_padding); + visibility_rect.Min = monitor.WorkPos + visibility_padding; + visibility_rect.Max = monitor.WorkPos + monitor.WorkSize - visibility_padding; + ClampWindowRect(window, visibility_rect); } } } @@ -6375,7 +6382,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (handle_borders_and_resize_grips && !window->Collapsed) - if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0])) + if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true; window->ResizeBorderHeld = (signed char)border_held; From 122febcdbf00f7bda3c5ed654ce589a79cf26777 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jun 2020 15:03:11 +0200 Subject: [PATCH 118/223] IO: Added storage for PenPressure (unused by core library, to facilitate experiments) (#2372) --- imgui.h | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui.h b/imgui.h index c443ca75..d6208a31 100644 --- a/imgui.h +++ b/imgui.h @@ -1584,6 +1584,7 @@ struct ImGuiIO float KeysDownDurationPrev[512]; // Previous duration the key has been down float NavInputsDownDuration[ImGuiNavInput_COUNT]; float NavInputsDownDurationPrev[ImGuiNavInput_COUNT]; + float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16 ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform back-end). Fill using AddInputCharacter() helper. From 9418dcb69355558f70de260483424412c5ca2fce Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jun 2020 15:09:55 +0200 Subject: [PATCH 119/223] Version 1.77 + fix minor clang-tidy warnings which seems reasonable --- docs/CHANGELOG.txt | 32 ++++++++++++++++++-------------- docs/TODO.txt | 5 ++--- examples/README.txt | 2 +- imgui.cpp | 3 ++- imgui.h | 10 +++++----- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 4 ++-- 9 files changed, 34 insertions(+), 30 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c145e368..4d757e0b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -9,11 +9,12 @@ RELEASE NOTES: https://github.com/ocornut/imgui/releases REPORT ISSUES, ASK QUESTIONS: https://github.com/ocornut/imgui/issues COMMITS HISTORY: https://github.com/ocornut/imgui/commits/master FAQ https://www.dearimgui.org/faq/ +WIKI https://github.com/ocornut/imgui/wiki WHEN TO UPDATE? -- Keeping your copy of dear imgui updated once in a while is recommended. -- It is generally safe to sync to the latest commit in master. +- Keeping your copy of Dear ImGui updated regularly is recommended. +- It is generally safe to sync to the latest commit in master or docking branches The library is fairly stable and regressions tends to be fixed fast when reported. HOW TO UPDATE? @@ -31,13 +32,16 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.77 WIP (In Progress) + VERSION 1.77 (Released 2020-06-29) ----------------------------------------------------------------------- +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.77 + Breaking Changes: - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please - note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. + note that this is a Beta api and will likely be reworked in order to support multi-DPI accross + multiple monitors. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. @@ -51,20 +55,20 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) -- Style: Added style.TabMinWidthForUnselectedCloseButton settings. - Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). - Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). - Set to an intermediary value to toggle behavior based on width (same as Firefox). -- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item - (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] - Windows: Fix unintended feedback loops when resizing windows close to main viewport edges. [@rokups] +- Tabs: Added style.TabMinWidthForUnselectedCloseButton settings: + - Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). + - Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). + - Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Tabs: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item + (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] - Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. - Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions to first test for the presence of another popup at the same level. - Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing - for !IsAnyItemHovered() prior to doing an OpenPopup. + for !IsAnyItemHovered() prior to doing an OpenPopup(). - Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. @@ -78,7 +82,7 @@ Other Changes: Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to - BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] + BeginMenu()/EndMenu() or BeginPopup(0/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Columns: Lower overhead on column switches and switching to background channel. @@ -96,12 +100,12 @@ Other Changes: a callback draw command would incorrectly override the callback draw command. - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra unrequired vertex. [@ShironekoBen] -- Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. +- Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeeds but FT_Load_Glyph() fails. - Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). - Fixed a static contructor which led to this dependency on some compiler setups (unclear which). + Fixed a static constructor which led to this dependency on some compiler setups. - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, diff --git a/docs/TODO.txt b/docs/TODO.txt index 71969690..abb9d513 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -34,7 +34,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - 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). + - window/tabbing: 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. @@ -111,7 +111,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. - layout: helper or a way to express ImGui::SameLine(ImGui::GetCursorStartPos().x + ImGui::CalcItemWidth() + ImGui::GetStyle().ItemInnerSpacing.x); in a simpler manner. - - layout: generalization of the above: a concept equivalent to word processor ruler tab stop ~ mini columns (position in X, no clipping implied) (vaguely relate to #267, #395, also what is used internally for menu items) + - layout, font: horizontal tab support, A) text mode: forward only tabs (e.g. every 4 characters/N pixels from pos x1), B) manual mode: explicit tab stops acting as mini columns, no clipping (for menu items, many kind of uses, also vaguely relate to #267, #395) - layout: horizontal layout helper (#97) - layout: horizontal flow until no space left (#404) - layout: more generic alignment state (left/right/centered) for single items? @@ -167,7 +167,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tabs: explicit api (even if internal) to cleanly manipulate tab order. - tabs: Mouse wheel over tab bar could scroll? (#2702) - - 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) diff --git a/examples/README.txt b/examples/README.txt index 0933a6ba..2137fe09 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.77 WIP + dear imgui, v1.77 ----------------------------------------------------------------------- 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 5b7cbe8b..2b5983a3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (main code and documentation) // Help: @@ -10382,6 +10382,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) 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*" : ""); + IM_UNUSED(p); if (ImGui::TreeNode(tab_bar, "%s", buf)) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) diff --git a/imgui.h b/imgui.h index d6208a31..3751f2e3 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (headers) // Help: @@ -59,8 +59,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.77 WIP" -#define IMGUI_VERSION_NUM 17602 +#define IMGUI_VERSION "1.77" +#define IMGUI_VERSION_NUM 17700 #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) @@ -85,8 +85,8 @@ Index of this file: #define IM_FMTARGS(FMT) #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_UNUSED(_VAR) ((void)_VAR) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! +#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 diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0c9b6e23..7abe7dd7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0e7c294e..49197277 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 9ec0760d..dd61fea6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (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! @@ -147,7 +147,7 @@ namespace ImStb #undef STB_TEXTEDIT_CHARTYPE #define STB_TEXTEDIT_STRING ImGuiInputTextState #define STB_TEXTEDIT_CHARTYPE ImWchar -#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f +#define STB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) #define STB_TEXTEDIT_UNDOSTATECOUNT 99 #define STB_TEXTEDIT_UNDOCHARCOUNT 999 #include "imstb_textedit.h" diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ec0bcc74..918dbf94 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (widgets code) /* @@ -5634,7 +5634,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags if (p_open) flags |= ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton; bool is_open = TreeNodeBehavior(id, flags, label); - if (p_open) + if (p_open != NULL) { // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. From dca7c3c62975b893fde1c65f3d8f43bb476bc381 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jun 2020 20:10:59 +0200 Subject: [PATCH 120/223] TestEngine: Added hook to notify test engine of a removed imgui context. --- imgui.cpp | 5 +++++ imgui.h | 2 +- imgui_internal.h | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2b5983a3..176326ed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3916,6 +3916,11 @@ void ImGui::Shutdown(ImGuiContext* context) SetCurrentContext(backup_context); } + // Notify hooked test engine, if any +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGuiTestEngineHook_Shutdown(context); +#endif + // Clear everything else for (int i = 0; i < g.Windows.Size; i++) IM_DELETE(g.Windows[i]); diff --git a/imgui.h b/imgui.h index 3751f2e3..9c926c86 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,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.77" -#define IMGUI_VERSION_NUM 17700 +#define IMGUI_VERSION_NUM 17701 #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_internal.h b/imgui_internal.h index dd61fea6..01a7a82c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2028,8 +2028,8 @@ IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned ch // [SECTION] Test Engine Hooks (imgui_test_engine) //----------------------------------------------------------------------------- -//#define IMGUI_ENABLE_TEST_ENGINE #ifdef IMGUI_ENABLE_TEST_ENGINE +extern void ImGuiTestEngineHook_Shutdown(ImGuiContext* ctx); extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); From 0738611559b0a51c7fa0c376eb9601587231f841 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Tue, 30 Jun 2020 15:31:54 +0200 Subject: [PATCH 121/223] Misc: Bunch of code formatting changes suggested by a pass running 'astyle' --- examples/imgui_impl_allegro5.cpp | 16 +-- examples/imgui_impl_dx10.cpp | 2 +- examples/imgui_impl_dx11.cpp | 2 +- examples/imgui_impl_dx12.cpp | 5 +- examples/imgui_impl_dx9.cpp | 4 +- examples/imgui_impl_glfw.cpp | 2 +- examples/imgui_impl_glut.cpp | 8 +- examples/imgui_impl_marmalade.cpp | 10 +- examples/imgui_impl_metal.h | 2 +- examples/imgui_impl_osx.h | 4 +- examples/imgui_impl_vulkan.cpp | 4 +- examples/imgui_impl_win32.cpp | 6 +- imgui.cpp | 116 +++++++++---------- imgui.h | 32 +++--- imgui_demo.cpp | 128 ++++++++++----------- imgui_draw.cpp | 96 ++++++++-------- imgui_internal.h | 32 +++--- imgui_widgets.cpp | 154 +++++++++++++------------- misc/fonts/binary_to_compressed_c.cpp | 20 ++-- misc/freetype/imgui_freetype.cpp | 8 +- 20 files changed, 326 insertions(+), 325 deletions(-) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 2c7df9a9..4a467c30 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -174,7 +174,7 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplAllegro5_CreateDeviceObjects() { // Build texture atlas - ImGuiIO &io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); @@ -182,7 +182,7 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() // Create texture int flags = al_get_new_bitmap_flags(); int fmt = al_get_new_bitmap_format(); - al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP|ALLEGRO_MIN_LINEAR|ALLEGRO_MAG_LINEAR); + al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE); ALLEGRO_BITMAP* img = al_create_bitmap(width, height); al_set_new_bitmap_flags(flags); @@ -190,13 +190,13 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() if (!img) return false; - ALLEGRO_LOCKED_REGION *locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY); + ALLEGRO_LOCKED_REGION* locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY); if (!locked_img) { al_destroy_bitmap(img); return false; } - memcpy(locked_img->data, pixels, sizeof(int)*width*height); + memcpy(locked_img->data, pixels, sizeof(int) * width * height); al_unlock_bitmap(img); // Convert software texture to hardware texture. @@ -211,7 +211,7 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() // Create an invisible mouse cursor // Because al_hide_mouse_cursor() seems to mess up with the actual inputs.. - ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8,8); + ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8, 8); g_MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0); al_destroy_bitmap(mouse_cursor); @@ -322,7 +322,7 @@ void ImGui_ImplAllegro5_Shutdown() // - 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. -bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT *ev) +bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) { ImGuiIO& io = ImGui::GetIO(); @@ -403,7 +403,7 @@ void ImGui_ImplAllegro5_NewFrame() if (!g_Texture) ImGui_ImplAllegro5_CreateDeviceObjects(); - ImGuiIO &io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; @@ -413,7 +413,7 @@ void ImGui_ImplAllegro5_NewFrame() // Setup time step double current_time = al_get_time(); - io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; // Setup inputs diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 23ade277..beade17f 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -287,7 +287,7 @@ static void ImGui_ImplDX10_CreateFontsTexture() desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - ID3D10Texture2D *pTexture = NULL; + ID3D10Texture2D* pTexture = NULL; D3D10_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 26eb407f..0f4a8615 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -299,7 +299,7 @@ static void ImGui_ImplDX11_CreateFontsTexture() desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - ID3D11Texture2D *pTexture = NULL; + ID3D11Texture2D* pTexture = NULL; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 167a189b..e9cd45c6 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -359,7 +359,7 @@ static void ImGui_ImplDX12_CreateFontsTexture() hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); - cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &cmdList); + cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); hr = cmdQueue->Signal(fence, 1); IM_ASSERT(SUCCEEDED(hr)); @@ -509,7 +509,8 @@ bool ImGui_ImplDX12_CreateDeviceObjects() psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() }; // Create the input layout - static D3D12_INPUT_ELEMENT_DESC local_layout[] = { + static D3D12_INPUT_ELEMENT_DESC local_layout[] = + { { "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 }, diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 03114aa8..b4c49cdc 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -199,7 +199,7 @@ 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, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_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); } } global_idx_offset += cmd_list->IdxBuffer.Size; @@ -250,7 +250,7 @@ static bool ImGui_ImplDX9_CreateFontsTexture() if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK) return false; for (int y = 0; y < height; y++) - memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel)); + memcpy((unsigned char*)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel)); g_FontTexture->UnlockRect(0); // Store our identifier diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index ef63c81f..5ea7be08 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -358,7 +358,7 @@ void ImGui_ImplGlfw_NewFrame() // Setup time step double current_time = glfwGetTime(); - io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; ImGui_ImplGlfw_UpdateMousePosAndButtons(); diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index 3c17bbfc..c8051452 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -25,9 +25,9 @@ #include "imgui.h" #include "imgui_impl_glut.h" #ifdef __APPLE__ - #include +#include #else - #include +#include #endif #ifdef _MSC_VER @@ -41,9 +41,9 @@ bool ImGui_ImplGLUT_Init() ImGuiIO& io = ImGui::GetIO(); #ifdef FREEGLUT - io.BackendPlatformName ="imgui_impl_glut (freeglut)"; + io.BackendPlatformName = "imgui_impl_glut (freeglut)"; #else - io.BackendPlatformName ="imgui_impl_glut"; + io.BackendPlatformName = "imgui_impl_glut"; #endif g_Time = 0; diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index 0675c6b4..00626072 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -36,7 +36,7 @@ static char* g_ClipboardText = NULL; static bool g_osdKeyboardEnabled = false; // use this setting to scale the interface - e.g. on device you could use 2 or 3 scale factor -static ImVec2 g_RenderScale = ImVec2(1.0f,1.0f); +static ImVec2 g_RenderScale = ImVec2(1.0f, 1.0f); // 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) @@ -272,18 +272,18 @@ void ImGui_Marmalade_NewFrame() // Setup display size (every frame to accommodate for window resizing) int w = IwGxGetScreenWidth(), h = IwGxGetScreenHeight(); io.DisplaySize = ImVec2((float)w, (float)h); - // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. + // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. io.DisplayFramebufferScale = g_scale; // Setup time step double current_time = s3eTimerGetUST() / 1000.0f; - io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; double mouse_x, mouse_y; mouse_x = s3ePointerGetX(); mouse_y = s3ePointerGetY(); - io.MousePos = ImVec2((float)mouse_x/g_scale.x, (float)mouse_y/g_scale.y); // Mouse position (set to -FLT_MAX,-FLT_MAX if no mouse / on another screen, etc.) + io.MousePos = ImVec2((float)mouse_x / g_scale.x, (float)mouse_y / g_scale.y); // Mouse position (set to -FLT_MAX,-FLT_MAX if no mouse / on another screen, etc.) for (int i = 0; i < 3; i++) { @@ -294,7 +294,7 @@ void ImGui_Marmalade_NewFrame() // TODO: Hide OS mouse cursor if ImGui is drawing it // s3ePointerSetInt(S3E_POINTER_HIDE_CURSOR,(io.MouseDrawCursor ? 0 : 1)); - // Show/hide OSD keyboard + // Show/hide OSD keyboard if (io.WantTextInput) { // Some text input widget is active? diff --git a/examples/imgui_impl_metal.h b/examples/imgui_impl_metal.h index f6e8fd2b..3e61085c 100644 --- a/examples/imgui_impl_metal.h +++ b/examples/imgui_impl_metal.h @@ -16,7 +16,7 @@ IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id device); IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor *renderPassDescriptor); +IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor); IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder); diff --git a/examples/imgui_impl_osx.h b/examples/imgui_impl_osx.h index dae5c0ce..d37652be 100644 --- a/examples/imgui_impl_osx.h +++ b/examples/imgui_impl_osx.h @@ -15,5 +15,5 @@ IMGUI_IMPL_API bool ImGui_ImplOSX_Init(); IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView *_Nullable view); -IMGUI_IMPL_API bool ImGui_ImplOSX_HandleEvent(NSEvent *_Nonnull event, NSView *_Nullable view); +IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view); +IMGUI_IMPL_API bool ImGui_ImplOSX_HandleEvent(NSEvent* _Nonnull event, NSView* _Nullable view); diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index c65b2db0..465060d5 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -221,7 +221,7 @@ static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, ui VkPhysicalDeviceMemoryProperties prop; vkGetPhysicalDeviceMemoryProperties(v->PhysicalDevice, &prop); for (uint32_t i = 0; i < prop.memoryTypeCount; i++) - if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<GetTexDataAsRGBA32(&pixels, &width, &height); - size_t upload_size = width*height*4*sizeof(char); + size_t upload_size = width * height * 4 * sizeof(char); VkResult err; diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 57d6e3ed..f6dd5b82 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -63,9 +63,9 @@ static bool g_WantUpdateHasGamepad = true; // Functions bool ImGui_ImplWin32_Init(void* hwnd) { - if (!::QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond)) + if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&g_TicksPerSecond)) return false; - if (!::QueryPerformanceCounter((LARGE_INTEGER *)&g_Time)) + if (!::QueryPerformanceCounter((LARGE_INTEGER*)&g_Time)) return false; // Setup back-end capabilities flags @@ -223,7 +223,7 @@ void ImGui_ImplWin32_NewFrame() // Setup time step INT64 current_time; - ::QueryPerformanceCounter((LARGE_INTEGER *)¤t_time); + ::QueryPerformanceCounter((LARGE_INTEGER*)¤t_time); io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond; g_Time = current_time; diff --git a/imgui.cpp b/imgui.cpp index 176326ed..295cb054 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -981,7 +981,7 @@ ImGuiIO::ImGuiIO() ConfigFlags = ImGuiConfigFlags_None; BackendFlags = ImGuiBackendFlags_None; DisplaySize = ImVec2(-1.0f, -1.0f); - DeltaTime = 1.0f/60.0f; + DeltaTime = 1.0f / 60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; @@ -1122,7 +1122,7 @@ static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; d3 = (d3 >= 0) ? d3 : -d3; - if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) { ImVec2 p_current(x4, y4); ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); @@ -1136,12 +1136,12 @@ static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, } else if (level < 10) { - float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; - float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; - float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; - float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; - float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; - float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; + float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f; + float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f; + float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f; + float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f; + float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f; + float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f; BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); } @@ -1595,7 +1595,7 @@ int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const cha { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); @@ -1642,7 +1642,7 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); - buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c ) & 0x3f)); return 3; } @@ -1679,13 +1679,13 @@ int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWch { char* buf_out = buf; const char* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else - buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); + buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c); } *buf_out = 0; return (int)(buf_out - buf); @@ -1721,7 +1721,7 @@ IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b) ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) { - float s = 1.0f/255.0f; + float s = 1.0f / 255.0f; return ImVec4( ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, @@ -1772,7 +1772,7 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& return; } - h = ImFmod(h, 1.0f) / (60.0f/360.0f); + h = ImFmod(h, 1.0f) / (60.0f / 360.0f); int i = (int)h; float f = h - (float)i; float p = v * (1.0f - s); @@ -1989,7 +1989,7 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector 0.0f) { - window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } @@ -2675,7 +2675,7 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) const float border_size = g.Style.FrameBorderSize; if (border_size > 0.0f) { - window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } @@ -2698,11 +2698,11 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl { const float THICKNESS = 2.0f; const float DISTANCE = 3.0f + THICKNESS * 0.5f; - display_rect.Expand(ImVec2(DISTANCE,DISTANCE)); + display_rect.Expand(ImVec2(DISTANCE, DISTANCE)); bool fully_visible = window->ClipRect.Contains(display_rect); if (!fully_visible) window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); - window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); + window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); if (!fully_visible) window->DrawList->PopClipRect(); } @@ -3820,7 +3820,7 @@ void ImGui::NewFrame() // 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.WithinFrameScopeWithImplicitWindow = true; - SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); + SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true); @@ -4460,7 +4460,7 @@ ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.BeginPopupStack.Size > 0) - return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos; + return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; return g.IO.MousePos; } @@ -4662,7 +4662,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, b ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; - flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; + flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow; flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag // Size @@ -4702,7 +4702,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, b { FocusWindow(child_window); NavInitWindow(child_window, false); - SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item + SetActiveID(id + 1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item g.ActiveIdSource = ImGuiInputSource_Nav; } return ret; @@ -4752,7 +4752,7 @@ void ImGui::EndChild() // When browsing a window that has no activable items (scroll only) we keep a highlight on the child if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow) - RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); + RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); } else { @@ -4978,10 +4978,10 @@ struct ImGuiResizeGripDef static const ImGuiResizeGripDef resize_grip_def[4] = { - { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower-right - { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower-left - { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper-left (Unused) - { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused) + { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right + { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left + { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused) + { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }, // Upper-right (Unused) }; struct ImGuiResizeBorderDef @@ -4993,16 +4993,16 @@ struct ImGuiResizeBorderDef static const ImGuiResizeBorderDef resize_border_def[4] = { - { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top - { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right - { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom - { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left + { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Top + { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right + { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }, // Bottom + { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f } // Left }; static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) { ImRect rect = window->Rect(); - if (thickness == 0.0f) rect.Max -= ImVec2(1,1); + if (thickness == 0.0f) rect.Max -= ImVec2(1, 1); if (border_n == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom @@ -5175,8 +5175,8 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { const ImGuiResizeBorderDef& def = resize_border_def[border_held]; ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); - window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle); - window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f); window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual } if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) @@ -5515,7 +5515,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) window->Active = true; window->HasCloseButton = (p_open != NULL); - window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); + window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX); window->IDStack.resize(1); window->DrawList->_ResetForNewFrame(); @@ -7067,10 +7067,10 @@ void ImGui::PushMultiItemsWidths(int components, float w_full) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiStyle& style = g.Style; - const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); + const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); window->DC.ItemWidthStack.push_back(w_item_last); - for (int i = 0; i < components-1; i++) + 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; @@ -7491,7 +7491,7 @@ void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags toolt 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; + ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; Begin(window_name, NULL, flags | extra_flags); } @@ -7564,7 +7564,7 @@ bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags) ImGuiWindow* ImGui::GetTopMostPopupModal() { ImGuiContext& g = *GImGui; - for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) + for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--) if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) if (popup->Flags & ImGuiWindowFlags_Modal) return popup; @@ -7838,7 +7838,7 @@ bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flag int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id, popup_flags); - return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) @@ -7851,7 +7851,7 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_fl if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) OpenPopupEx(id, popup_flags); - return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) @@ -7864,7 +7864,7 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flag if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) if (GetTopMostPopupModal() == NULL) OpenPopupEx(id, popup_flags); - return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) @@ -8083,7 +8083,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items if (dby != 0.0f && dbx != 0.0f) - dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); + dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); float dist_box = ImFabs(dbx) + ImFabs(dby); // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) @@ -8124,7 +8124,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) ImDrawList* draw_list = 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 + CalcTextSize(buf) + ImVec2(4,4), IM_COL32(40,0,0,150)); + draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150)); draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf); } else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate. @@ -8138,7 +8138,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf); } } - #endif +#endif // Is it in the quadrant we're interesting in moving to? bool new_best = false; @@ -8214,7 +8214,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_Disabled|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 @@ -8649,7 +8649,7 @@ static void ImGui::NavUpdate() // *Normal* Manual scroll with NavScrollXXX keys // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. - ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); + ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f); if (scroll_dir.x != 0.0f && window->ScrollbarX) { SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); @@ -8671,7 +8671,7 @@ static void ImGui::NavUpdate() if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == ImGuiNavLayer_Main) { ImGuiWindow* window = g.NavWindow; - ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.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; @@ -8683,7 +8683,7 @@ static void ImGui::NavUpdate() } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) - ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); + ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y); g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x); @@ -8901,7 +8901,7 @@ static void ImGui::NavEndFrame() static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; - for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--) + for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--) if (g.WindowsFocusOrder[i] == window) return i; return -1; @@ -9385,7 +9385,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop // FIXME-DRAG: Settle on a proper default visuals for drop target. r.Expand(3.5f); bool push_clip_rect = !window->ClipRect.Contains(r); - if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1)); + if (push_clip_rect) window->DrawList->PushClipRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1)); window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f); if (push_clip_rect) window->DrawList->PopClipRect(); } @@ -10222,7 +10222,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); - 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) + 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; } @@ -10250,7 +10250,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", - pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, + 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 (ImGui::IsItemHovered() && (show_drawcmd_mesh || show_drawcmd_aabb) && fg_draw_list) @@ -10276,11 +10276,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, true, false); // 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. + 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++) + for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) { - char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); + char* buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangle[3]; for (int n = 0; n < 3; n++, idx_i++) { diff --git a/imgui.h b/imgui.h index 9c926c86..724aa289 100644 --- a/imgui.h +++ b/imgui.h @@ -173,7 +173,7 @@ typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: f typedef void* ImTextureID; // User data for rendering back-end to identify a texture. This is whatever to you want it to be! read the FAQ about ImTextureID for details. #endif typedef unsigned int ImGuiID; // A unique ID used by widgets, typically hashed from a stack of string. -typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data); +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Decoded character types @@ -1254,13 +1254,13 @@ enum ImGuiColorEditFlags_ // 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, + 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__InputMask = ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_InputHSV + ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, + ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, + ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags__InputMask = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -1375,7 +1375,7 @@ struct ImVector inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } - inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } + 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 shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation @@ -1385,10 +1385,10 @@ struct ImVector inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); } - inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } - inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(T)); Size -= (int)count; return Data + off; } - inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } - inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } + inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } + inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last > it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(T)); Size -= (int)count; return Data + off; } + inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } + inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } @@ -1651,7 +1651,7 @@ struct ImGuiPayload ImGuiID SourceId; // Source item id ImGuiID SourceParentId; // Source parent id (if available) int DataFrameCount; // Data timestamp - char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max) + char DataType[32 + 1]; // Data type tag (short user-supplied string, 32 characters max) bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. @@ -1879,8 +1879,8 @@ struct ImColor ImVec4 Value; ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } - ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } - ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } + ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f / 255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } + ImColor(ImU32 rgba) { float sc = 1.0f / 255.0f; Value.x = (float)((rgba >> IM_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } @@ -1888,7 +1888,7 @@ struct ImColor // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } - static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } }; //----------------------------------------------------------------------------- @@ -2074,7 +2074,7 @@ struct ImDrawList // 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 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& center, float radius, float a_min, float a_max, int num_segments = 10); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7abe7dd7..e0fc9af7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -378,12 +378,12 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Configuration##2")) { - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); 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::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int*)&io.ConfigFlags, 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); + ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); // The "NoMouse" option above can get us stuck with a disable mouse! Provide an alternative way to fix it: if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) @@ -396,7 +396,7 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Space))) io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; } - ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); + ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); ImGui::SameLine(); HelpMarker("Instruct back-end to not alter mouse cursor shape and visibility."); ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); ImGui::SameLine(); HelpMarker("Set to false to disable blinking cursor, for users who consider it distracting"); @@ -417,10 +417,10 @@ void ImGui::ShowDemoWindow(bool* p_open) // Make a local copy to avoid modifying actual back-end flags. ImGuiBackendFlags backend_flags = io.BackendFlags; - 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: RendererHasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); + 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: RendererHasVtxOffset", (unsigned int*)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); ImGui::TreePop(); ImGui::Separator(); } @@ -507,9 +507,9 @@ static void ShowDemoWindowWidgets() if (i > 0) ImGui::SameLine(); ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.6f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.7f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i/7.0f, 0.8f, 0.8f)); + ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); ImGui::Button("Click"); ImGui::PopStyleColor(3); ImGui::PopID(); @@ -615,17 +615,17 @@ static void ShowDemoWindowWidgets() ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%"); - static float f1=1.00f, f2=0.0067f; + static float f1 = 1.00f, f2 = 0.0067f; ImGui::DragFloat("drag float", &f1, 0.005f); ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); } { - static int i1=0; + static int i1 = 0; ImGui::SliderInt("slider int", &i1, -1, 3); ImGui::SameLine(); HelpMarker("CTRL+click to input value."); - static float f1=0.123f, f2=0.0f; + 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); @@ -644,8 +644,8 @@ 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 }; + 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(); HelpMarker( "Click on the colored square to open a color picker.\n" @@ -822,8 +822,8 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Colored Text")) { // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. - 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::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(); HelpMarker("The TextDisabled color is stored in ImGuiStyle."); ImGui::TreePop(); @@ -1079,11 +1079,11 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Grid")) { - static int selected[4*4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; - for (int i = 0; i < 4*4; i++) + static int selected[4 * 4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; + for (int i = 0; i < 4 * 4; i++) { ImGui::PushID(i); - if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50,50))) + if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50, 50))) { // Toggle selected[i] = !selected[i]; @@ -1118,7 +1118,7 @@ static void ShowDemoWindowWidgets() 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::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80)); ImGui::PopStyleVar(); } } @@ -1253,9 +1253,9 @@ static void ShowDemoWindowWidgets() { static float phase = 0.0f; values[values_offset] = cosf(phase); - values_offset = (values_offset+1) % IM_ARRAYSIZE(values); - phase += 0.10f*values_offset; - refresh_time += 1.0f/60.0f; + values_offset = (values_offset + 1) % IM_ARRAYSIZE(values); + phase += 0.10f * values_offset; + refresh_time += 1.0f / 60.0f; } // Plots can display overlay texts @@ -1286,8 +1286,8 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); ImGui::SliderInt("Sample count", &display_count, 1, 400); float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; - ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); - ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); ImGui::Separator(); // Animate a simple progress bar @@ -1301,20 +1301,20 @@ static void ShowDemoWindowWidgets() // 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::ProgressBar(progress, ImVec2(0.0f, 0.0f)); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::Text("Progress Bar"); float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); char buf[32]; - sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); - ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); + sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf); ImGui::TreePop(); } if (ImGui::TreeNode("Color/Picker Widgets")) { - static ImVec4 color = ImVec4(114.0f/255.0f, 144.0f/255.0f, 154.0f/255.0f, 200.0f/255.0f); + 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; @@ -1381,9 +1381,9 @@ static void ShowDemoWindowWidgets() ImGui::BeginGroup(); // Lock X position ImGui::Text("Current"); - ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40)); + ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); ImGui::Text("Previous"); - if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40))) + if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) color = backup_color; ImGui::Separator(); ImGui::Text("Palette"); @@ -1394,7 +1394,7 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; - if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20,20))) + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! // Allow user to drop colors into each palette entry. Note that ColorButton() is already a @@ -1417,14 +1417,14 @@ static void ShowDemoWindowWidgets() ImGui::Text("Color button only:"); static bool no_border = false; ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); - ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80,80)); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); ImGui::Text("Color picker:"); static bool alpha = true; static bool alpha_bar = true; static bool side_preview = true; static bool ref_color = false; - static ImVec4 ref_color_v(1.0f,0.0f,1.0f,0.5f); + static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f); static int display_mode = 0; static int picker_mode = 0; ImGui::Checkbox("With Alpha", &alpha); @@ -1639,7 +1639,7 @@ static void ShowDemoWindowWidgets() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); static int int_value = 0; - ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); + ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); ImGui::SameLine(); static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; @@ -1648,11 +1648,11 @@ static void ShowDemoWindowWidgets() { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i/7.0f, 0.5f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i/7.0f, 0.9f, 0.9f)); - ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); + ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values[i]); ImGui::PopStyleColor(4); @@ -1671,7 +1671,7 @@ static void ShowDemoWindowWidgets() ImGui::BeginGroup(); for (int ny = 0; ny < rows; ny++) { - ImGui::PushID(nx*rows+ny); + ImGui::PushID(nx * rows + ny); ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values2[nx]); @@ -1688,7 +1688,7 @@ static void ShowDemoWindowWidgets() if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); - ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); ImGui::PopStyleVar(); ImGui::PopID(); } @@ -1736,7 +1736,7 @@ static void ShowDemoWindowWidgets() ImGui::PushID(n); if ((n % 3) != 0) ImGui::SameLine(); - ImGui::Button(names[n], ImVec2(60,60)); + ImGui::Button(names[n], ImVec2(60, 60)); // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) @@ -2560,8 +2560,8 @@ static void ShowDemoWindowLayout() ImGui::PushID(n + line * 1000); char num_buf[16]; sprintf(num_buf, "%d", n); - const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : num_buf; - float hue = n*0.05f; + const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf; + float hue = n * 0.05f; ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f)); @@ -2906,7 +2906,7 @@ static void ShowDemoWindowPopups() // Testing behavior of widgets stacking their own regular popups over the modal. static int item = 1; - static float color[4] = { 0.4f,0.7f,0.0f,0.5f }; + static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); ImGui::ColorEdit4("color", color); @@ -3933,7 +3933,7 @@ static void ShowExampleMenuFile() { const char* name = ImGui::GetStyleColorName((ImGuiCol)i); ImVec2 p = ImGui::GetCursorScreenPos(); - ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x+sz, p.y+sz), ImGui::GetColorU32((ImGuiCol)i)); + ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i)); ImGui::Dummy(ImVec2(sz, sz)); ImGui::SameLine(); ImGui::MenuItem(name); @@ -4025,7 +4025,7 @@ struct ExampleAppConsole void Draw(const char* title, bool* p_open) { - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); if (!ImGui::Begin(title, p_open)) { ImGui::End(); @@ -4103,7 +4103,7 @@ struct ExampleAppConsole // If your items are of variable height: // - Split them into same height items would be simpler and facilitate random-seeking into your list. // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); for (int i = 0; i < Items.Size; i++) @@ -4163,7 +4163,7 @@ struct ExampleAppConsole // Insert into history. First find match and delete it so it can be pushed to the back. // This isn't trying to be smart or optimal. HistoryPos = -1; - for (int i = History.Size-1; i >= 0; i--) + for (int i = History.Size - 1; i >= 0; i--) if (Stricmp(History[i], command_line) == 0) { free(History[i]); @@ -4228,18 +4228,18 @@ struct ExampleAppConsole // Build a list of candidates ImVector candidates; for (int i = 0; i < Commands.Size; i++) - if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) + if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0) candidates.push_back(Commands[i]); if (candidates.Size == 0) { // No match - AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); + AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start); } else if (candidates.Size == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. - data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } @@ -4264,7 +4264,7 @@ struct ExampleAppConsole if (match_len > 0) { - data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); } @@ -4552,7 +4552,7 @@ static void ShowDummyObject(const char* prefix, int uid) ImGui::NextColumn(); if (node_open) { - static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + static float dummy_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; for (int i = 0; i < 8; i++) { ImGui::PushID(i); // Use field index as identifier. @@ -4584,7 +4584,7 @@ static void ShowDummyObject(const char* prefix, int uid) // Demonstrate create a simple property editor. static void ShowExampleAppPropertyEditor(bool* p_open) { - ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Example: Property editor", p_open)) { ImGui::End(); @@ -4597,7 +4597,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open) "Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\n" "your cursor horizontally instead of using the Columns() API."); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); ImGui::Columns(2); ImGui::Separator(); @@ -4618,7 +4618,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open) // Demonstrate/test rendering huge amount of text, and the incidence of clipping. static void ShowExampleAppLongText(bool* p_open) { - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Example: Long text display", p_open)) { ImGui::End(); @@ -4639,7 +4639,7 @@ static void ShowExampleAppLongText(bool* p_open) if (ImGui::Button("Add 1000 lines")) { for (int i = 0; i < 1000; i++) - log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines+i); + log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i); lines += 1000; } ImGui::BeginChild("Log"); @@ -4996,7 +4996,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), 0, 10+4); + ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4); if (draw_fg) ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10); ImGui::EndTabItem(); @@ -5022,7 +5022,7 @@ struct MyDocument bool WantClose; // Set when the document ImVec4 Color; // An arbitrary variable associated to the document - MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f,1.0f,1.0f,1.0f)) + MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)) { Name = name; Open = OpenPrev = open; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 49197277..87e59205 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -668,7 +668,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const ImVec2 opaque_uv = _Data->TexUvWhitePixel; int count = points_count; if (!closed) - count = points_count-1; + count = points_count - 1; const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) @@ -677,8 +677,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int idx_count = thick_line ? count*18 : count*12; - const int vtx_count = thick_line ? points_count*4 : points_count*3; + const int idx_count = thick_line ? count * 18 : count * 12; + const int vtx_count = thick_line ? points_count * 4 : points_count * 3; PrimReserve(idx_count, vtx_count); // Temporary buffer @@ -687,7 +687,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; float dx = points[i2].x - points[i1].x; float dy = points[i2].y - points[i1].y; IM_NORMALIZE2F_OVER_ZERO(dx, dy); @@ -695,7 +695,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_normals[i1].y = -dx; } if (!closed) - temp_normals[points_count-1] = temp_normals[points_count-2]; + temp_normals[points_count - 1] = temp_normals[points_count - 2]; if (!thick_line) { @@ -711,8 +711,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; - unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -722,7 +722,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_y *= AA_SIZE; // Add temporary vertices - ImVec2* out_vtx = &temp_points[i2*2]; + ImVec2* out_vtx = &temp_points[i2 * 2]; out_vtx[0].x = points[i2].x + dm_x; out_vtx[0].y = points[i2].y + dm_y; out_vtx[1].x = points[i2].x - dm_x; @@ -780,7 +780,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 float dm_in_y = dm_y * half_inner_thickness; // Add temporary vertices - ImVec2* out_vtx = &temp_points[i2*4]; + ImVec2* out_vtx = &temp_points[i2 * 4]; out_vtx[0].x = points[i2].x + dm_out_x; out_vtx[0].y = points[i2].y + dm_out_y; out_vtx[1].x = points[i2].x + dm_in_x; @@ -817,13 +817,13 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 else { // Non Anti-aliased Stroke - const int idx_count = count*6; - const int vtx_count = count*4; // FIXME-OPT: Not sharing edges + const int idx_count = count * 6; + const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; const ImVec2& p1 = points[i1]; const ImVec2& p2 = points[i2]; @@ -860,22 +860,22 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun // Anti-aliased Fill const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int idx_count = (points_count-2)*3 + points_count*6; - const int vtx_count = (points_count*2); + const int idx_count = (points_count - 2)*3 + points_count * 6; + const int vtx_count = (points_count * 2); PrimReserve(idx_count, vtx_count); // Add indexes for fill unsigned int vtx_inner_idx = _VtxCurrentIdx; - unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + unsigned int vtx_outer_idx = _VtxCurrentIdx + 1; for (int i = 2; i < points_count; i++) { - _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1)); _IdxWritePtr += 3; } // Compute normals ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630 - for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { const ImVec2& p0 = points[i0]; const ImVec2& p1 = points[i1]; @@ -886,7 +886,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun temp_normals[i0].y = -dx; } - for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { // Average normals const ImVec2& n0 = temp_normals[i0]; @@ -903,8 +903,8 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun _VtxWritePtr += 2; // Add indexes for fringes - _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); - _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr += 6; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; @@ -912,7 +912,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun else { // Non Anti-aliased Fill - const int idx_count = (points_count-2)*3; + const int idx_count = (points_count - 2)*3; const int vtx_count = points_count; PrimReserve(idx_count, vtx_count); for (int i = 0; i < vtx_count; i++) @@ -922,7 +922,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun } for (int i = 2; i < points_count; i++) { - _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i); _IdxWritePtr += 3; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; @@ -989,20 +989,20 @@ static void PathBezierToCasteljau(ImVector* path, float x1, float y1, fl float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; d3 = (d3 >= 0) ? d3 : -d3; - if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) { path->push_back(ImVec2(x4, y4)); } else if (level < 10) { - float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; - float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; - float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; - float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; - float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; - float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; - PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); - PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); + float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f; + float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f; + float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f; + float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f; + float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f; + float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f; + PathBezierToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); + PathBezierToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); } } @@ -1062,9 +1062,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if ((col & IM_COL32_A_MASK) == 0) return; if (Flags & ImDrawListFlags_AntiAliasedLines) - PathRect(p_min + ImVec2(0.50f,0.50f), p_max - ImVec2(0.50f,0.50f), rounding, rounding_corners); + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, rounding_corners); else - 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. + 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); } @@ -1092,8 +1092,8 @@ void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_ma const ImVec2 uv = _Data->TexUvWhitePixel; 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)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 3)); 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); @@ -1787,15 +1787,15 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) } // Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) -static unsigned int stb_decompress_length(const unsigned char *input); -static unsigned int stb_decompress(unsigned char *output, const unsigned char *input, unsigned int length); +static unsigned int stb_decompress_length(const unsigned char* input); +static unsigned int stb_decompress(unsigned char* output, const unsigned char* input, unsigned int length); static const char* GetDefaultCompressedFontDataTTFBase85(); static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } static void Decode85(const unsigned char* src, unsigned char* dst) { while (*src) { - unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4])))); dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. src += 5; dst += 4; @@ -1862,7 +1862,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 *)IM_ALLOC(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(); @@ -2149,7 +2149,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) if (atlas->TexDesiredWidth > 0) atlas->TexWidth = atlas->TexDesiredWidth; else - atlas->TexWidth = (surface_sqrt >= 4096*0.7f) ? 4096 : (surface_sqrt >= 2048*0.7f) ? 2048 : (surface_sqrt >= 1024*0.7f) ? 1024 : 512; + atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512; // 5. Start packing // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). @@ -2262,7 +2262,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->CustomRectIds[0] >= 0) return; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); else atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(2, 2); } @@ -2712,7 +2712,7 @@ void ImFont::BuildLookupTable() tab_glyph.Codepoint = '\t'; tab_glyph.AdvanceX *= IM_TABSIZE; IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; - IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size-1); + IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size - 1); } // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons) @@ -3207,7 +3207,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col // Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink() draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data); - draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + 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 = vtx_current_idx; @@ -3293,10 +3293,10 @@ void ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, Im pos -= offset; const ImTextureID tex_id = font_atlas->TexID; draw_list->PushTextureID(tex_id); - draw_list->AddImage(tex_id, pos + ImVec2(1,0)*scale, pos + ImVec2(1,0)*scale + size*scale, uv[2], uv[3], col_shadow); - draw_list->AddImage(tex_id, pos + ImVec2(2,0)*scale, pos + ImVec2(2,0)*scale + size*scale, uv[2], uv[3], col_shadow); - draw_list->AddImage(tex_id, pos, pos + size*scale, uv[2], uv[3], col_border); - draw_list->AddImage(tex_id, pos, pos + size*scale, uv[0], uv[1], col_fill); + draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow); + draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border); + draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill); draw_list->PopTextureID(); } } @@ -3551,7 +3551,7 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i // Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding). // The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. //----------------------------------------------------------------------------- -static const char proggy_clean_ttf_compressed_data_base85[11980+1] = +static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] = "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a 1.0f) ? 1.0f : f; } -static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } -static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } -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 ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } +static inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } +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; } @@ -1315,7 +1315,7 @@ struct ImGuiContext int WantCaptureMouseNextFrame; // Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags int WantCaptureKeyboardNextFrame; int WantTextInputNextFrame; - char TempBuffer[1024*3+1]; // Temporary text buffer + char TempBuffer[1024 * 3 + 1]; // Temporary text buffer ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(&DrawListSharedData), ForegroundDrawList(&DrawListSharedData) { @@ -1355,7 +1355,7 @@ struct ImGuiContext ActiveIdUsingNavDirMask = 0x00; ActiveIdUsingNavInputMask = 0x00; ActiveIdUsingKeyInputMask = 0x00; - ActiveIdClickOffset = ImVec2(-1,-1); + ActiveIdClickOffset = ImVec2(-1, -1); ActiveIdWindow = NULL; ActiveIdSource = ImGuiInputSource_None; ActiveIdMouseButton = 0; @@ -1650,7 +1650,7 @@ 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); } + 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())); } @@ -1956,7 +1956,7 @@ namespace ImGui IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); 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 bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col); + IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col); IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowResizeID(ImGuiWindow* window, int n); // 0..3: corners, 4..7: borders diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 918dbf94..7d6bf847 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -160,7 +160,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) // - 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(); - ImVec2 text_size(0,0); + ImVec2 text_size(0, 0); // Lines to skip (can't skip when logging text) ImVec2 pos = text_pos; @@ -332,8 +332,8 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) 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)); - const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); + const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2)); + const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y * 2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, 0)) return; @@ -341,7 +341,7 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) // Render const char* value_text_begin = &g.TempBuffer[0]; const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); - RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); + RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f, 0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } @@ -377,7 +377,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // Render ImU32 text_col = GetColorU32(ImGuiCol_Text); - RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, g.FontSize*0.5f), text_col); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col); RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false); } @@ -781,8 +781,8 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size) 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); - window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f); + window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); + window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); return pressed; } @@ -1067,7 +1067,7 @@ bool ImGui::Checkbox(const char* label, bool* v) else if (*v) { const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f)); - RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad*2.0f); + RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f); } if (g.LogEnabled) @@ -1133,7 +1133,7 @@ bool ImGui::RadioButton(const char* label, bool active) 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); } @@ -1166,7 +1166,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, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f); ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, 0)) @@ -1183,13 +1183,13 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over char overlay_buf[32]; if (!overlay) { - ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f); overlay = overlay_buf; } ImVec2 overlay_size = CalcTextSize(overlay, NULL); if (overlay_size.x > 0.0f) - RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb); } void ImGui::Bullet() @@ -1200,18 +1200,18 @@ void ImGui::Bullet() ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float line_height = ImMax(ImMin(window->DC.CurrLineSize.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)) { - SameLine(0, style.FramePadding.x*2); + SameLine(0, style.FramePadding.x * 2); return; } // Render and stay on same line 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); + 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); } @@ -1484,7 +1484,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const ImVec2 label_size = CalcTextSize(label, NULL, true); 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 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); if (!ItemAdd(total_bb, id, &frame_bb)) @@ -1509,7 +1509,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF } RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding); if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) - RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), 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); @@ -2011,7 +2011,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings float adjust_delta = 0.0f; - if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f) + if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f * 1.0f) { adjust_delta = g.IO.MouseDelta[axis]; if (g.IO.KeyAlt) @@ -2148,7 +2148,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, const ImGuiID id = window->GetID(label); 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 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); @@ -2369,12 +2369,12 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m if (v_clamped < 0.0f) { const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min)); - return (1.0f - ImPow(f, 1.0f/power)) * linear_zero_pos; + return (1.0f - ImPow(f, 1.0f / power)) * linear_zero_pos; } else { const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min))); - return linear_zero_pos + ImPow(f, 1.0f/power) * (1.0f - linear_zero_pos); + return linear_zero_pos + ImPow(f, 1.0f / power) * (1.0f - linear_zero_pos); } } @@ -2450,7 +2450,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if ((decimal_precision > 0) || is_power) { @@ -2522,7 +2522,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } // Round to user desired precision based on format string - v_new = RoundScalarWithFormatT(format, data_type, v_new); + v_new = RoundScalarWithFormatT(format, data_type, v_new); // Apply result if (*v != v_new) @@ -2565,23 +2565,23 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } case ImGuiDataType_S32: - IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN/2 && *(const ImS32*)p_max <= IM_S32_MAX/2); + IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_U32: - IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX/2); + IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_S64: - IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN/2 && *(const ImS64*)p_max <= IM_S64_MAX/2); + IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_U64: - IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX/2); + IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_Float: - IM_ASSERT(*(const float*)p_min >= -FLT_MAX/2.0f && *(const float*)p_max <= FLT_MAX/2.0f); + IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f); return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_Double: - IM_ASSERT(*(const double*)p_min >= -DBL_MAX/2.0f && *(const double*)p_max <= DBL_MAX/2.0f); - return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, power, flags, out_grab_bb); + IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f); + return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); @@ -2602,7 +2602,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat 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 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); @@ -2659,7 +2659,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // 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, p_data, format); - RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); + 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, frame_bb.Min.y + style.FramePadding.y), label); @@ -2728,9 +2728,9 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl { if (format == NULL) format = "%.0f deg"; - float v_deg = (*v_rad) * 360.0f / (2*IM_PI); + float v_deg = (*v_rad) * 360.0f / (2 * IM_PI); bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); - *v_rad = v_deg * (2*IM_PI) / 360.0f; + *v_rad = v_deg * (2 * IM_PI) / 360.0f; return value_changed; } @@ -2806,7 +2806,7 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); - RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -3097,7 +3097,7 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_dat bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) { flags |= ImGuiInputTextFlags_CharsScientific; - return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), format, flags); + return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags); } bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags) @@ -3154,7 +3154,7 @@ bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiIn { // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; - return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), format, flags); + return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags); } bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) @@ -3175,7 +3175,7 @@ bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) { flags |= ImGuiInputTextFlags_CharsScientific; - return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), format, flags); + return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags); } //------------------------------------------------------------------------- @@ -3286,10 +3286,10 @@ static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* ob } static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } -static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->TextW[idx-1] ) && !is_separator( obj->TextW[idx] ) ) : 1; } +static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator(obj->TextW[idx - 1]) && !is_separator(obj->TextW[idx]) ) : 1; } static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } #ifdef __APPLE__ // FIXME: Move setting to IO structure -static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; } +static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator(obj->TextW[idx - 1]) && is_separator(obj->TextW[idx]) ) : 1; } static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } #else static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } @@ -3495,7 +3495,7 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f // Turn a-z into A-Z if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') - *p_char = (c += (unsigned int)('A'-'a')); + *p_char = (c += (unsigned int)('A' - 'a')); if (flags & ImGuiInputTextFlags_CharsNoBlank) if (ImCharIsBlankW(c)) @@ -3556,7 +3556,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); - const ImVec2 frame_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 ImVec2 frame_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 ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); @@ -3746,7 +3746,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Edit in progress 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 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])) @@ -3842,9 +3842,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (!state->HasSelection()) { if (is_wordmove_key_down) - state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); + 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); + state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT); } state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } @@ -3903,7 +3903,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*)IM_ALLOC((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; ) { @@ -4235,7 +4235,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); if (rect_size.x <= 0.0f) rect_size.x = IM_FLOOR(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines - ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); + ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn)); rect.ClipWith(clip_rect); if (rect.Overlaps(clip_rect)) draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); @@ -4406,8 +4406,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders - const float w_item_one = ImMax(1.0f, IM_FLOOR((w_inputs - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, IM_FLOOR(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + const float w_item_one = ImMax(1.0f, IM_FLOOR((w_inputs - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); + const float w_item_last = ImMax(1.0f, IM_FLOOR(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" }; @@ -4434,7 +4434,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 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, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); value_changed_as_float |= value_changed; } else @@ -4450,9 +4450,9 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // RGB Hexadecimal Input char buf[64]; if (alpha) - 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)); + 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)); + 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_inputs); if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { @@ -4484,7 +4484,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // Store current color and open a picker g.ColorPickerRef = col_v4; OpenPopup("picker"); - SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y)); + SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1, style.ItemSpacing.y)); } } if (!(flags & ImGuiColorEditFlags_NoOptions)) @@ -4645,7 +4645,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl float wheel_thickness = sv_picker_size * 0.08f; float wheel_r_outer = sv_picker_size * 0.50f; float wheel_r_inner = wheel_r_outer - wheel_thickness; - ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f); + ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f); // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic. float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f); @@ -4684,10 +4684,10 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center; ImVec2 current_off = g.IO.MousePos - wheel_center; float initial_dist2 = ImLengthSqr(initial_off); - if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1)) + if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1)) { // Interactive with Hue wheel - H = ImAtan2(current_off.y, current_off.x) / IM_PI*0.5f; + H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f; if (H < 0.0f) H += 1.0f; value_changed = value_changed_h = true; @@ -4716,8 +4716,8 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size)); if (IsItemActive()) { - S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1)); - V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1)); + V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); value_changed = value_changed_sv = true; } if (!(flags & ImGuiColorEditFlags_NoOptions)) @@ -4728,7 +4728,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl InvisibleButton("hue", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { - H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); value_changed = value_changed_h = true; } } @@ -4740,7 +4740,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { - col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); value_changed = true; } } @@ -4791,7 +4791,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl { 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]); + 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]); g.ColorEditLastHue = H; g.ColorEditLastSat = S; memcpy(g.ColorEditLastColor, col, sizeof(float) * 3); @@ -4894,17 +4894,17 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // 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, col_hues[n], col_hues[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 float cos_hue_angle = ImCos(H * 2.0f * IM_PI); float sin_hue_angle = ImSin(H * 2.0f * IM_PI); - ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f); + ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f); 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, col_midgrey, 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) @@ -4942,7 +4942,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // 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, 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 + 1, col_midgrey, 12); draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, 12); // Render alpha bar @@ -5014,8 +5014,8 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) { float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f); - RenderColorRectWithAlphaCheckerboard(window->DrawList, 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); + RenderColorRectWithAlphaCheckerboard(window->DrawList, 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 { @@ -5133,7 +5133,7 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) if (allow_opt_inputs || allow_opt_datatype) Separator(); - if (Button("Copy as..", ImVec2(-1,0))) + if (Button("Copy as..", ImVec2(-1, 0))) OpenPopup("Copy"); if (BeginPopup("Copy")) { @@ -5177,7 +5177,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl // Draw small/thumbnail version of each picker type (over an invisible button for selection) if (picker_type > 0) Separator(); PushID(picker_type); - ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha); + ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha); if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar; if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel; ImVec2 backup_pos = GetCursorScreenPos(); @@ -5361,7 +5361,7 @@ 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 frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + 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; frame_bb.Min.x = (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x; frame_bb.Min.y = window->DC.CursorPos.y; @@ -5375,9 +5375,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l frame_bb.Max.x += IM_FLOOR(window->WindowPadding.x * 0.5f); } - const float text_offset_x = g.FontSize + (display_frame ? padding.x*3 : padding.x*2); // Collapser arrow width + Spacing + const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapser arrow width + Spacing const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it - const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x * 2 : 0.0f); // Include collapser ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y); ItemSize(ImVec2(text_width, frame_height), padding.y); @@ -5511,9 +5511,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // 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. const char log_prefix[] = "\n##"; const char log_suffix[] = "##"; - LogRenderedText(&text_pos, log_prefix, log_prefix+3); + LogRenderedText(&text_pos, log_prefix, log_prefix + 3); RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); - LogRenderedText(&text_pos, log_suffix, log_suffix+2); + LogRenderedText(&text_pos, log_suffix, log_suffix + 2); } else { @@ -5988,7 +5988,7 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) - SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1); else if (plot_type == ImGuiPlotType_Histogram) SetTooltip("%d: %8.4g", v_idx, v0); idx_hovered = v_idx; @@ -6034,7 +6034,7 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get // Text overlay if (overlay_text) - RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f, 0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); @@ -7538,7 +7538,7 @@ void ImGui::SetColumnOffset(int column_index, float offset) 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 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)) diff --git a/misc/fonts/binary_to_compressed_c.cpp b/misc/fonts/binary_to_compressed_c.cpp index 4c6f1200..1f621e16 100644 --- a/misc/fonts/binary_to_compressed_c.cpp +++ b/misc/fonts/binary_to_compressed_c.cpp @@ -28,7 +28,7 @@ // stb_compress* from stb.h - declaration typedef unsigned int stb_uint; typedef unsigned char stb_uchar; -stb_uint stb_compress(stb_uchar *out,stb_uchar *in,stb_uint len); +stb_uint stb_compress(stb_uchar* out, stb_uchar* in, stb_uint len); static bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression); @@ -54,7 +54,7 @@ int main(int argc, char** argv) } } - bool ret = binary_to_compressed_c(argv[argn], argv[argn+1], use_base85_encoding, use_compression); + 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; @@ -63,7 +63,7 @@ int main(int argc, char** argv) char Encode85Byte(unsigned int x) { x = (x % 85) + 35; - return (x>='\\') ? x+1 : x; + return (x >= '\\') ? x + 1 : x; } bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression) @@ -73,7 +73,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b if (!f) return false; int data_sz; if (fseek(f, 0, SEEK_END) || (data_sz = (int)ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return false; } - char* data = new char[data_sz+4]; + char* data = new char[data_sz + 4]; if (fread(data, 1, data_sz, f) != (size_t)data_sz) { fclose(f); delete[] data; return false; } memset((void*)(((char*)data) + data_sz), 0, 4); fclose(f); @@ -83,16 +83,16 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b char* compressed = use_compression ? new char[maxlen] : data; int compressed_sz = use_compression ? stb_compress((stb_uchar*)compressed, (stb_uchar*)data, data_sz) : data_sz; if (use_compression) - memset(compressed + compressed_sz, 0, maxlen - compressed_sz); + memset(compressed + compressed_sz, 0, maxlen - compressed_sz); // Output as Base85 encoded FILE* out = stdout; fprintf(out, "// File: '%s' (%d bytes)\n", filename, (int)data_sz); fprintf(out, "// Exported using binary_to_compressed_c.cpp\n"); - const char* compressed_str = use_compression ? "compressed_" : ""; + const char* compressed_str = use_compression ? "compressed_" : ""; if (use_base85_encoding) { - fprintf(out, "static const char %s_%sdata_base85[%d+1] =\n \"", symbol, compressed_str, (int)((compressed_sz+3)/4)*5); + fprintf(out, "static const char %s_%sdata_base85[%d+1] =\n \"", symbol, compressed_str, (int)((compressed_sz + 3) / 4)*5); char prev_c = 0; for (int src_i = 0; src_i < compressed_sz; src_i += 4) { @@ -104,7 +104,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b fprintf(out, (c == '?' && prev_c == '?') ? "\\%c" : "%c", c); prev_c = c; } - if ((src_i % 112) == 112-4) + if ((src_i % 112) == 112 - 4) fprintf(out, "\"\n \""); } fprintf(out, "\";\n\n"); @@ -112,7 +112,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b else { fprintf(out, "static const unsigned int %s_%ssize = %d;\n", symbol, compressed_str, (int)compressed_sz); - fprintf(out, "static const unsigned int %s_%sdata[%d/4] =\n{", symbol, compressed_str, (int)((compressed_sz+3)/4)*4); + fprintf(out, "static const unsigned int %s_%sdata[%d/4] =\n{", symbol, compressed_str, (int)((compressed_sz + 3) / 4)*4); int column = 0; for (int i = 0; i < compressed_sz; i += 4) { @@ -128,7 +128,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b // Cleanup delete[] data; if (use_compression) - delete[] compressed; + delete[] compressed; return true; } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 20a3be0e..b76bc6e0 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -13,7 +13,7 @@ // - 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!) -// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. +// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. // Gamma Correct Blending: // FreeType assumes blending in linear space rather than gamma space. @@ -502,7 +502,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns if (atlas->TexDesiredWidth > 0) atlas->TexWidth = atlas->TexDesiredWidth; else - atlas->TexWidth = (surface_sqrt >= 4096*0.7f) ? 4096 : (surface_sqrt >= 2048*0.7f) ? 2048 : (surface_sqrt >= 1024*0.7f) ? 1024 : 512; + atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512; // 5. Start packing // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). @@ -609,8 +609,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 IM_ALLOC(size); } -static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(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; From ab4ef822f0e85a6dd65723db9e0e632a1e1a45d8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 16:56:09 +0200 Subject: [PATCH 122/223] Version 1.78 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 +- 8 files changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4d757e0b..c62a140d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -31,6 +31,11 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.78 WIP (In Progress) +----------------------------------------------------------------------- + + ----------------------------------------------------------------------- VERSION 1.77 (Released 2020-06-29) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 2137fe09..35ee87b9 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.77 + dear imgui, v1.78 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 295cb054..d8bf40be 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 724aa289..dc4fa453 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (headers) // Help: @@ -59,8 +59,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.77" -#define IMGUI_VERSION_NUM 17701 +#define IMGUI_VERSION "1.78 WIP" +#define IMGUI_VERSION_NUM 17702 #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 e0fc9af7..a2208ebe 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 87e59205..ade1290d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index f55a061b..b57b01b5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 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 7d6bf847..86295bcd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (widgets code) /* From 2b9d88196e76c988bc28e615aa4fe12dc51c8fc8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 18:52:02 +0200 Subject: [PATCH 123/223] Docking: Rework size allocations to recover when there's no enough room for nodes + do not hold on WantLockSizeOnce forever (#3328) (Ensure if the fact that WantLockSizeOnce was kept when only 1 child is visible was desired/desirable) --- imgui.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cf5f13b5..3936fd32 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13793,16 +13793,14 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si IM_ASSERT(!(child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)); if (child_0->WantLockSizeOnce) { - child_0->WantLockSizeOnce = false; - child_0_size[axis] = child_0->SizeRef[axis] = child_0->Size[axis]; + child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, 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) { - child_1->WantLockSizeOnce = false; - child_1_size[axis] = child_1->SizeRef[axis] = child_1->Size[axis]; + child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, 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); } @@ -13825,8 +13823,11 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5F)); child_1_size[axis] = (size_avail - child_0_size[axis]); } + child_1_pos[axis] += spacing + child_0_size[axis]; } + child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false; + if (child_0->IsVisible) DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size); if (child_1->IsVisible) @@ -15584,7 +15585,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) 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" : ""); + ImGui::BulletText("Misc:%s%s%s%s%s", + node->IsDockSpace() ? " IsDockSpace" : "", + node->IsCentralNode() ? " IsCentralNode" : "", + (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", + (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : "", + node->WantLockSizeOnce ? " WantLockSizeOnce" : ""); if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) { ImGui::CheckboxFlags("LocalFlags: NoDocking", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoDocking); From 4bdbea8375557fcd3c8b46abde7cc0119c2c57d4 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 18:53:13 +0200 Subject: [PATCH 124/223] Docking: Rework size allocation to allow user code to override node sizes. Not all edge cases will be properly handled but this is a step toward toolbar emitting size constraints. --- imgui.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3936fd32..efcfc3c5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13790,20 +13790,27 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f); // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) - IM_ASSERT(!(child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)); - if (child_0->WantLockSizeOnce) + if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce) { child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, 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) + else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce) { child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, 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); } + else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce) + { + // FIXME-DOCK: We cannot honor the requested size, so apply ratio. + // Currently this path will only be taken if code programmatically sets WantLockSizeOnce + float ratio_0 = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]); + child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * ratio_0); + 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); + } // 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) From a1d2c6fad96ec7a3e444094a1522dc1796ab68fe Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 19:00:31 +0200 Subject: [PATCH 125/223] Fixed invalid comment (#3327) --- imgui.h | 2 +- imgui_demo.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index dc4fa453..2da0d21a 100644 --- a/imgui.h +++ b/imgui.h @@ -740,7 +740,7 @@ namespace ImGui IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held? IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down) IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) - IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. + IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? (note that a double-click will also report IsMouseClicked() == true) 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); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available IMGUI_API bool IsAnyMouseDown(); // is any mouse button held? diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a2208ebe..ed38e52f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3224,7 +3224,7 @@ static void ShowDemoWindowMisc() ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } - ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } 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); From fc9d6b6cb5956eb5a07e09c1d5e4685b1037109e Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 29 Nov 2019 17:52:30 +0100 Subject: [PATCH 126/223] Docking: Added experimental flags to perform more docking filtering and disable resize per axis. Designed for toolbar patterns. The local/shared flags specs, saving and inheriting rules are pretty inconsistent at the moment. --- imgui.cpp | 19 ++++++++++++++----- imgui.h | 2 +- imgui_internal.h | 11 +++++++++-- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index efcfc3c5..08fbff28 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13486,22 +13486,27 @@ static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockN IM_ASSERT(ref_node_for_rect->IsVisible); // Filter, figure out where we are allowed to dock - ImGuiDockNodeFlags host_node_flags = host_node ? host_node->GetMergedFlags() : 0; + ImGuiDockNodeFlags src_node_flags = root_payload_as_host ? root_payload_as_host->GetMergedFlags() : root_payload->WindowClass.DockNodeFlagsOverrideSet; + ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->GetMergedFlags() : host_window->WindowClass.DockNodeFlagsOverrideSet; data->IsCenterAvailable = true; if (is_outer_docking) data->IsCenterAvailable = false; - else if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDocking)) + else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking) data->IsCenterAvailable = false; - else if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode()) + else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode()) data->IsCenterAvailable = false; else if ((!host_node || !host_node->IsEmpty()) && root_payload_as_host && root_payload_as_host->IsSplitNode() && (root_payload_as_host->OnlyNodeWithWindows == NULL)) // Is _visibly_ split? data->IsCenterAvailable = false; + else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther)) + data->IsCenterAvailable = false; data->IsSidesAvailable = true; - if ((host_node && (host_node_flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) + if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit) data->IsSidesAvailable = false; else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode()) data->IsSidesAvailable = false; + else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)) + data->IsSidesAvailable = false; // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton); @@ -13877,7 +13882,9 @@ 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 ((child_0->GetMergedFlags() | child_1->GetMergedFlags()) & ImGuiDockNodeFlags_NoResize) + const ImGuiDockNodeFlags merged_flags = child_0->GetMergedFlags() | child_1->GetMergedFlags(); + const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY; + if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag)) { ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding); @@ -15603,6 +15610,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::CheckboxFlags("LocalFlags: NoDocking", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoDocking); ImGui::CheckboxFlags("LocalFlags: NoSplit", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); ImGui::CheckboxFlags("LocalFlags: NoResize", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("LocalFlags: NoResizeX", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResizeX); + ImGui::CheckboxFlags("LocalFlags: NoResizeY", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResizeY); 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); diff --git a/imgui.h b/imgui.h index d91a343f..233d2841 100644 --- a/imgui.h +++ b/imgui.h @@ -1739,7 +1739,7 @@ struct ImGuiWindowClass ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) ImGuiDockNodeFlags DockNodeFlagsOverrideClear; // [EXPERIMENTAL] bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (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. + bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. // FIXME-DOCK: Move to DockNodeFlags override? ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideSet = ViewportFlagsOverrideClear = 0x00; DockNodeFlagsOverrideSet = DockNodeFlagsOverrideClear = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; } }; diff --git a/imgui_internal.h b/imgui_internal.h index 16b41d11..3934034b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1086,10 +1086,17 @@ enum ImGuiDockNodeFlagsPrivate_ 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_NoDocking = 1 << 16, // Local, Saved // Disable any form of docking in this dockspace or individual node. (On a whole dockspace, this pretty much defeat the purpose of using a dockspace at all). Note: when turned on, existing docked nodes will be preserved. + ImGuiDockNodeFlags_NoDockingSplitMe = 1 << 17, // [EXPERIMENTAL] Prevent another window/node from splitting this node. + ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 18, // [EXPERIMENTAL] Prevent this node from splitting another window/node. + ImGuiDockNodeFlags_NoDockingOverMe = 1 << 19, // [EXPERIMENTAL] Prevent another window/node to be docked over this node. + ImGuiDockNodeFlags_NoDockingOverOther = 1 << 20, // [EXPERIMENTAL] Prevent this node to be docked over another window/node. + ImGuiDockNodeFlags_NoResizeX = 1 << 21, // [EXPERIMENTAL] + ImGuiDockNodeFlags_NoResizeY = 1 << 22, // [EXPERIMENTAL] ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, - ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking, + ImGuiDockNodeFlags_NoResizeFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, + ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking, ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace, // When splitting those flags are moved to the inheriting child, never duplicated - ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking + ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking }; // Store the source authority (dock node vs window) of a field From 4f5aac319e3561284833db90f35d218de8b282c1 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 Jul 2020 15:51:05 +0200 Subject: [PATCH 127/223] Docking: moved local-ish IMGUI_DOCK_SPLITTER_SIZE to DOCKING_SPLITTER_SIZE at the top of the file. --- imgui.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 08fbff28..7b31979c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -811,6 +811,7 @@ static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock // Docking static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport. +static const float DOCKING_SPLITTER_SIZE = 2.0f; //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS @@ -11602,8 +11603,6 @@ void ImGui::DestroyPlatformWindows() // - ImGuiDockContext //----------------------------------------------------------------------------- -static float IMGUI_DOCK_SPLITTER_SIZE = 2.0f; - enum ImGuiDockRequestType { ImGuiDockRequestType_None = 0, @@ -13697,7 +13696,7 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG parent_node->VisibleWindow = NULL; parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode; - float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE); + float size_avail = (parent_node->Size[split_axis] - DOCKING_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; @@ -13785,7 +13784,7 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si ImVec2 child_0_size = size, child_1_size = size; if (child_0->IsVisible && child_1->IsVisible) { - const float spacing = IMGUI_DOCK_SPLITTER_SIZE; + const float spacing = DOCKING_SPLITTER_SIZE; const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; const float size_avail = ImMax(size[axis] - spacing, 0.0f); From 0d03e1fafafb8d1cebcb6268b3a8014dff08d97c Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Tue, 7 Jul 2020 12:49:25 +0300 Subject: [PATCH 128/223] CI: Fix emscripten builds that broke due behavior change of emscripten SDK. --- .github/workflows/build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8edef47b..b3b910f2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -394,7 +394,9 @@ jobs: - name: Build example_emscripten run: | - source emsdk-master/emsdk_env.sh + pushd emsdk-master + source ./emsdk_env.sh + popd make -C examples/example_emscripten Static-Analysis: From 8e4046e13ba3642de7aa5e2795021c035259f710 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Wed, 8 Jul 2020 17:17:52 +0200 Subject: [PATCH 129/223] Atlas build use GetCustomRectByIndex() + comments, rename, and shallow merge from tex_antialiasing_lines branch. --- imgui.cpp | 4 +- imgui.h | 25 ++++++------ imgui_demo.cpp | 1 + imgui_draw.cpp | 101 +++++++++++++++++++++++++++---------------------- 4 files changed, 72 insertions(+), 59 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d8bf40be..d09d61ed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -934,8 +934,8 @@ ImGuiStyle::ImGuiStyle() DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors 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.) + AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + AntiAliasedFill = true; // Enable anti-aliased 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. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. diff --git a/imgui.h b/imgui.h index 2da0d21a..adb2ab1c 100644 --- a/imgui.h +++ b/imgui.h @@ -151,7 +151,7 @@ typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling 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 ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags @@ -1438,8 +1438,8 @@ struct ImGuiStyle 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.) + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. 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. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. ImVec4 Colors[ImGuiCol_COUNT]; @@ -1994,10 +1994,10 @@ enum ImDrawCornerFlags_ 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 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). + ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; // Draw command list @@ -2211,11 +2211,12 @@ struct ImFontAtlasCustomRect bool IsPacked() const { return X != 0xFFFF; } }; +// Flags for ImFontAtlas build enum ImFontAtlasFlags_ { ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two - ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas + ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas (save a little texture memory) }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2289,7 +2290,7 @@ struct ImFontAtlas // Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. IMGUI_API int AddCustomRectRegular(int width, int height); IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); - const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } + ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; } // [Internal] IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const; @@ -2315,8 +2316,10 @@ struct ImFontAtlas 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 ConfigData; // Internal data - int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList + ImVector ConfigData; // Configuration data + + // [Internal] Packing data + int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ed38e52f..b481c305 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -405,6 +405,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly); ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. 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::Text("Also see Style->Rendering for rendering options."); ImGui::TreePop(); ImGui::Separator(); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ade1290d..30b9b9fe 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -666,11 +666,9 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 return; const ImVec2 opaque_uv = _Data->TexUvWhitePixel; - int count = points_count; - if (!closed) - count = points_count - 1; - + const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw const bool thick_line = (thickness > 1.0f); + if (Flags & ImDrawListFlags_AntiAliasedLines) { // Anti-aliased stroke @@ -682,9 +680,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 PrimReserve(idx_count, vtx_count); // Temporary buffer + // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; + // Calculate normals (tangents) for each line segment for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; @@ -707,12 +707,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; } + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. - unsigned int idx1 = _VtxCurrentIdx; - for (int i1 = 0; i1 < count; i1++) + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; - unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; + const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -721,14 +723,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_x *= AA_SIZE; dm_y *= AA_SIZE; - // Add temporary vertices + // Add temporary vertexes for the outer edges ImVec2* out_vtx = &temp_points[i2 * 2]; out_vtx[0].x = points[i2].x + dm_x; out_vtx[0].y = points[i2].y + dm_y; out_vtx[1].x = points[i2].x - dm_x; out_vtx[1].y = points[i2].y - dm_y; - // Add indexes + // Add indexes for four triangles _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); @@ -738,7 +740,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertices + // Add vertexes for each point on the line for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; @@ -749,7 +751,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { + // Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) { const int points_last = points_count - 1; @@ -763,9 +768,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); } + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. - unsigned int idx1 = _VtxCurrentIdx; - for (int i1 = 0; i1 < count; i1++) + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment @@ -816,7 +823,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { - // Non Anti-aliased Stroke + // Non texture-based, Non anti-aliased lines const int idx_count = count * 6; const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); @@ -1656,8 +1663,7 @@ ImFontAtlas::ImFontAtlas() TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); - for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) - CustomRectIds[n] = -1; + PackIdMouseCursors = -1; } ImFontAtlas::~ImFontAtlas() @@ -1685,8 +1691,7 @@ void ImFontAtlas::ClearInputData() } ConfigData.clear(); CustomRects.clear(); - for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) - CustomRectIds[n] = -1; + PackIdMouseCursors = -1; } void ImFontAtlas::ClearTexData() @@ -1926,9 +1931,9 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou if (Flags & ImFontAtlasFlags_NoMouseCursors) return false; - IM_ASSERT(CustomRectIds[0] != -1); - ImFontAtlasCustomRect& r = CustomRects[CustomRectIds[0]]; - ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y); + IM_ASSERT(PackIdMouseCursors != -1); + ImFontAtlasCustomRect* r = GetCustomRectByIndex(PackIdMouseCursors); + 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]; *out_size = size; *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; @@ -2256,17 +2261,6 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) return true; } -// Register default custom rectangles (this is called/shared by both the stb_truetype and the FreeType builder) -void ImFontAtlasBuildInit(ImFontAtlas* atlas) -{ - if (atlas->CustomRectIds[0] >= 0) - return; - if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - else - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(2, 2); -} - void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) { if (!font_config->MergeMode) @@ -2310,20 +2304,18 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { - IM_ASSERT(atlas->CustomRectIds[0] >= 0); - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; - IM_ASSERT(r.IsPacked()); + ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); + IM_ASSERT(r->IsPacked()); const int w = atlas->TexWidth; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) { // Render/copy pixels - IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); + IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++) for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) { - const int offset0 = (int)(r.X + x) + (int)(r.Y + y) * w; + const int offset0 = (int)(r->X + x) + (int)(r->Y + y) * w; const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00; atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00; @@ -2331,29 +2323,46 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) } else { - IM_ASSERT(r.Width == 2 && r.Height == 2); - const int offset = (int)(r.X) + (int)(r.Y) * w; + // Render 4 white pixels + IM_ASSERT(r->Width == 2 && r->Height == 2); + const int offset = (int)r->X + (int)r->Y * w; atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; } - atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y); + atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } + +// Note: this is called / shared by both the stb_truetype and the FreeType builder +void ImFontAtlasBuildInit(ImFontAtlas* atlas) +{ + // Register texture region for mouse cursors or standard white pixels + if (atlas->PackIdMouseCursors < 0) + { + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + else + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); + } +} + +// This is called/shared by both the stb_truetype and the FreeType builder. void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { - // Render into our custom data block + // Render into our custom data blocks + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) { - const ImFontAtlasCustomRect& r = atlas->CustomRects[i]; - if (r.Font == NULL || r.GlyphID == 0) + const ImFontAtlasCustomRect* r = &atlas->CustomRects[i]; + if (r->Font == NULL || r->GlyphID == 0) continue; - IM_ASSERT(r.Font->ContainerAtlas == atlas); + IM_ASSERT(r->Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&r, &uv0, &uv1); - r.Font->AddGlyph((ImWchar)r.GlyphID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX); + atlas->CalcCustomRectUV(r, &uv0, &uv1); + r->Font->AddGlyph((ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); } // Build all fonts lookup tables From 1d3c3070d8462b6ca2d84e3ca0f05d28896018ec Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Mon, 13 Jan 2020 14:24:55 +0900 Subject: [PATCH 130/223] Texture-based thick lines: Initial version of AA line drawing using textures (press SHIFT to enable) --- imgui.cpp | 6 ++ imgui.h | 10 ++- imgui_demo.cpp | 57 +++++++++++++++++ imgui_draw.cpp | 156 +++++++++++++++++++++++++++++++++++++++-------- imgui_internal.h | 4 ++ 5 files changed, 206 insertions(+), 27 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d09d61ed..34b63566 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,6 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + TexturedAntiAliasedLines= true; // Draw anti-aliased lines using textures where possible. AntiAliasedFill = true; // Enable anti-aliased 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. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3688,10 +3689,14 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; + if (g.Style.TexturedAntiAliasedLines) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; + if ((g.Style.TexturedAntiAliasedLines) && (!(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; g.BackgroundDrawList._ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); @@ -6158,6 +6163,7 @@ void ImGui::SetCurrentFont(ImFont* font) ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; + g.DrawListSharedData.TexUvAALines = &atlas->TexUvAALines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } diff --git a/imgui.h b/imgui.h index adb2ab1c..09d92309 100644 --- a/imgui.h +++ b/imgui.h @@ -1439,6 +1439,7 @@ struct ImGuiStyle 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-aliased lines/borders. Disable if you are really tight on CPU/GPU. + bool TexturedAntiAliasedLines; // Draw anti-aliased lines using textures where possible. bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. 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. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1997,7 +1998,8 @@ enum ImDrawListFlags_ ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. + ImDrawListFlags_AllowVtxOffset = 1 << 2, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. + ImDrawListFlags_TexturedAALines = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? }; // Draw command list @@ -2216,7 +2218,8 @@ enum ImFontAtlasFlags_ { ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two - ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoAALines = 1 << 2 // Don't build anti-aliased line textures into the atlas }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2320,6 +2323,9 @@ struct ImFontAtlas // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors + int AALineMaxWidth; // Maximum line width to build anti-aliased textures for + ImVector AALineRectIds; // Custom texture rectangle IDs for anti-aliased lines + ImVector TexUvAALines; // UVs for anti-aliased line textures #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b481c305..f06d8526 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -297,6 +297,62 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); + // Test lines + + if (ImGui::Begin("Lines")) + { + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + const int num_cols = 16; + const int num_rows = 3; + const float line_len = 64.0f; + const float line_spacing = 128.0f; + + static float base_rot = 0.0f; + ImGui::SliderFloat("Base rotation", &base_rot, 0.0f, 360.0f); + static float line_width = 1.0f; + ImGui::SliderFloat("Line width", &line_width, 1.0f, 10.0f); + + ImVec2 window_pos = ImGui::GetWindowPos(); + ImVec2 cursor_pos = ImGui::GetCursorPos(); + ImVec2 base_pos(window_pos.x + cursor_pos.x + (line_spacing * 0.5f), window_pos.y + cursor_pos.y); + + for (int i = 0; i < num_rows; i++) + { + const char* name = ""; + switch (i) + { + case 0: name = "No AA"; draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; break; + case 1: name = "AA no texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags &= ~ImDrawListFlags_TexturedAALines; break; + case 2: name = "AA with texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags |= ImDrawListFlags_TexturedAALines; break; + } + + int initial_vtx_count = draw_list->VtxBuffer.Size; + int initial_idx_count = draw_list->IdxBuffer.Size; + + for (int j = 0; j < num_cols; j++) + { + const float pi = 3.14159265359f; + float r = (base_rot * pi / 180.0f) + ((j * pi * 0.5f) / (num_cols - 1)); + + ImVec2 center = ImVec2(base_pos.x + (line_spacing * (j * 0.5f)), base_pos.y + (line_spacing * (i + 0.5f))); + ImVec2 start = ImVec2(center.x + (sinf(r) * line_len * 0.5f), center.y + (cosf(r) * line_len * 0.5f)); + ImVec2 end = ImVec2(center.x - (sinf(r) * line_len * 0.5f), center.y - (cosf(r) * line_len * 0.5f)); + + draw_list->AddLine(start, end, IM_COL32(255, 255, 255, 255), line_width); + } + + ImGui::SetCursorPosY(cursor_pos.y + (i * line_spacing)); + ImGui::Text("%s - %d vertices, %d indices", name, draw_list->VtxBuffer.Size - initial_vtx_count, draw_list->IdxBuffer.Size - initial_idx_count); + } + + ImGui::SetCursorPosY(cursor_pos.y + (num_rows * line_spacing)); + + //ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); + //ImGui::Image(ImGui::GetFont()->ContainerAtlas->TexID, ImVec2((float)ImGui::GetFont()->ContainerAtlas->TexWidth, (float)ImGui::GetFont()->ContainerAtlas->TexHeight)); + } + ImGui::End(); + // Main body of the Demo window starts here. if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags)) { @@ -3831,6 +3887,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { 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("Use textures for anti-aliased lines", &style.TexturedAntiAliasedLines); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 30b9b9fe..7c845f94 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -667,6 +667,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const ImVec2 opaque_uv = _Data->TexUvWhitePixel; const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw + const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) @@ -675,13 +676,24 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int idx_count = thick_line ? count * 18 : count * 12; - const int vtx_count = thick_line ? points_count * 4 : points_count * 3; + const int integer_thickness = (int)thickness; + + // Do we want to draw this line using a texture? + bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && + (integer_thickness >= 1) && + (integer_thickness <= _Data->Font->ContainerAtlas->AALineMaxWidth) && + ImGui::GetIO().KeyShift; // FIXME-AALINES: Remove this debug code + + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_TexturedAALines unless ImFontAtlasFlags_NoAALines is off + IM_ASSERT_PARANOID((!use_textures) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); + + const int idx_count = use_textures ? (count * 6) : (thick_line ? count * 18 : count * 12); + const int vtx_count = use_textures ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); PrimReserve(idx_count, vtx_count); // Temporary buffer // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point - ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630 + ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_textures) ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; // Calculate normals (tangents) for each line segment @@ -697,14 +709,19 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (!closed) temp_normals[points_count - 1] = temp_normals[points_count - 2]; - if (!thick_line) + // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point + if ((!thick_line) || (use_textures)) { + // The width of the geometry we need to draw + const float half_draw_size = (!thick_line) ? AA_SIZE : (AA_SIZE + (thickness * 0.5f)); + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) { - temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; - temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; - temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; - temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; + temp_points[0] = points[0] + temp_normals[0] * half_draw_size; + temp_points[1] = points[0] - temp_normals[0] * half_draw_size; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size; } // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges @@ -713,15 +730,15 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { - const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; - const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment + unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_textures ? 2 : 3)); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; IM_FIXNORMAL2F(dm_x, dm_y); - dm_x *= AA_SIZE; - dm_y *= AA_SIZE; + dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area + dm_y *= half_draw_size; // Add temporary vertexes for the outer edges ImVec2* out_vtx = &temp_points[i2 * 2]; @@ -730,28 +747,54 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 out_vtx[1].x = points[i2].x - dm_x; out_vtx[1].y = points[i2].y - dm_y; - // Add indexes for four triangles - _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); - _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); - _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); - _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); - _IdxWritePtr += 12; + if (use_textures) + { + // Add indices for two triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri + _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri + _IdxWritePtr += 6; + } + else + { + // Add indexes for four triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1 + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2 + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1 + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2 + _IdxWritePtr += 12; + } idx1 = idx2; } // Add vertexes for each point on the line - for (int i = 0; i < points_count; i++) + if (use_textures) + { + // If we're using textures we only need to emit the left/right edge vertices + const ImVec4 tex_uvs = (*_Data->TexUvAALines)[integer_thickness - 1]; + + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = ImVec2(tex_uvs.x, tex_uvs.y); _VtxWritePtr[0].col = col; // Left-side outer edge + _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = ImVec2(tex_uvs.z, tex_uvs.y); _VtxWritePtr[1].col = col; // Right-side outer edge + _VtxWritePtr += 2; + } + } + else { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; - _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; - _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; - _VtxWritePtr += 3; + // If we're not using a texture, we need the centre vertex as well + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Centre of line + _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge + _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge + _VtxWritePtr += 3; + } } } else { - // Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point + // For untextured lines that are greater than a pixel in width, we need to draw the solid line core and thus require four vertices per point const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend @@ -1664,6 +1707,8 @@ ImFontAtlas::ImFontAtlas() TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); PackIdMouseCursors = -1; + + AALineMaxWidth = 8; } ImFontAtlas::~ImFontAtlas() @@ -2010,6 +2055,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) IM_ASSERT(atlas->ConfigData.Size > 0); ImFontAtlasBuildInit(atlas); + ImFontAtlasBuildRegisterAALineCustomRects(atlas); // Clear atlas atlas->TexID = (ImTextureID)NULL; @@ -2331,7 +2377,6 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } - // Note: this is called / shared by both the stb_truetype and the FreeType builder void ImFontAtlasBuildInit(ImFontAtlas* atlas) { @@ -2346,12 +2391,73 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) } // This is called/shared by both the stb_truetype and the FreeType builder. +const unsigned int FONT_ATLAS_AA_LINE_TEX_HEIGHT = 1; // Technically we only need 1 pixel in the ideal case but this can be increased if necessary to give a border to avoid sampling artifacts + +void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) +{ + if (atlas->AALineRectIds.size() > 0) + return; + + if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) + return; + + const int max = atlas->AALineMaxWidth; + + for (int n = 0; n < max; n++) + { + const int width = n + 1; // The line width this entry corresponds to + // The "width + 3" here is interesting - +2 is to give space for the end caps, but the remaining +1 is because (empirically) to match the behaviour of the untextured render path we need to draw lines one pixel wider + atlas->AALineRectIds.push_back(atlas->AddCustomRectRegular(width + 3, FONT_ATLAS_AA_LINE_TEX_HEIGHT)); + } +} + +void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) +{ + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); + IM_ASSERT(atlas->TexUvAALines.size() == 0); + + if (atlas->Flags & ImFontAtlasFlags_NoAALines) + return; + + const int w = atlas->TexWidth; + const unsigned int max = atlas->AALineMaxWidth; + + for (unsigned int n = 0; n < max; n++) + { + IM_ASSERT(atlas->AALineRectIds.size() > (int)n); + ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; + IM_ASSERT(r.IsPacked()); + + // We fill as many lines as we were given, to allow for >1 lines being used to work around sampling weirdness + for (unsigned int y = 0; y < r.Height; y++) + { + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + + // Each line consists of two empty pixels at the ends, with a line of solid pixels in the middle + *(write_ptr++) = 0; + for (unsigned short x = 0; x < (r.Width - 2U); x++) + { + *(write_ptr++) = 0xFF; + } + *(write_ptr++) = 0; + } + + ImVec2 uv0, uv1; + atlas->CalcCustomRectUV(&r, &uv0, &uv1); + float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the texture as we want a horizontal slice (with some padding either side to avoid sampling artifacts) + atlas->TexUvAALines.push_back(ImVec4(uv0.x, halfV, uv1.x, halfV)); + } +} + void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data blocks IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); + // Render anti-aliased line textures + ImFontAtlasBuildAALinesTexData(atlas); + // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) { diff --git a/imgui_internal.h b/imgui_internal.h index b57b01b5..2035f324 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -545,6 +545,8 @@ struct IMGUI_API ImDrawListSharedData ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) + ImVector* TexUvAALines; // UV of anti-aliased lines in the atlas + ImDrawListSharedData(); void SetCircleSegmentMaxError(float max_error); }; @@ -2018,8 +2020,10 @@ namespace ImGui // ImFontAtlas internals IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); +IMGUI_API void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas); 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); From 741ab74b5575f0b4b5db82db549f07fda130d244 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Wed, 15 Jan 2020 16:33:09 +0900 Subject: [PATCH 131/223] Texture-based thick lines: Improvements to code for drawing anti-aliased lines using textures Moved line width into a constant Removed test code (now in imgui-tests) Improved matching between geometry and texture rendering at non-integer sizes --- imgui.h | 1 - imgui_demo.cpp | 56 ------------------------------------------------ imgui_draw.cpp | 14 +++++------- imgui_internal.h | 3 +++ 4 files changed, 8 insertions(+), 66 deletions(-) diff --git a/imgui.h b/imgui.h index 09d92309..cc4be5e0 100644 --- a/imgui.h +++ b/imgui.h @@ -2323,7 +2323,6 @@ struct ImFontAtlas // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int AALineMaxWidth; // Maximum line width to build anti-aliased textures for ImVector AALineRectIds; // Custom texture rectangle IDs for anti-aliased lines ImVector TexUvAALines; // UVs for anti-aliased line textures diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f06d8526..2afa7a4f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -297,62 +297,6 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); - // Test lines - - if (ImGui::Begin("Lines")) - { - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - - const int num_cols = 16; - const int num_rows = 3; - const float line_len = 64.0f; - const float line_spacing = 128.0f; - - static float base_rot = 0.0f; - ImGui::SliderFloat("Base rotation", &base_rot, 0.0f, 360.0f); - static float line_width = 1.0f; - ImGui::SliderFloat("Line width", &line_width, 1.0f, 10.0f); - - ImVec2 window_pos = ImGui::GetWindowPos(); - ImVec2 cursor_pos = ImGui::GetCursorPos(); - ImVec2 base_pos(window_pos.x + cursor_pos.x + (line_spacing * 0.5f), window_pos.y + cursor_pos.y); - - for (int i = 0; i < num_rows; i++) - { - const char* name = ""; - switch (i) - { - case 0: name = "No AA"; draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; break; - case 1: name = "AA no texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags &= ~ImDrawListFlags_TexturedAALines; break; - case 2: name = "AA with texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags |= ImDrawListFlags_TexturedAALines; break; - } - - int initial_vtx_count = draw_list->VtxBuffer.Size; - int initial_idx_count = draw_list->IdxBuffer.Size; - - for (int j = 0; j < num_cols; j++) - { - const float pi = 3.14159265359f; - float r = (base_rot * pi / 180.0f) + ((j * pi * 0.5f) / (num_cols - 1)); - - ImVec2 center = ImVec2(base_pos.x + (line_spacing * (j * 0.5f)), base_pos.y + (line_spacing * (i + 0.5f))); - ImVec2 start = ImVec2(center.x + (sinf(r) * line_len * 0.5f), center.y + (cosf(r) * line_len * 0.5f)); - ImVec2 end = ImVec2(center.x - (sinf(r) * line_len * 0.5f), center.y - (cosf(r) * line_len * 0.5f)); - - draw_list->AddLine(start, end, IM_COL32(255, 255, 255, 255), line_width); - } - - ImGui::SetCursorPosY(cursor_pos.y + (i * line_spacing)); - ImGui::Text("%s - %d vertices, %d indices", name, draw_list->VtxBuffer.Size - initial_vtx_count, draw_list->IdxBuffer.Size - initial_idx_count); - } - - ImGui::SetCursorPosY(cursor_pos.y + (num_rows * line_spacing)); - - //ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); - //ImGui::Image(ImGui::GetFont()->ContainerAtlas->TexID, ImVec2((float)ImGui::GetFont()->ContainerAtlas->TexWidth, (float)ImGui::GetFont()->ContainerAtlas->TexHeight)); - } - ImGui::End(); - // Main body of the Demo window starts here. if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags)) { diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7c845f94..72ccb963 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -676,13 +676,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int integer_thickness = (int)thickness; + // The -0.5f here is to better match the geometry-based code, and also shift the transition point from one width texture to another off the integer values (where it will be less noticeable) + const int integer_thickness = ImMax((int)(thickness - 0.5f), 1); // Do we want to draw this line using a texture? - bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && - (integer_thickness >= 1) && - (integer_thickness <= _Data->Font->ContainerAtlas->AALineMaxWidth) && - ImGui::GetIO().KeyShift; // FIXME-AALINES: Remove this debug code + bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_TexturedAALines unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_textures) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); @@ -1707,8 +1705,6 @@ ImFontAtlas::ImFontAtlas() TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); PackIdMouseCursors = -1; - - AALineMaxWidth = 8; } ImFontAtlas::~ImFontAtlas() @@ -2401,7 +2397,7 @@ void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - const int max = atlas->AALineMaxWidth; + const int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; for (int n = 0; n < max; n++) { @@ -2420,7 +2416,7 @@ void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) return; const int w = atlas->TexWidth; - const unsigned int max = atlas->AALineMaxWidth; + const unsigned int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; for (unsigned int n = 0; n < max; n++) { diff --git a/imgui_internal.h b/imgui_internal.h index 2035f324..643aea4d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -529,6 +529,9 @@ struct IMGUI_API ImChunkStream #define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 #endif +// The maximum line width to build anti-aliased textures for +#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX 65 + // Data shared between all ImDrawList instances // You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. struct IMGUI_API ImDrawListSharedData From 222b7ddbfa16635905772faed268e33501ee22ae Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jan 2020 15:23:23 +0100 Subject: [PATCH 132/223] Texture-based thick lines: Tweaks, fix for truetype builder. --- imgui.cpp | 8 ++--- imgui.h | 4 +-- imgui_demo.cpp | 3 +- imgui_draw.cpp | 84 ++++++++++++++++++++++-------------------------- imgui_internal.h | 2 -- 5 files changed, 46 insertions(+), 55 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 34b63566..e6fe1184 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,7 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - TexturedAntiAliasedLines= true; // Draw anti-aliased lines using textures where possible. + AntiAliasedLinesUseTexData = true; // Draw anti-aliased lines using textures where possible. AntiAliasedFill = true; // Enable anti-aliased 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. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3689,14 +3689,12 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; - if (g.Style.TexturedAntiAliasedLines) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; + if (g.Style.AntiAliasedLinesUseTexData && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTexData; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; - if ((g.Style.TexturedAntiAliasedLines) && (!(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; g.BackgroundDrawList._ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); diff --git a/imgui.h b/imgui.h index cc4be5e0..f361102c 100644 --- a/imgui.h +++ b/imgui.h @@ -1439,7 +1439,7 @@ struct ImGuiStyle 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-aliased lines/borders. Disable if you are really tight on CPU/GPU. - bool TexturedAntiAliasedLines; // Draw anti-aliased lines using textures where possible. + bool AntiAliasedLinesUseTexData; // Draw anti-aliased lines using textures where possible. bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. 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. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1999,7 +1999,7 @@ enum ImDrawListFlags_ ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1 << 2, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. - ImDrawListFlags_TexturedAALines = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AntiAliasedLinesUseTexData = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? }; // Draw command list diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2afa7a4f..e90fd517 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3831,7 +3831,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { 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("Use textures for anti-aliased lines", &style.TexturedAntiAliasedLines); + ImGui::Checkbox("Anti-aliased lines use texture data", &style.AntiAliasedLinesUseTexData); + ImGui::SameLine(); HelpMarker("Faster lines using texture data. Requires texture to use bilinear sampling (not nearest)."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 72ccb963..41d25955 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -358,6 +358,7 @@ ImDrawListSharedData::ImDrawListSharedData() ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } memset(CircleSegmentCounts, 0, sizeof(CircleSegmentCounts)); // This will be set by SetCircleSegmentMaxError() + TexUvAALines = NULL; } void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) @@ -680,18 +681,18 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const int integer_thickness = ImMax((int)(thickness - 0.5f), 1); // Do we want to draw this line using a texture? - bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); - // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_TexturedAALines unless ImFontAtlasFlags_NoAALines is off - IM_ASSERT_PARANOID((!use_textures) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off + IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); - const int idx_count = use_textures ? (count * 6) : (thick_line ? count * 18 : count * 12); - const int vtx_count = use_textures ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); + const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); + const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); PrimReserve(idx_count, vtx_count); // Temporary buffer // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point - ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_textures) ? 5 : 3) * sizeof(ImVec2)); //-V630 + ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_texture) ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; // Calculate normals (tangents) for each line segment @@ -708,7 +709,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_normals[points_count - 1] = temp_normals[points_count - 2]; // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point - if ((!thick_line) || (use_textures)) + if (!thick_line || use_texture) { // The width of the geometry we need to draw const float half_draw_size = (!thick_line) ? AA_SIZE : (AA_SIZE + (thickness * 0.5f)); @@ -729,7 +730,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment - unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_textures ? 2 : 3)); // Vertex index for end of segment + unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -745,7 +746,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 out_vtx[1].x = points[i2].x - dm_x; out_vtx[1].y = points[i2].y - dm_y; - if (use_textures) + if (use_texture) { // Add indices for two triangles _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri @@ -766,7 +767,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } // Add vertexes for each point on the line - if (use_textures) + if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices const ImVec4 tex_uvs = (*_Data->TexUvAALines)[integer_thickness - 1]; @@ -2051,7 +2052,6 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) IM_ASSERT(atlas->ConfigData.Size > 0); ImFontAtlasBuildInit(atlas); - ImFontAtlasBuildRegisterAALineCustomRects(atlas); // Clear atlas atlas->TexID = (ImTextureID)NULL; @@ -2373,68 +2373,49 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } -// Note: this is called / shared by both the stb_truetype and the FreeType builder -void ImFontAtlasBuildInit(ImFontAtlas* atlas) -{ - // Register texture region for mouse cursors or standard white pixels - if (atlas->PackIdMouseCursors < 0) - { - if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - else - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); - } -} - // This is called/shared by both the stb_truetype and the FreeType builder. const unsigned int FONT_ATLAS_AA_LINE_TEX_HEIGHT = 1; // Technically we only need 1 pixel in the ideal case but this can be increased if necessary to give a border to avoid sampling artifacts -void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) +static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) { - if (atlas->AALineRectIds.size() > 0) + if (atlas->AALineRectIds.Size > 0) return; if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - const int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; - - for (int n = 0; n < max; n++) + for (int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) { + // The "width + 3" here is interesting. +2 is to give space for the end caps, but the remaining +1 is + // because (empirically) to match the behavior of the untextured render path we need to draw lines one pixel wider. const int width = n + 1; // The line width this entry corresponds to - // The "width + 3" here is interesting - +2 is to give space for the end caps, but the remaining +1 is because (empirically) to match the behaviour of the untextured render path we need to draw lines one pixel wider atlas->AALineRectIds.push_back(atlas->AddCustomRectRegular(width + 3, FONT_ATLAS_AA_LINE_TEX_HEIGHT)); } } -void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) +static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - IM_ASSERT(atlas->TexUvAALines.size() == 0); + IM_ASSERT(atlas->TexUvAALines.Size == 0); if (atlas->Flags & ImFontAtlasFlags_NoAALines) return; const int w = atlas->TexWidth; - const unsigned int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; - - for (unsigned int n = 0; n < max; n++) + for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) { - IM_ASSERT(atlas->AALineRectIds.size() > (int)n); - ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; + IM_ASSERT(atlas->AALineRectIds.Size > (int)n); + ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; IM_ASSERT(r.IsPacked()); // We fill as many lines as we were given, to allow for >1 lines being used to work around sampling weirdness for (unsigned int y = 0; y < r.Height; y++) { - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; - // Each line consists of two empty pixels at the ends, with a line of solid pixels in the middle + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; *(write_ptr++) = 0; for (unsigned short x = 0; x < (r.Width - 2U); x++) - { *(write_ptr++) = 0xFF; - } *(write_ptr++) = 0; } @@ -2445,14 +2426,27 @@ void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) } } +// Note: this is called / shared by both the stb_truetype and the FreeType builder +void ImFontAtlasBuildInit(ImFontAtlas* atlas) +{ + // Register texture region for mouse cursors or standard white pixels + if (atlas->PackIdMouseCursors < 0) + { + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + else + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); + } + + ImFontAtlasBuildRegisterAALineCustomRects(atlas); +} + +// This is called/shared by both the stb_truetype and the FreeType builder. void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data blocks - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); - - // Render anti-aliased line textures - ImFontAtlasBuildAALinesTexData(atlas); + ImFontAtlasBuildRenderAALinesTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) diff --git a/imgui_internal.h b/imgui_internal.h index 643aea4d..d38d9b78 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2023,10 +2023,8 @@ namespace ImGui // ImFontAtlas internals IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); -IMGUI_API void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas); 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); From 403bf45245901031e112f8de4828cdd8c7eee805 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Thu, 6 Feb 2020 14:30:29 +0900 Subject: [PATCH 133/223] Texture-based thick lines: Allow interpolation between textures for non-integer line widths --- imgui.h | 2 +- imgui_draw.cpp | 84 +++++++++++++++++++++++++++++------------------- imgui_internal.h | 2 +- 3 files changed, 53 insertions(+), 35 deletions(-) diff --git a/imgui.h b/imgui.h index f361102c..47f15fb1 100644 --- a/imgui.h +++ b/imgui.h @@ -2323,7 +2323,7 @@ struct ImFontAtlas // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - ImVector AALineRectIds; // Custom texture rectangle IDs for anti-aliased lines + int AALineRectId; // Custom texture rectangle ID for anti-aliased lines ImVector TexUvAALines; // UVs for anti-aliased line textures #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 41d25955..376d4141 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -677,11 +677,12 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - // The -0.5f here is to better match the geometry-based code, and also shift the transition point from one width texture to another off the integer values (where it will be less noticeable) - const int integer_thickness = ImMax((int)(thickness - 0.5f), 1); + // The thick_line test is an attempt to compensate for the way half_draw_size gets calculated later, which special-cases 1.0f width lines + const int integer_thickness = thick_line ? ImMax((int)(thickness), 1) : 2; + const float fractional_thickness = thick_line ? (thickness) - integer_thickness : 0.0f; // Do we want to draw this line using a texture? - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); @@ -711,8 +712,9 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point if (!thick_line || use_texture) { - // The width of the geometry we need to draw - const float half_draw_size = (!thick_line) ? AA_SIZE : (AA_SIZE + (thickness * 0.5f)); + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA + // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code + const float half_draw_size = (thickness * 0.5f) + 1; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) @@ -770,7 +772,18 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices - const ImVec4 tex_uvs = (*_Data->TexUvAALines)[integer_thickness - 1]; + + ImVec4 tex_uvs; + + if (fractional_thickness == 0.0f) // Fast path for pure integer widths + tex_uvs = (*_Data->TexUvAALines)[integer_thickness]; + else + { + // Calculate UV by interpolating between the two nearest integer line widths + const ImVec4 tex_uvs_0 = (*_Data->TexUvAALines)[integer_thickness]; + const ImVec4 tex_uvs_1 = (*_Data->TexUvAALines)[integer_thickness + 1]; + tex_uvs = ImLerp(tex_uvs_0, tex_uvs_1, fractional_thickness); + } for (int i = 0; i < points_count; i++) { @@ -2373,24 +2386,14 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } -// This is called/shared by both the stb_truetype and the FreeType builder. -const unsigned int FONT_ATLAS_AA_LINE_TEX_HEIGHT = 1; // Technically we only need 1 pixel in the ideal case but this can be increased if necessary to give a border to avoid sampling artifacts - static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) { - if (atlas->AALineRectIds.Size > 0) - return; - if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - for (int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) - { - // The "width + 3" here is interesting. +2 is to give space for the end caps, but the remaining +1 is - // because (empirically) to match the behavior of the untextured render path we need to draw lines one pixel wider. - const int width = n + 1; // The line width this entry corresponds to - atlas->AALineRectIds.push_back(atlas->AddCustomRectRegular(width + 3, FONT_ATLAS_AA_LINE_TEX_HEIGHT)); - } + const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate + // The "max_width + 2" here is to give space for the end caps, whilst height (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX+1) is to accommodate the fact we have a zero-width row + atlas->AALineRectId = atlas->AddCustomRectRegular(max_width + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); } static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) @@ -2401,27 +2404,42 @@ static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) if (atlas->Flags & ImFontAtlasFlags_NoAALines) return; + ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectId]; + IM_ASSERT(r.IsPacked()); + + // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them const int w = atlas->TexWidth; - for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) + for (unsigned int n = 0; n < (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); n++) // +1 because of the zero-width row { - IM_ASSERT(atlas->AALineRectIds.Size > (int)n); - ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; - IM_ASSERT(r.IsPacked()); + unsigned int y = n; + unsigned int line_width = n; + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + unsigned int pad_left = (r.Width - line_width) / 2; + unsigned int pad_right = r.Width - (pad_left + line_width); - // We fill as many lines as we were given, to allow for >1 lines being used to work around sampling weirdness - for (unsigned int y = 0; y < r.Height; y++) - { - // Each line consists of two empty pixels at the ends, with a line of solid pixels in the middle - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + // Make sure we're inside the texture bounds before we start writing pixels + IM_ASSERT_PARANOID(pad_left + line_width + pad_right == r.Width); + IM_ASSERT_PARANOID(y < r.Height); + + // Write each slice + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + for (unsigned int x = 0; x < pad_left; x++) *(write_ptr++) = 0; - for (unsigned short x = 0; x < (r.Width - 2U); x++) - *(write_ptr++) = 0xFF; + for (unsigned int x = 0; x < line_width; x++) + *(write_ptr++) = 0xFF; + for (unsigned int x = 0; x < pad_right; x++) *(write_ptr++) = 0; - } + + // Calculate UVs for this line + ImFontAtlasCustomRect line_rect = r; + line_rect.X += (unsigned short)(pad_left - 1); + line_rect.Width = (unsigned short)(line_width + 2); + line_rect.Y += (unsigned short)y; + line_rect.Height = 1; ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&r, &uv0, &uv1); - float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the texture as we want a horizontal slice (with some padding either side to avoid sampling artifacts) + atlas->CalcCustomRectUV(&line_rect, &uv0, &uv1); + float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvAALines.push_back(ImVec4(uv0.x, halfV, uv1.x, halfV)); } } diff --git a/imgui_internal.h b/imgui_internal.h index d38d9b78..4f3882c9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -529,7 +529,7 @@ struct IMGUI_API ImChunkStream #define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 #endif -// The maximum line width to build anti-aliased textures for +// The maximum line width to build anti-aliased textures for (note that this needs to be one greater than the maximum line width you want to be able to draw using the textured path) #define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX 65 // Data shared between all ImDrawList instances From 21d9e8e1f44b52a1f12eb04f650db99d7c34ac8a Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Tue, 11 Feb 2020 11:23:43 +0900 Subject: [PATCH 134/223] Texture-based thick lines: Simplified line width calculation code and removed hack for thickness 1.0 lines --- imgui_draw.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 376d4141..18ca4bd8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -677,9 +677,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - // The thick_line test is an attempt to compensate for the way half_draw_size gets calculated later, which special-cases 1.0f width lines - const int integer_thickness = thick_line ? ImMax((int)(thickness), 1) : 2; - const float fractional_thickness = thick_line ? (thickness) - integer_thickness : 0.0f; + // Thicknesses <1.0 should behave like thickness 1.0 + thickness = ImMax(thickness, 1.0f); + + const int integer_thickness = (int)thickness ; + const float fractional_thickness = (thickness) - integer_thickness; // Do we want to draw this line using a texture? const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); @@ -714,7 +716,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 { // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code - const float half_draw_size = (thickness * 0.5f) + 1; + const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : 1.0f; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) From a07c8b69991af2988fce91fabab975ffcb976a41 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 17 Feb 2020 11:58:22 +0100 Subject: [PATCH 135/223] Texture-based thick lines: Fixes for AddCustomRect api, add IMGUI_HAS_TEXLINES define (temporarily) to facilitate working with test cases, Demo allows growing FrameBorderSize for testing --- imgui.h | 2 ++ imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 47f15fb1..e5e54290 100644 --- a/imgui.h +++ b/imgui.h @@ -1993,6 +1993,8 @@ enum ImDrawCornerFlags_ ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience }; +#define IMGUI_HAS_TEXLINES 1 + enum ImDrawListFlags_ { ImDrawListFlags_None = 0, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e90fd517..f599e034 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3698,7 +3698,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); + ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 4.0f, "%.1f"); ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::Text("Rounding"); ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 18ca4bd8..a4f68f9d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2393,8 +2393,8 @@ static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate // The "max_width + 2" here is to give space for the end caps, whilst height (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX+1) is to accommodate the fact we have a zero-width row + const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate atlas->AALineRectId = atlas->AddCustomRectRegular(max_width + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); } From 78d6bdf08036fdeea08ee9e6a0191f058f89dca0 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 May 2020 16:55:05 +0200 Subject: [PATCH 136/223] Texture-based thick lines: Remove unnecessary indirection in fetching UV data, removed lerp call, renames, tweaks. --- imgui.cpp | 8 ++--- imgui.h | 17 ++++++---- imgui_demo.cpp | 4 +-- imgui_draw.cpp | 84 +++++++++++++++++++++++------------------------- imgui_internal.h | 5 +-- 5 files changed, 58 insertions(+), 60 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e6fe1184..b9c300fa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,7 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - AntiAliasedLinesUseTexData = true; // Draw anti-aliased lines using textures where possible. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. AntiAliasedFill = true; // Enable anti-aliased 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. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3689,8 +3689,8 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; - if (g.Style.AntiAliasedLinesUseTexData && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines)) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTexData; + if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) @@ -6161,7 +6161,7 @@ void ImGui::SetCurrentFont(ImFont* font) ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; - g.DrawListSharedData.TexUvAALines = &atlas->TexUvAALines; + g.DrawListSharedData.TexUvAALines = atlas->TexUvAALines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } diff --git a/imgui.h b/imgui.h index e5e54290..5e86bae5 100644 --- a/imgui.h +++ b/imgui.h @@ -1439,7 +1439,7 @@ struct ImGuiStyle 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-aliased lines/borders. Disable if you are really tight on CPU/GPU. - bool AntiAliasedLinesUseTexData; // Draw anti-aliased lines using textures where possible. + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. 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. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1897,6 +1897,11 @@ struct ImColor // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoAALines to disable baking. +#ifndef IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX (63) +#endif + // ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] // 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: @@ -2000,8 +2005,8 @@ enum ImDrawListFlags_ ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AllowVtxOffset = 1 << 2, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. - ImDrawListFlags_AntiAliasedLinesUseTexData = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 2, // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; // Draw command list @@ -2221,7 +2226,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoAALines = 1 << 2 // Don't build anti-aliased line textures into the atlas + ImFontAtlasFlags_NoAntiAliasedLines = 1 << 2 // Don't build anti-aliased line textures into the atlas (save a little texture memory). They will be rendered using polygons (a little bit more expensive) }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2322,11 +2327,11 @@ struct ImFontAtlas ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector ConfigData; // Configuration data + ImVec4 TexUvAALines[IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1]; // UVs for anti-aliased line textures // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int AALineRectId; // Custom texture rectangle ID for anti-aliased lines - ImVector TexUvAALines; // UVs for anti-aliased line textures + int PackIdAALines; // Custom texture rectangle ID for anti-aliased lines #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f599e034..8b5d57d4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3698,7 +3698,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f"); - ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 4.0f, "%.1f"); + 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, 12.0f, "%.0f"); @@ -3831,7 +3831,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { 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 lines use texture data", &style.AntiAliasedLinesUseTexData); + ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); ImGui::SameLine(); HelpMarker("Faster lines using texture data. Requires texture to use bilinear sampling (not nearest)."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a4f68f9d..24e8a654 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -668,7 +668,6 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const ImVec2 opaque_uv = _Data->TexUvWhitePixel; const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw - const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) @@ -679,12 +678,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Thicknesses <1.0 should behave like thickness 1.0 thickness = ImMax(thickness, 1.0f); - - const int integer_thickness = (int)thickness ; - const float fractional_thickness = (thickness) - integer_thickness; + const int integer_thickness = (int)thickness; + const float fractional_thickness = thickness - integer_thickness; // Do we want to draw this line using a texture? - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); @@ -712,8 +710,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_normals[points_count - 1] = temp_normals[points_count - 2]; // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point - if (!thick_line || use_texture) + if (use_texture || !thick_line) { + // [PATH 1] Texture-based lines (thick or non-thick) + // [PATH 2] Non texture-based lines (non-thick) + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : 1.0f; @@ -734,7 +735,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment - unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment + const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -774,32 +775,30 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices - - ImVec4 tex_uvs; - - if (fractional_thickness == 0.0f) // Fast path for pure integer widths - tex_uvs = (*_Data->TexUvAALines)[integer_thickness]; - else + ImVec4 tex_uvs = _Data->TexUvAALines[integer_thickness]; + if (fractional_thickness != 0.0f) { - // Calculate UV by interpolating between the two nearest integer line widths - const ImVec4 tex_uvs_0 = (*_Data->TexUvAALines)[integer_thickness]; - const ImVec4 tex_uvs_1 = (*_Data->TexUvAALines)[integer_thickness + 1]; - tex_uvs = ImLerp(tex_uvs_0, tex_uvs_1, fractional_thickness); + const ImVec4 tex_uvs_1 = _Data->TexUvAALines[integer_thickness + 1]; + tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() + tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; + tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; + tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; } - + ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y); + ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w); for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = ImVec2(tex_uvs.x, tex_uvs.y); _VtxWritePtr[0].col = col; // Left-side outer edge - _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = ImVec2(tex_uvs.z, tex_uvs.y); _VtxWritePtr[1].col = col; // Right-side outer edge + _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge + _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge _VtxWritePtr += 2; } } else { - // If we're not using a texture, we need the centre vertex as well + // If we're not using a texture, we need the center vertex as well for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Centre of line + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Center of line _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge _VtxWritePtr += 3; @@ -808,7 +807,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { - // For untextured lines that are greater than a pixel in width, we need to draw the solid line core and thus require four vertices per point + // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend @@ -880,7 +879,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { - // Non texture-based, Non anti-aliased lines + // [PATH 4] Non texture-based, Non anti-aliased lines const int idx_count = count * 6; const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); @@ -1720,7 +1719,7 @@ ImFontAtlas::ImFontAtlas() TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); - PackIdMouseCursors = -1; + PackIdMouseCursors = PackIdAALines = -1; } ImFontAtlas::~ImFontAtlas() @@ -1748,7 +1747,7 @@ void ImFontAtlas::ClearInputData() } ConfigData.clear(); CustomRects.clear(); - PackIdMouseCursors = -1; + PackIdMouseCursors = PackIdAALines = -1; } void ImFontAtlas::ClearTexData() @@ -2390,41 +2389,38 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) { - if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) + if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) return; - // The "max_width + 2" here is to give space for the end caps, whilst height (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX+1) is to accommodate the fact we have a zero-width row - const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate - atlas->AALineRectId = atlas->AddCustomRectRegular(max_width + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row + atlas->PackIdAALines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); } static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - IM_ASSERT(atlas->TexUvAALines.Size == 0); - - if (atlas->Flags & ImFontAtlasFlags_NoAALines) + if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) return; - ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectId]; - IM_ASSERT(r.IsPacked()); + ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdAALines); + IM_ASSERT(r->IsPacked()); // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them const int w = atlas->TexWidth; - for (unsigned int n = 0; n < (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); n++) // +1 because of the zero-width row + for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle unsigned int y = n; unsigned int line_width = n; - // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle - unsigned int pad_left = (r.Width - line_width) / 2; - unsigned int pad_right = r.Width - (pad_left + line_width); + unsigned int pad_left = (r->Width - line_width) / 2; + unsigned int pad_right = r->Width - (pad_left + line_width); // Make sure we're inside the texture bounds before we start writing pixels IM_ASSERT_PARANOID(pad_left + line_width + pad_right == r.Width); IM_ASSERT_PARANOID(y < r.Height); // Write each slice - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * w)]; for (unsigned int x = 0; x < pad_left; x++) *(write_ptr++) = 0; for (unsigned int x = 0; x < line_width; x++) @@ -2433,16 +2429,16 @@ static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) *(write_ptr++) = 0; // Calculate UVs for this line - ImFontAtlasCustomRect line_rect = r; + ImFontAtlasCustomRect line_rect = *r; line_rect.X += (unsigned short)(pad_left - 1); - line_rect.Width = (unsigned short)(line_width + 2); line_rect.Y += (unsigned short)y; + line_rect.Width = (unsigned short)(line_width + 2); line_rect.Height = 1; ImVec2 uv0, uv1; atlas->CalcCustomRectUV(&line_rect, &uv0, &uv1); - float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - atlas->TexUvAALines.push_back(ImVec4(uv0.x, halfV, uv1.x, halfV)); + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvAALines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } diff --git a/imgui_internal.h b/imgui_internal.h index 4f3882c9..629ddc32 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -529,9 +529,6 @@ struct IMGUI_API ImChunkStream #define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 #endif -// The maximum line width to build anti-aliased textures for (note that this needs to be one greater than the maximum line width you want to be able to draw using the textured path) -#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX 65 - // Data shared between all ImDrawList instances // You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. struct IMGUI_API ImDrawListSharedData @@ -548,7 +545,7 @@ struct IMGUI_API ImDrawListSharedData ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) - ImVector* TexUvAALines; // UV of anti-aliased lines in the atlas + const ImVec4* TexUvAALines; // UV of anti-aliased lines in the atlas ImDrawListSharedData(); void SetCircleSegmentMaxError(float max_error); From b5bae9781df1204a7dc6ae8b4b1f605c05f0fd74 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Tue, 7 Jul 2020 16:19:27 +0900 Subject: [PATCH 137/223] Texture-based thick lines: Only use textured lines for integer line widths --- imgui_draw.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 24e8a654..15a6c6f2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -681,8 +681,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const int integer_thickness = (int)thickness; const float fractional_thickness = thickness - integer_thickness; - // Do we want to draw this line using a texture? - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + // Do we want to draw this line using a texture? (for now, only draw integer-width lines using textures to avoid issues with the way scaling occurs) + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX) && (fractional_thickness >= -0.00001f) && (fractional_thickness <= 0.00001f); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); From 3a6c9907cd182795f82c67df5d77e88bcfe9563c Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 7 Jul 2020 13:24:10 +0200 Subject: [PATCH 138/223] Texture-based thick lines: Minor tweaks and rename toward merging in master. Changes to allow changing AA_SIZE (disable texture path). --- docs/CHANGELOG.txt | 9 +++++ imgui.cpp | 6 ++-- imgui.h | 28 +++++++-------- imgui_demo.cpp | 2 +- imgui_draw.cpp | 85 +++++++++++++++++++--------------------------- imgui_internal.h | 3 +- 6 files changed, 63 insertions(+), 70 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c62a140d..8043bf47 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? VERSION 1.78 WIP (In Progress) ----------------------------------------------------------------------- +Other Changes: + +- ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based + path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] + - This change will facilitate the wider use of thick borders in future style changes. + - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. + - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. + - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. + ----------------------------------------------------------------------- VERSION 1.77 (Released 2020-06-29) diff --git a/imgui.cpp b/imgui.cpp index b9c300fa..37e611ad 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,7 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require back-end to render with bilinear filtering. AntiAliasedFill = true; // Enable anti-aliased 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. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3689,7 +3689,7 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; - if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines)) + if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; @@ -6161,7 +6161,7 @@ void ImGui::SetCurrentFont(ImFont* font) ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; - g.DrawListSharedData.TexUvAALines = atlas->TexUvAALines; + g.DrawListSharedData.TexUvLines = atlas->TexUvLines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } diff --git a/imgui.h b/imgui.h index 5e86bae5..6f4dec52 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,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.78 WIP" -#define IMGUI_VERSION_NUM 17702 +#define IMGUI_VERSION_NUM 17703 #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) @@ -1438,9 +1438,9 @@ struct ImGuiStyle 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-aliased lines/borders. Disable if you are really tight on CPU/GPU. - bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. - bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require back-end to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). 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. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. ImVec4 Colors[ImGuiCol_COUNT]; @@ -1897,9 +1897,9 @@ struct ImColor // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- -// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoAALines to disable baking. -#ifndef IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX (63) +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63) #endif // ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] @@ -1998,14 +1998,14 @@ enum ImDrawCornerFlags_ ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience }; -#define IMGUI_HAS_TEXLINES 1 - +// Flags for ImDrawList. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. +// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. enum ImDrawListFlags_ { ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) - ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 2, // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require back-end to render with bilinear filtering. + ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; @@ -2226,7 +2226,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoAntiAliasedLines = 1 << 2 // Don't build anti-aliased line textures into the atlas (save a little texture memory). They will be rendered using polygons (a little bit more expensive) + ImFontAtlasFlags_NoBakedLines = 1 << 2 // Don't build thick line textures into the atlas (save a little texture memory). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2327,11 +2327,11 @@ struct ImFontAtlas ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector ConfigData; // Configuration data - ImVec4 TexUvAALines[IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1]; // UVs for anti-aliased line textures + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int PackIdAALines; // Custom texture rectangle ID for anti-aliased lines + int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8b5d57d4..d66bf014 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3832,7 +3832,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) 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 lines use texture", &style.AntiAliasedLinesUseTex); - ImGui::SameLine(); HelpMarker("Faster lines using texture data. Requires texture to use bilinear sampling (not nearest)."); + ImGui::SameLine(); HelpMarker("Faster lines using texture data. Require back-end to render with bilinear filtering (not point/nearest filtering)."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 15a6c6f2..942c2d90 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -358,7 +358,7 @@ ImDrawListSharedData::ImDrawListSharedData() ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } memset(CircleSegmentCounts, 0, sizeof(CircleSegmentCounts)); // This will be set by SetCircleSegmentMaxError() - TexUvAALines = NULL; + TexUvLines = NULL; } void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) @@ -681,11 +681,13 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const int integer_thickness = (int)thickness; const float fractional_thickness = thickness - integer_thickness; - // Do we want to draw this line using a texture? (for now, only draw integer-width lines using textures to avoid issues with the way scaling occurs) - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX) && (fractional_thickness >= -0.00001f) && (fractional_thickness <= 0.00001f); + // Do we want to draw this line using a texture? + // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. + // - If AA_SIZE is not 1.0f we cannot use the texture path. + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f); - // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off - IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off + IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); @@ -693,7 +695,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Temporary buffer // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point - ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_texture) ? 5 : 3) * sizeof(ImVec2)); //-V630 + ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((use_texture || !thick_line) ? 3 : 5) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; // Calculate normals (tangents) for each line segment @@ -717,7 +719,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code - const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : 1.0f; + const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) @@ -775,10 +777,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices - ImVec4 tex_uvs = _Data->TexUvAALines[integer_thickness]; + ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness]; if (fractional_thickness != 0.0f) { - const ImVec4 tex_uvs_1 = _Data->TexUvAALines[integer_thickness + 1]; + const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1]; tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; @@ -1719,7 +1721,7 @@ ImFontAtlas::ImFontAtlas() TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); - PackIdMouseCursors = PackIdAALines = -1; + PackIdMouseCursors = PackIdLines = -1; } ImFontAtlas::~ImFontAtlas() @@ -1747,7 +1749,7 @@ void ImFontAtlas::ClearInputData() } ConfigData.clear(); CustomRects.clear(); - PackIdMouseCursors = PackIdAALines = -1; + PackIdMouseCursors = PackIdLines = -1; } void ImFontAtlas::ClearTexData() @@ -2387,27 +2389,15 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } -static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) +static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas) { - if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) + if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) return; - // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row - atlas->PackIdAALines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); -} - -static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) -{ - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) - return; - - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdAALines); - IM_ASSERT(r->IsPacked()); - // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them - const int w = atlas->TexWidth; - for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row + ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines); + IM_ASSERT(r->IsPacked()); + for (unsigned int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle unsigned int y = n; @@ -2415,30 +2405,18 @@ static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) unsigned int pad_left = (r->Width - line_width) / 2; unsigned int pad_right = r->Width - (pad_left + line_width); - // Make sure we're inside the texture bounds before we start writing pixels - IM_ASSERT_PARANOID(pad_left + line_width + pad_right == r.Width); - IM_ASSERT_PARANOID(y < r.Height); - // Write each slice - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * w)]; - for (unsigned int x = 0; x < pad_left; x++) - *(write_ptr++) = 0; - for (unsigned int x = 0; x < line_width; x++) - *(write_ptr++) = 0xFF; - for (unsigned int x = 0; x < pad_right; x++) - *(write_ptr++) = 0; + IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)]; + memset(write_ptr, 0x00, pad_left); + memset(write_ptr + pad_left, 0xFF, line_width); + memset(write_ptr + pad_left + line_width, 0x00, pad_right); // Calculate UVs for this line - ImFontAtlasCustomRect line_rect = *r; - line_rect.X += (unsigned short)(pad_left - 1); - line_rect.Y += (unsigned short)y; - line_rect.Width = (unsigned short)(line_width + 2); - line_rect.Height = 1; - - ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&line_rect, &uv0, &uv1); + ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale; float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - atlas->TexUvAALines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } @@ -2454,15 +2432,22 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); } - ImFontAtlasBuildRegisterAALineCustomRects(atlas); + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row + if (atlas->PackIdLines < 0) + { + if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines)) + atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); + } } // This is called/shared by both the stb_truetype and the FreeType builder. void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data blocks + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); - ImFontAtlasBuildRenderAALinesTexData(atlas); + ImFontAtlasBuildRenderLinesTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) diff --git a/imgui_internal.h b/imgui_internal.h index 629ddc32..a6245d1a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -544,8 +544,7 @@ struct IMGUI_API ImDrawListSharedData // [Internal] Lookup tables ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) - - const ImVec4* TexUvAALines; // UV of anti-aliased lines in the atlas + const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas ImDrawListSharedData(); void SetCircleSegmentMaxError(float max_error); From 89685b346c7b02b7d557678fd9d5d11a80967f83 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 Jul 2020 11:21:31 +0200 Subject: [PATCH 139/223] ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra unrequired vertex. Actual missing code for d3b37180a3ff186b481d93d09664bb244a428d10, thanks @domgho! --- docs/CHANGELOG.txt | 8 ++++---- imgui_draw.cpp | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8043bf47..8f4de8d9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,12 +37,14 @@ HOW TO UPDATE? Other Changes: -- ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based +- ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - - This change will facilitate the wider use of thick borders in future style changes. + - This change will facilitate the wider use of thick borders in future style changes. - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. +- ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate + an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] ----------------------------------------------------------------------- @@ -112,8 +114,6 @@ Other Changes: VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after a callback draw command would incorrectly override the callback draw command. -- ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would - generate an extra unrequired vertex. [@ShironekoBen] - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeeds but FT_Load_Glyph() fails. - Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 942c2d90..cdaa34fa 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1235,7 +1235,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; if (num_segments == 12) - PathArcToFast(center, radius - 0.5f, 0, 12); + PathArcToFast(center, radius - 0.5f, 0, 12 - 1); else PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); PathStroke(col, true, thickness); @@ -1265,7 +1265,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, // 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; if (num_segments == 12) - PathArcToFast(center, radius, 0, 12); + PathArcToFast(center, radius, 0, 12 - 1); else PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); PathFillConvex(col); From cb1d5784707503b2a1a82be81dabcbe5529e4e5f Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 12:09:24 +0200 Subject: [PATCH 140/223] Backends: DX12, Viewports: Fixed issue on shutdown when viewports are disabled. (#3347) --- examples/imgui_impl_dx12.cpp | 38 ++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 40559b71..e4480e99 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -49,6 +49,7 @@ static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {}; static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL; static UINT g_numFramesInFlight = 0; +// Buffers used during the rendering of a frame struct FrameResources { ID3D12Resource* IndexBuffer; @@ -57,6 +58,7 @@ struct FrameResources int VertexBufferSize; }; +// Buffers used for secondary viewports created by the multi-viewports systems struct FrameContext { ID3D12CommandAllocator* CommandAllocator; @@ -64,7 +66,7 @@ struct FrameContext D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; }; -// Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data. +// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. struct ImGuiViewportDataDx12 { ID3D12CommandQueue* CommandQueue; @@ -133,6 +135,13 @@ static void SafeRelease(T*& res) res = NULL; } +static void ImGui_ImplDX12_DestroyFrameResources(FrameResources* resources) +{ + SafeRelease(resources->IndexBuffer); + SafeRelease(resources->VertexBuffer); + resources->IndexBufferSize = resources->VertexBufferSize = 0; +} + struct VERTEX_CONSTANT_BUFFER { float mvp[4][4]; @@ -699,6 +708,8 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO g_numFramesInFlight = num_frames_in_flight; g_pd3dSrvDescHeap = cbv_srv_heap; + // Create a dummy ImGuiViewportDataDx12 holder for the main viewport, + // Since this is created and managed by the application, we will only use the ->Resources[] fields. ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->RendererUserData = IM_NEW(ImGuiViewportDataDx12)(); @@ -712,6 +723,18 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO void ImGui_ImplDX12_Shutdown() { + // Manually delete main viewport render resources in-case we haven't initialized for viewports + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + if (ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)main_viewport->RendererUserData) + { + // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[] + for (UINT i = 0; i < g_numFramesInFlight; i++) + ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + IM_DELETE(data); + main_viewport->RendererUserData = NULL; + } + + // Clean up windows and device objects ImGui_ImplDX12_ShutdownPlatformInterface(); ImGui_ImplDX12_InvalidateDeviceObjects(); @@ -720,11 +743,6 @@ void ImGui_ImplDX12_Shutdown() g_hFontSrvGpuDescHandle.ptr = 0; g_numFramesInFlight = 0; g_pd3dSrvDescHeap = NULL; - - ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - if (ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)main_viewport->RendererUserData) - IM_DELETE(data); - main_viewport->RendererUserData = NULL; } void ImGui_ImplDX12_NewFrame() @@ -841,10 +859,7 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) } for (UINT i = 0; i < g_numFramesInFlight; i++) - { - SafeRelease(data->Resources[i].IndexBuffer); - SafeRelease(data->Resources[i].VertexBuffer); - } + ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); } static void ImGui_WaitForPendingOperations(ImGuiViewportDataDx12* data) @@ -880,8 +895,7 @@ static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport) { SafeRelease(data->FrameCtx[i].RenderTarget); SafeRelease(data->FrameCtx[i].CommandAllocator); - SafeRelease(data->Resources[i].IndexBuffer); - SafeRelease(data->Resources[i].VertexBuffer); + ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); } IM_DELETE(data); } From b626dd57d3f11a2ea91ea2f0b7d9be50d7506d21 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 12:20:03 +0200 Subject: [PATCH 141/223] Backends: DX12, Viewports: Tidying up, renaming. --- examples/imgui_impl_dx12.cpp | 74 ++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 36 deletions(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index e4480e99..690f3a8b 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -50,7 +50,7 @@ static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL; static UINT g_numFramesInFlight = 0; // Buffers used during the rendering of a frame -struct FrameResources +struct ImGui_ImplDX12_RenderBuffers { ID3D12Resource* IndexBuffer; ID3D12Resource* VertexBuffer; @@ -59,28 +59,31 @@ struct FrameResources }; // Buffers used for secondary viewports created by the multi-viewports systems -struct FrameContext +struct ImGui_ImplDX12_FrameContext { - ID3D12CommandAllocator* CommandAllocator; - ID3D12Resource* RenderTarget; - D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; + ID3D12CommandAllocator* CommandAllocator; + ID3D12Resource* RenderTarget; + D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; }; // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. +// Main viewport created by application will only use the Resources field. +// Secondary viewports created by this back-end will use all the fields (including Window fields), struct ImGuiViewportDataDx12 { - ID3D12CommandQueue* CommandQueue; - ID3D12GraphicsCommandList* CommandList; - ID3D12DescriptorHeap* RtvDescHeap; - IDXGISwapChain3* SwapChain; - - ID3D12Fence* Fence; - UINT64 FenceSignaledValue; - HANDLE FenceEvent; - - UINT FrameIndex; - FrameContext* FrameCtx; - FrameResources* Resources; + // Window + ID3D12CommandQueue* CommandQueue; + ID3D12GraphicsCommandList* CommandList; + ID3D12DescriptorHeap* RtvDescHeap; + IDXGISwapChain3* SwapChain; + ID3D12Fence* Fence; + UINT64 FenceSignaledValue; + HANDLE FenceEvent; + ImGui_ImplDX12_FrameContext* FrameCtx; + + // Render buffers + UINT FrameIndex; + ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers; ImGuiViewportDataDx12() { @@ -88,13 +91,12 @@ struct ImGuiViewportDataDx12 CommandList = NULL; RtvDescHeap = NULL; SwapChain = NULL; - Fence = NULL; FenceSignaledValue = 0; FenceEvent = NULL; + FrameCtx = new ImGui_ImplDX12_FrameContext[g_numFramesInFlight]; FrameIndex = UINT_MAX; - FrameCtx = new FrameContext[g_numFramesInFlight]; - Resources = new FrameResources[g_numFramesInFlight]; + FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[g_numFramesInFlight]; for (UINT i = 0; i < g_numFramesInFlight; ++i) { @@ -102,10 +104,10 @@ struct ImGuiViewportDataDx12 FrameCtx[i].RenderTarget = NULL; // Create buffers with a default size (they will later be grown as needed) - Resources[i].IndexBuffer = NULL; - Resources[i].VertexBuffer = NULL; - Resources[i].VertexBufferSize = 5000; - Resources[i].IndexBufferSize = 10000; + FrameRenderBuffers[i].IndexBuffer = NULL; + FrameRenderBuffers[i].VertexBuffer = NULL; + FrameRenderBuffers[i].VertexBufferSize = 5000; + FrameRenderBuffers[i].IndexBufferSize = 10000; } } ~ImGuiViewportDataDx12() @@ -119,11 +121,11 @@ struct ImGuiViewportDataDx12 for (UINT i = 0; i < g_numFramesInFlight; ++i) { IM_ASSERT(FrameCtx[i].CommandAllocator == NULL && FrameCtx[i].RenderTarget == NULL); - IM_ASSERT(Resources[i].IndexBuffer == NULL && Resources[i].VertexBuffer == NULL); + IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == NULL && FrameRenderBuffers[i].VertexBuffer == NULL); } delete[] FrameCtx; FrameCtx = NULL; - delete[] Resources; Resources = NULL; + delete[] FrameRenderBuffers; FrameRenderBuffers = NULL; } }; @@ -135,11 +137,11 @@ static void SafeRelease(T*& res) res = NULL; } -static void ImGui_ImplDX12_DestroyFrameResources(FrameResources* resources) +static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers) { - SafeRelease(resources->IndexBuffer); - SafeRelease(resources->VertexBuffer); - resources->IndexBufferSize = resources->VertexBufferSize = 0; + SafeRelease(render_buffers->IndexBuffer); + SafeRelease(render_buffers->VertexBuffer); + render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0; } struct VERTEX_CONSTANT_BUFFER @@ -151,7 +153,7 @@ struct VERTEX_CONSTANT_BUFFER static void ImGui_ImplDX12_InitPlatformInterface(); static void ImGui_ImplDX12_ShutdownPlatformInterface(); -static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, FrameResources* fr) +static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* 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). @@ -216,7 +218,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL ImGuiViewportDataDx12* render_data = (ImGuiViewportDataDx12*)draw_data->OwnerViewport->RendererUserData; render_data->FrameIndex++; - FrameResources* fr = &render_data->Resources[render_data->FrameIndex % g_numFramesInFlight]; + ImGui_ImplDX12_RenderBuffers* fr = &render_data->FrameRenderBuffers[render_data->FrameIndex % g_numFramesInFlight]; // Create and grow vertex/index buffers if needed if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount) @@ -729,7 +731,7 @@ void ImGui_ImplDX12_Shutdown() { // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[] for (UINT i = 0; i < g_numFramesInFlight; i++) - ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + ImGui_ImplDX12_DestroyRenderBuffers(&data->FrameRenderBuffers[i]); IM_DELETE(data); main_viewport->RendererUserData = NULL; } @@ -859,7 +861,7 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) } for (UINT i = 0; i < g_numFramesInFlight; i++) - ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + ImGui_ImplDX12_DestroyRenderBuffers(&data->FrameRenderBuffers[i]); } static void ImGui_WaitForPendingOperations(ImGuiViewportDataDx12* data) @@ -895,7 +897,7 @@ static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport) { SafeRelease(data->FrameCtx[i].RenderTarget); SafeRelease(data->FrameCtx[i].CommandAllocator); - ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + ImGui_ImplDX12_DestroyRenderBuffers(&data->FrameRenderBuffers[i]); } IM_DELETE(data); } @@ -928,7 +930,7 @@ static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*) { ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)viewport->RendererUserData; - FrameContext* frame_context = &data->FrameCtx[data->FrameIndex % g_numFramesInFlight]; + ImGui_ImplDX12_FrameContext* frame_context = &data->FrameCtx[data->FrameIndex % g_numFramesInFlight]; UINT back_buffer_idx = data->SwapChain->GetCurrentBackBufferIndex(); const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); From 06f7854b160200ac942aba1137e76be7600d7fc5 Mon Sep 17 00:00:00 2001 From: Moritz Heinemann Date: Wed, 1 Jul 2020 23:13:59 +0200 Subject: [PATCH 142/223] Backends: OpenGL3: Add glad 2 to OpenGL loaders. (#3330) --- examples/example_glfw_opengl3/Makefile | 4 ++++ examples/example_glfw_opengl3/main.cpp | 4 ++++ examples/example_sdl_opengl3/Makefile | 4 ++++ examples/example_sdl_opengl3/main.cpp | 4 ++++ examples/imgui_impl_opengl3.cpp | 5 +++++ examples/imgui_impl_opengl3.h | 3 +++ 6 files changed, 24 insertions(+) diff --git a/examples/example_glfw_opengl3/Makefile b/examples/example_glfw_opengl3/Makefile index 3bc72b6f..0e7faa12 100644 --- a/examples/example_glfw_opengl3/Makefile +++ b/examples/example_glfw_opengl3/Makefile @@ -42,6 +42,10 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W # SOURCES += ../libs/glad/src/glad.c # CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD +## Using OpenGL loader: glad2 +# SOURCES += ../libs/glad/src/gl.c +# CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD2 + ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 6a3592f1..fa4e4bb9 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -17,6 +17,8 @@ #include // Initialize with glewInit() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Initialize with gladLoadGL() +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) +#include // Initialize with gladLoadGL(...) or gladLoaderLoadGL() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. #include // Initialize with glbinding::Binding::initialize() @@ -84,6 +86,8 @@ int main(int, char**) bool err = glewInit() != GLEW_OK; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) + bool err = gladLoadGL(glfwGetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index 41826741..e8009a4c 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -42,6 +42,10 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W # SOURCES += ../libs/glad/src/glad.c # CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD +## Using OpenGL loader: glad2 +# SOURCES += ../libs/glad/src/gl.c +# CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD2 + ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 3146084d..96e5617b 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -19,6 +19,8 @@ #include // Initialize with glewInit() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Initialize with gladLoadGL() +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) +#include // Initialize with gladLoadGL(...) or gladLoaderLoadGL() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. #include // Initialize with glbinding::Binding::initialize() @@ -79,6 +81,8 @@ int main(int, char**) bool err = glewInit() != GLEW_OK; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) + bool err = gladLoadGL((GLADloadfunc) SDL_GL_GetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 028a704b..df64bfa2 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-07-01: OpenGL: Added support for glad2 OpenGL loader. // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. @@ -101,6 +102,8 @@ #include // Needs to be initialized with glewInit() in user's code. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Needs to be initialized with gladLoadGL() in user's code. +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) +#include // Needs to be initialized with gladLoadGL(...) or gladLoaderLoadGL() in user's code. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) #ifndef GLFW_INCLUDE_NONE #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. @@ -189,6 +192,8 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) gl_loader = "GLEW"; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) gl_loader = "GLAD"; +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) + gl_loader = "GLAD2"; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) gl_loader = "glbinding2"; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index 07d35219..14eb2842 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -49,6 +49,7 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); && !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \ + && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) @@ -68,6 +69,8 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); #define IMGUI_IMPL_OPENGL_LOADER_GLEW #elif __has_include() #define IMGUI_IMPL_OPENGL_LOADER_GLAD +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLAD2 #elif __has_include() #define IMGUI_IMPL_OPENGL_LOADER_GL3W #elif __has_include() From fb7f6cab8c322731da336e553915e944bf386e62 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 14:36:00 +0200 Subject: [PATCH 143/223] Backends: Amend, docs + extra comments. (#3330, #3245) --- docs/CHANGELOG.txt | 1 + examples/README.txt | 4 ++-- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_sdl_opengl3/main.cpp | 2 +- examples/imgui_impl_opengl3.cpp | 2 +- imgui_draw.cpp | 7 +++++-- 6 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8f4de8d9..6ee96d78 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other Changes: - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] +- Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 35ee87b9..8c89ef00 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -204,7 +204,7 @@ example_glfw_opengl2/ GLFW + OpenGL2 example (legacy, fixed pipeline). = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp **DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** - **Prefer using OPENGL3 code (with gl3w/glew/glad/glbinding, you can replace the OpenGL function loader)** + **Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)** This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to make things more complicated, will require your code to reset many OpenGL attributes to their initial @@ -253,7 +253,7 @@ example_sdl_opengl2/ SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline). = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp **DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** - **Prefer using OPENGL3 code (with gl3w/glew/glad/glbinding, you can replace the OpenGL function loader)** + **Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)** This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to make things more complicated, will require your code to reset many OpenGL attributes to their initial diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index fa4e4bb9..30943301 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -87,7 +87,7 @@ int main(int, char**) #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) - bool err = gladLoadGL(glfwGetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. + bool err = gladLoadGL(glfwGetProcAddress) == 0; // glad2 recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 96e5617b..92d03138 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -82,7 +82,7 @@ int main(int, char**) #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) - bool err = gladLoadGL((GLADloadfunc) SDL_GL_GetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. + bool err = gladLoadGL((GLADloadfunc)SDL_GL_GetProcAddress) == 0; // glad2 recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index df64bfa2..cb60304d 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) -// 2020-07-01: OpenGL: Added support for glad2 OpenGL loader. +// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader. // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index cdaa34fa..864364e9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -717,8 +717,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // [PATH 1] Texture-based lines (thick or non-thick) // [PATH 2] Non texture-based lines (non-thick) - // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA - // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus "one pixel" for AA. + // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture + // (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code. + // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to + // allow scaling geometry while preserving one-screen-pixel AA fringe). const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend From cbade7b16d3b7f1bbcd257a9639209e937a88224 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 19:04:58 +0200 Subject: [PATCH 144/223] Docking: Workaround recovery for node created without the _ockSpace flags later becoming DockSpace. (#3340) --- imgui.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 7b31979c..36d27145 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14145,6 +14145,17 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla node->OnlyNodeWithWindows = NULL; IM_ASSERT(node->IsRootNode()); + + // We need to handle the rare case were a central node is missing. + // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace. + // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. + // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. + // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, + // as it doesn't make sense for an empty dockspace to not have this property. + if (node->IsLeafNode() && !node->IsCentralNode()) + node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; + + // Update the node DockNodeUpdate(node); g.WithinEndChild = true; @@ -15765,14 +15776,16 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("Dock nodes")) { + static bool root_nodes_only = true; ImGuiDockContext* dc = &g.DockContext; + ImGui::Checkbox("List root nodes", &root_nodes_only); ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes); if (ImGui::SmallButton("Clear nodes")) { 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()) + if (!root_nodes_only || node->IsRootNode()) Funcs::NodeDockNode(node, "Node"); ImGui::TreePop(); } From 550f110354fc922d1a471906360558b14374c863 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 12 Jul 2020 23:51:13 +0200 Subject: [PATCH 145/223] InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (#3349) --- docs/CHANGELOG.txt | 5 +++++ docs/TODO.txt | 3 ++- imgui_draw.cpp | 5 ++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ee96d78..0264e314 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,11 @@ HOW TO UPDATE? Other Changes: +- InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more + than ~16 KB characters. (Note that current code is going to show corrupted display if after + clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText + call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare + but it will be addressed later). (#3349) - ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - This change will facilitate the wider use of thick borders in future style changes. diff --git a/docs/TODO.txt b/docs/TODO.txt index abb9d513..9502e264 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -308,7 +308,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font/atlas: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. - 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: better reserve policy for large horizontal block of text (shouldn't reserve for all clipped lines). also see #3349. + - font/draw: fix for drawing 16k+ visible characters in same call. - 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? diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 864364e9..09b5a413 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -517,7 +517,7 @@ void ImDrawList::_OnChangedVtxOffset() // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this. _VtxCurrentIdx = 0; ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); + //IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); // See #3349 if (curr_cmd->ElemCount != 0) { AddDrawCmd(); @@ -582,6 +582,9 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { + // FIXME: In theory we should be testing that vtx_count <64k here. + // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us + // to not make that check until we rework the text functions to handle clipping and large horizontal lines better. _CmdHeader.VtxOffset = VtxBuffer.Size; _OnChangedVtxOffset(); } From eefae082617cd36d9b1d412e481a7913ab0ef3f2 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 14 Jul 2020 18:36:35 +0200 Subject: [PATCH 146/223] Nav: Fixed clicking on void from not clearing focused window. Amend d31fe97f7. (#3344, #2880) This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. --- docs/CHANGELOG.txt | 5 ++++- imgui.cpp | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0264e314..b11ed192 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,9 @@ HOW TO UPDATE? Other Changes: +- Nav: Fixed clicking on void from not clearing focused window. + This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard + flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (Note that current code is going to show corrupted display if after clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText @@ -62,7 +65,7 @@ Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.77 Breaking Changes: - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please - note that this is a Beta api and will likely be reworked in order to support multi-DPI accross + note that this is a Beta api and will likely be reworked in order to support multi-DPI across multiple monitors. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor diff --git a/imgui.cpp b/imgui.cpp index 37e611ad..b17e2ee8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3367,7 +3367,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; } - else if (root_window != NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) + else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { // Clicking on void disable focus FocusWindow(NULL); From 825f2ae455b90862fd9637115f4a70bfb17c9290 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 16 Jul 2020 17:20:24 +0200 Subject: [PATCH 147/223] Demo: Tweak "child windows" section. (#3318) --- docs/CHANGELOG.txt | 1 + imgui_demo.cpp | 22 +++++++--------------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b11ed192..ebce7da0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,7 @@ Other Changes: - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] +- Demo: Tweak "Child Windows" section. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d66bf014..97e2951d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1969,12 +1969,6 @@ static void ShowDemoWindowLayout() ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel); ImGui::Checkbox("Disable Menu", &disable_menu); - static int line = 50; - bool goto_line = ImGui::Button("Goto"); - ImGui::SameLine(); - ImGui::SetNextItemWidth(100); - goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); - // Child 1: no border, enable horizontal scrollbar { ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; @@ -1982,13 +1976,7 @@ static void ShowDemoWindowLayout() window_flags |= ImGuiWindowFlags_NoScrollWithMouse; ImGui::BeginChild("ChildL", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags); for (int i = 0; i < 100; i++) - { ImGui::Text("%04d: scrollable region", i); - if (goto_line && line == i) - ImGui::SetScrollHereY(); - } - if (goto_line && line >= 100) - ImGui::SetScrollHereY(); ImGui::EndChild(); } @@ -2034,15 +2022,21 @@ 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 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details. { - ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10); + static int offset_x = 0; + ImGui::SetNextItemWidth(100); + ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000); + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x); ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); ImGui::BeginChild("Red", ImVec2(200, 100), true, ImGuiWindowFlags_None); for (int n = 0; n < 50; n++) ImGui::Text("Some test %d", n); ImGui::EndChild(); + bool child_is_hovered = ImGui::IsItemHovered(); ImVec2 child_rect_min = ImGui::GetItemRectMin(); ImVec2 child_rect_max = ImGui::GetItemRectMax(); ImGui::PopStyleColor(); + ImGui::Text("Hovered: %d", child_is_hovered); ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y); } @@ -2428,8 +2422,6 @@ static void ShowDemoWindowLayout() 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); From 4be8155002b2248335eeac57fb185f2020f8f8bb Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 16 Jul 2020 21:51:49 +0200 Subject: [PATCH 148/223] Style Editor: Added preview of circle auto-tessellation when editing the corresponding value.. --- docs/CHANGELOG.txt | 3 ++- imgui_demo.cpp | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ebce7da0..4e3a5a1a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Other Changes: - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] - Demo: Tweak "Child Windows" section. +- Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] @@ -129,7 +130,7 @@ Other Changes: Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). - Fixed a static constructor which led to this dependency on some compiler setups. + Fixed a static constructor which led to this dependency on some compiler setups. [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 97e2951d..49ac4180 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3829,7 +3829,28 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f; - ImGui::DragFloat("Circle segment Max Error", &style.CircleSegmentMaxError, 0.01f, 0.10f, 10.0f, "%.2f"); + + // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. + ImGui::DragFloat("Circle Segment Max Error", &style.CircleSegmentMaxError, 0.01f, 0.10f, 10.0f, "%.2f"); + if (ImGui::IsItemActive()) + { + ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); + ImGui::BeginTooltip(); + ImVec2 p = ImGui::GetCursorScreenPos(); + float RAD_MIN = 10.0f, RAD_MAX = 80.0f; + float off_x = 10.0f; + for (int n = 0; n < 7; n++) + { + const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (7.0f - 1.0f); + ImGui::GetWindowDrawList()->AddCircle(ImVec2(p.x + off_x + rad, p.y + RAD_MAX), rad, ImGui::GetColorU32(ImGuiCol_Text), 0); + off_x += 10.0f + rad * 2.0f; + } + ImGui::Dummy(ImVec2(off_x, RAD_MAX * 2.0f)); + ImGui::EndTooltip(); + } + ImGui::SameLine(); + HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically."); + ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. ImGui::PopItemWidth(); From e223bd8177f15eb60698d8cb0f8a9d455b77b783 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 16 Jul 2020 22:25:23 +0200 Subject: [PATCH 149/223] ImDrawList: changed AddCircle(), AddCircleFilled() default num_segments from 12 to 0. --- docs/CHANGELOG.txt | 5 ++++- imgui.h | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4e3a5a1a..7846eace 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,7 +37,7 @@ HOW TO UPDATE? Other Changes: -- Nav: Fixed clicking on void from not clearing focused window. +- Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more @@ -51,6 +51,9 @@ Other Changes: - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. +- ImDrawList: changed AddCircle(), AddCircleFilled() default num_segments from 12 to 0, effectively + enabling auto-tessellation by default. Tweak tessellation in Style Editor->Rendering section, or + by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] - Demo: Tweak "Child Windows" section. diff --git a/imgui.h b/imgui.h index 6f4dec52..4517aabc 100644 --- a/imgui.h +++ b/imgui.h @@ -2052,6 +2052,7 @@ struct ImDrawList // Primitives // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). + // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. // In future versions we will use textures to provide cheaper and higher-quality circles. // Use AddNgon() and AddNgonFilled() functions if you need to guaranteed a specific number of sides. IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); @@ -2062,8 +2063,8 @@ struct ImDrawList IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); - IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); From cba52b66afa44a886f82b4c78e12e4ed389c7068 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 17 Jul 2020 18:11:01 +0200 Subject: [PATCH 150/223] Backends: GLFW: Fixed enabling ImGuiBackendFlags_HasMouseHoveredViewport broken by 950539b7. As it turns out, back-end passing NULL hovered with HasMouseHoveredViewport is also broken which defeats some of its purpose. --- examples/imgui_impl_glfw.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 1fab7634..d163a72a 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -166,7 +166,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw 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) -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy) #endif io.BackendPlatformName = "imgui_impl_glfw"; @@ -348,7 +348,7 @@ static void ImGui_ImplGlfw_UpdateMousePosAndButtons() // rectangles and last focused time of every viewports it knows about. It will be unaware of other windows that may be sitting between or over your windows. // [GLFW] FIXME: This is currently only correct on Win32. See what we do below with the WM_NCHITTEST, missing an equivalent for other systems. // See https://github.com/glfw/glfw/issues/1236 if you want to help in making this a GLFW feature. -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !(viewport->Flags & ImGuiViewportFlags_NoInputs)) io.MouseHoveredViewport = viewport->ID; #endif @@ -586,7 +586,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) { if (data->WindowOwned) { -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) HWND hwnd = (HWND)viewport->PlatformHandleRaw; ::RemovePropA(hwnd, "IMGUI_VIEWPORT"); #endif @@ -600,7 +600,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) // We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs". // In the meanwhile we implement custom per-platform workarounds here (FIXME-VIEWPORT: Implement same work-around for Linux/OSX!) -#if defined(_WIN32) && GLFW_HAS_GLFW_HOVERED +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) static WNDPROC g_GlfwWndProc = NULL; static LRESULT CALLBACK WndProcNoInputs(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { @@ -634,7 +634,7 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) } // GLFW hack: install hook for WM_NCHITTEST message handler -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) ::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport); if (g_GlfwWndProc == NULL) g_GlfwWndProc = (WNDPROC)::GetWindowLongPtr(hwnd, GWLP_WNDPROC); From 3d4af15d1d5f5d3746b69859308949c357e0c21e Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 17 Jul 2020 16:57:50 +0300 Subject: [PATCH 151/223] Backends GLFW: Use GLFW_MOUSE_PASSTHROUGH when available. --- examples/imgui_impl_glfw.cpp | 24 ++++++++++++++++++------ examples/imgui_impl_glfw.h | 3 +++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index d163a72a..e7dc10ca 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -10,6 +10,9 @@ // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// Issues: +// [ ] Platform: Multi-viewport support: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). + // 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 @@ -63,6 +66,11 @@ #else #define GLFW_HAS_NEW_CURSORS (0) #endif +#ifdef GLFW_MOUSE_PASSTHROUGH // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2020-07-17 (passthrough) +#define GLFW_HAS_MOUSE_PASSTHROUGH (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_MOUSE_PASSTHROUGH +#else +#define GLFW_HAS_MOUSE_PASSTHROUGH (0) +#endif // Data enum GlfwClientApi @@ -166,7 +174,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw 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) -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)) io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy) #endif io.BackendPlatformName = "imgui_impl_glfw"; @@ -348,8 +356,12 @@ static void ImGui_ImplGlfw_UpdateMousePosAndButtons() // rectangles and last focused time of every viewports it knows about. It will be unaware of other windows that may be sitting between or over your windows. // [GLFW] FIXME: This is currently only correct on Win32. See what we do below with the WM_NCHITTEST, missing an equivalent for other systems. // See https://github.com/glfw/glfw/issues/1236 if you want to help in making this a GLFW feature. -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) - if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !(viewport->Flags & ImGuiViewportFlags_NoInputs)) +#if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)) + const bool window_no_input = (viewport->Flags & ImGuiViewportFlags_NoInputs) != 0; +#if GLFW_HAS_MOUSE_PASSTHROUGH + glfwSetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH, window_no_input); +#endif + if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !window_no_input) io.MouseHoveredViewport = viewport->ID; #endif } @@ -586,7 +598,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) { if (data->WindowOwned) { -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) HWND hwnd = (HWND)viewport->PlatformHandleRaw; ::RemovePropA(hwnd, "IMGUI_VIEWPORT"); #endif @@ -600,7 +612,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) // We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs". // In the meanwhile we implement custom per-platform workarounds here (FIXME-VIEWPORT: Implement same work-around for Linux/OSX!) -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) static WNDPROC g_GlfwWndProc = NULL; static LRESULT CALLBACK WndProcNoInputs(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { @@ -634,7 +646,7 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) } // GLFW hack: install hook for WM_NCHITTEST message handler -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) ::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport); if (g_GlfwWndProc == NULL) g_GlfwWndProc = (WNDPROC)::GetWindowLongPtr(hwnd, GWLP_WNDPROC); diff --git a/examples/imgui_impl_glfw.h b/examples/imgui_impl_glfw.h index bea576a0..9ad0d9b3 100644 --- a/examples/imgui_impl_glfw.h +++ b/examples/imgui_impl_glfw.h @@ -9,6 +9,9 @@ // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// Issues: +// [ ] Platform: Multi-viewport support: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). + // 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 From b335225caa7816ceb833703ebde4c82a5c46e0f0 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 17:24:52 +0200 Subject: [PATCH 152/223] Internals: Extract ImFontAtlasBuildRender1bppRectFromString() out of ImFontAtlasBuildRenderDefaultTexData() + minor renaming, comments --- imgui_draw.cpp | 36 +++++++++++++++++++++--------------- imgui_internal.h | 1 + 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 09b5a413..137e2494 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1667,10 +1667,10 @@ 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 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; -static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = +// The 2x2 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 = 108; // Actual texture will be 2 times that + 1 spacing. +const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; +static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX " "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X " @@ -2003,7 +2003,7 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; out_uv_border[0] = (pos) * TexUvScale; out_uv_border[1] = (pos + size) * TexUvScale; - pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; + pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; out_uv_fill[0] = (pos) * TexUvScale; out_uv_fill[1] = (pos + size) * TexUvScale; return true; @@ -2366,6 +2366,16 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa } } +void ImFontAtlasBuildRender1bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value) +{ + IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth); + IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight); + unsigned char* out_pixel = atlas->TexPixelsAlpha8 + x + (y * atlas->TexWidth); + for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w) + for (int off_x = 0; off_x < w; off_x++) + out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : 0x00; +} + static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); @@ -2375,15 +2385,11 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) { // Render/copy pixels - IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); - for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++) - for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) - { - const int offset0 = (int)(r->X + x) + (int)(r->Y + y) * w; - const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; - atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00; - atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00; - } + IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); + const int x_for_white = r->X; + const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; + ImFontAtlasBuildRender1bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', 0xFF); + ImFontAtlasBuildRender1bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', 0xFF); } else { @@ -2433,7 +2439,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->PackIdMouseCursors < 0) { if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); else atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); } diff --git a/imgui_internal.h b/imgui_internal.h index a6245d1a..27212402 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2022,6 +2022,7 @@ IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRender1bppRectFromString(ImFontAtlas* atlas, int atlas_x, int atlas_y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value); 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); From fdc526e8f81b74752c6d057e7e28629336e66f30 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 18:18:30 +0200 Subject: [PATCH 153/223] Stop advertisting for Drag v_min>v_max which was introduced in 1.73 likely for 0537ac00 then made unnecessary with 32c33c66, added undocumented ImGuiItemFlags_ReadOnly as possible replacement (unused), (#211) --- imgui.h | 1 - imgui_internal.h | 1 + imgui_widgets.cpp | 6 ++++++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 4517aabc..bc056857 100644 --- a/imgui.h +++ b/imgui.h @@ -464,7 +464,6 @@ namespace ImGui // - 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_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - // - 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_internal.h b/imgui_internal.h index 27212402..5399a122 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -575,6 +575,7 @@ enum ImGuiItemFlags_ 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_ReadOnly = 1 << 7, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags_Default_ = 0 }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 86295bcd..9b3ec52d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2113,6 +2113,8 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } if (g.ActiveId != id) return false; + if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + return false; switch (data_type) { @@ -2558,6 +2560,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { + ImGuiContext& g = *GImGui; + if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + return false; + switch (data_type) { case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } From b8c22bdb2849577d27314fd61df96c4978c7359c Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 19:03:48 +0200 Subject: [PATCH 154/223] DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 3 ++- imgui_widgets.cpp | 22 ++++++++++++++++++---- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7846eace..c2850811 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,8 @@ Other Changes: - Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) +- DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both + min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (Note that current code is going to show corrupted display if after clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 49ac4180..647e4298 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1491,7 +1491,8 @@ static void ShowDemoWindowWidgets() { static float begin = 10, end = 90; static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9b3ec52d..c0de761a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2278,10 +2278,17 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu BeginGroup(); 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); + float min = (v_min >= v_max) ? -FLT_MAX : v_min; + float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, format_max ? format_max : format, power); + + min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + max = (v_min >= v_max) ? FLT_MAX : v_max; + if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2323,10 +2330,17 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ BeginGroup(); 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); + int min = (v_min >= v_max) ? INT_MIN : v_min; + int max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit + bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, format_max ? format_max : format); + + min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + max = (v_min >= v_max) ? INT_MAX : v_max; + if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit + value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); From bbd061538cf42c850b9a0b88f03741393db18fb4 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 Jul 2020 13:00:56 +0200 Subject: [PATCH 155/223] Internals: Drag/Sliders: simplified some code. --- imgui_widgets.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c0de761a..ecae7d0a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2166,7 +2166,6 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Tabbing or CTRL-clicking on Drag turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); bool temp_input_is_active = TempInputIsActive(id); - bool temp_input_start = false; if (!temp_input_is_active) { const bool focus_requested = FocusableItemRegister(window, id); @@ -2180,14 +2179,14 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); if (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id) { - temp_input_start = true; + temp_input_is_active = true; FocusableItemUnregister(window); } } } // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. - if (temp_input_is_active || temp_input_start) + if (temp_input_is_active) return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame @@ -2638,7 +2637,6 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Tabbing or CTRL-clicking on Slider turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); bool temp_input_is_active = TempInputIsActive(id); - bool temp_input_start = false; if (!temp_input_is_active) { const bool focus_requested = FocusableItemRegister(window, id); @@ -2651,14 +2649,14 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); if (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id) { - temp_input_start = true; + temp_input_is_active = true; FocusableItemUnregister(window); } } } // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. - if (temp_input_is_active || temp_input_start) + if (temp_input_is_active) return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame From c7f5876f8ac6e9fdbe47da444da0d5eaa1270f09 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 Jul 2020 14:44:58 +0200 Subject: [PATCH 156/223] Internals: backport window HitTestHole code from docking branch + RenderRectFilledWithHole() helper. (#1512, #3368) --- imgui.cpp | 20 ++++++++++++++++++++ imgui_draw.cpp | 16 ++++++++++++++++ imgui_internal.h | 4 ++++ 3 files changed, 40 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index b17e2ee8..59845af7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4295,6 +4295,16 @@ static void FindHoveredWindow() if (!bb.Contains(g.IO.MousePos)) continue; + // Support for one rectangular hole in any given window + // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) + if (window->HitTestHoleSize.x != 0) + { + ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y); + ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y); + if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos)) + continue; + } + // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches. if (hovered_window == NULL) hovered_window = window; @@ -5940,6 +5950,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (!(flags & ImGuiWindowFlags_NoTitleBar)) RenderWindowTitleBarContents(window, title_bar_rect, name, p_open); + // Clear hit test shape every frame + window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0; + // 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? @@ -6429,6 +6442,13 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co window->Collapsed = collapsed; } +void ImGui::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(size); + window->HitTestHoleOffset = ImVec2ih(pos - window->Pos); +} + void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) { SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 137e2494..ad44b671 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3501,6 +3501,22 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im draw_list->PathFillConvex(col); } +void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding) +{ + const bool fill_L = (inner.Min.x > outer.Min.x); + const bool fill_R = (inner.Max.x < outer.Max.x); + const bool fill_U = (inner.Min.y > outer.Min.y); + const bool fill_D = (inner.Max.y < outer.Max.y); + if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, (fill_U ? 0 : ImDrawCornerFlags_TopLeft) | (fill_D ? 0 : ImDrawCornerFlags_BotLeft)); + if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, (fill_U ? 0 : ImDrawCornerFlags_TopRight) | (fill_D ? 0 : ImDrawCornerFlags_BotRight)); + if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, (fill_L ? 0 : ImDrawCornerFlags_TopLeft) | (fill_R ? 0 : ImDrawCornerFlags_TopRight)); + if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, (fill_L ? 0 : ImDrawCornerFlags_BotLeft) | (fill_R ? 0 : ImDrawCornerFlags_BotRight)); + if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawCornerFlags_TopLeft); + if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawCornerFlags_TopRight); + if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawCornerFlags_BotLeft); + if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawCornerFlags_BotRight); +} + // Helper for ColorPicker4() // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. // Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. diff --git a/imgui_internal.h b/imgui_internal.h index 5399a122..ea135fce 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1615,6 +1615,8 @@ struct IMGUI_API ImGuiWindow ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect 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 ContentRegionRect; // 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. + ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. + ImVec2ih HitTestHoleOffset; int LastFrameActive; // Last frame number the window was Active. float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) @@ -1775,6 +1777,7 @@ 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 SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window); @@ -1943,6 +1946,7 @@ namespace ImGui IMGUI_API void RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow); 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 RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // [1.71: 2019/06/07: Updating prototypes of some of the internal functions. Leaving those for reference for a short while] From 218ff3a2a5186a91bf1a053468e66727d1c34d73 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 Jul 2020 15:04:29 +0200 Subject: [PATCH 157/223] Internals: Backport one ->WasActive test in NavRestoreLastChildNavWindow() from 9bf6509c6 + minor/shallow bits from docking branch. --- imgui.cpp | 42 ++++++++++++++++++++++++++---------------- imgui.h | 4 ++-- imgui_demo.cpp | 5 +++-- imgui_internal.h | 4 ++++ 4 files changed, 35 insertions(+), 20 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 59845af7..a74e96a5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2467,6 +2467,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) return "Unknown"; } + //----------------------------------------------------------------------------- // [SECTION] RENDER HELPERS // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, @@ -5590,6 +5591,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f) window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); + // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. + window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); + window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; + // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) @@ -5912,8 +5917,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f); window->DC.MenuBarAppending = false; - window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); - window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); window->DC.TreeDepth = 0; window->DC.TreeJumpToParentOnPopMask = 0x00; @@ -7624,7 +7627,7 @@ void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; - //IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id); + IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id); if (g.OpenPopupStack.Size < current_stack_size + 1) { g.OpenPopupStack.push_back(popup_ref); @@ -7685,7 +7688,7 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to } 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); + IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep); ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup); } } @@ -7693,6 +7696,7 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; + IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup); IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); // Trim open popup stack @@ -7737,7 +7741,7 @@ void ImGui::CloseCurrentPopup() break; popup_idx--; } - //IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); + IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); ClosePopupToLevel(popup_idx, true); // A common pattern is to close a popup when selecting a menu item/selectable that will open another window. @@ -8322,18 +8326,20 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov // 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) - parent_window = parent_window->ParentWindow; - if (parent_window && parent_window != nav_window) - parent_window->NavLastChildNavWindow = nav_window; + ImGuiWindow* parent = nav_window; + while (parent && (parent->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + parent = parent->ParentWindow; + if (parent && parent != nav_window) + parent->NavLastChildNavWindow = nav_window; } // 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; + return window; } static void NavRestoreLayer(ImGuiNavLayer layer) @@ -9651,6 +9657,7 @@ void ImGui::LogButtons() LogToClipboard(); } + //----------------------------------------------------------------------------- // [SECTION] SETTINGS //----------------------------------------------------------------------------- @@ -9905,9 +9912,9 @@ static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; int x, y; int i; - 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); + 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); } } // Apply to existing windows (if any) @@ -10514,7 +10521,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Details for Docking #ifdef IMGUI_HAS_DOCK - if (ImGui::TreeNode("Docking")) + if (ImGui::TreeNode("Dock nodes")) { ImGui::TreePop(); } @@ -10526,6 +10533,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear")) ImGui::ClearIniSettings(); ImGui::SameLine(); + if (ImGui::SmallButton("Save to memory")) + ImGui::SaveIniSettingsToMemory(); + ImGui::SameLine(); if (ImGui::SmallButton("Save to disk")) ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); ImGui::SameLine(); @@ -10537,7 +10547,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) { for (int n = 0; n < g.SettingsHandlers.Size; n++) - ImGui::TextUnformatted(g.SettingsHandlers[n].TypeName); + ImGui::BulletText("%s", g.SettingsHandlers[n].TypeName); ImGui::TreePop(); } if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) diff --git a/imgui.h b/imgui.h index bc056857..00ea2f3d 100644 --- a/imgui.h +++ b/imgui.h @@ -723,7 +723,7 @@ namespace ImGui IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); // Inputs Utilities: Keyboard - // - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[]. + // - For 'int user_key_index' you can use your own indices/enums according to how your back-end/engine stored them in io.KeysDown[]. // - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index. IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. @@ -1434,7 +1434,7 @@ struct ImGuiStyle 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. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. - ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. + ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors 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-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 647e4298..2acee763 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -228,8 +228,8 @@ void ImGui::ShowDemoWindow(bool* p_open) IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); // Examples Apps (accessible from the "Examples" menu) - static bool show_app_documents = false; static bool show_app_main_menu_bar = false; + static bool show_app_documents = false; static bool show_app_console = false; static bool show_app_log = false; static bool show_app_layout = false; @@ -241,8 +241,9 @@ 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); if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); + if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); + if (show_app_console) ShowExampleAppConsole(&show_app_console); if (show_app_log) ShowExampleAppLog(&show_app_log); if (show_app_layout) ShowExampleAppLayout(&show_app_layout); diff --git a/imgui_internal.h b/imgui_internal.h index ea135fce..e5d72c74 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -163,6 +163,10 @@ namespace ImStb #define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) #endif +// Debug Logging for selected systems. Remove the '((void)0) //' to enable. +//#define IMGUI_DEBUG_LOG_POPUP IMGUI_DEBUG_LOG // Enable log +#define IMGUI_DEBUG_LOG_POPUP(...) ((void)0) // Disable log + // Static Asserts #if (__cplusplus >= 201100) #define IM_STATIC_ASSERT(_COND) static_assert(_COND, "") From 76ddacd2a12f713a218116c849928ef2274d3f8b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 Jul 2020 15:26:31 +0200 Subject: [PATCH 158/223] Internals: Backport HoveredWindowUnderMovingWindow code from Docking branch. (effectively allowing a window to be a drag payload without have to make it _NoInputs) --- imgui.cpp | 29 +++++++++++++++++------------ imgui_internal.h | 2 ++ 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a74e96a5..28c975e2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3593,15 +3593,14 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. FindHoveredWindow(); - // Modal windows prevents cursor from hovering behind them. + // Modal windows prevents mouse from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); - if (modal_window) - if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) - g.HoveredRootWindow = g.HoveredWindow = NULL; + if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // Disabled mouse? if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) - g.HoveredWindow = g.HoveredRootWindow = NULL; + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward. int mouse_earliest_button_down = -1; @@ -3621,7 +3620,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) - g.HoveredWindow = g.HoveredRootWindow = NULL; + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // 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) @@ -3935,7 +3934,7 @@ void ImGui::Shutdown(ImGuiContext* context) g.CurrentWindowStack.clear(); g.WindowsById.Clear(); g.NavWindow = NULL; - g.HoveredWindow = g.HoveredRootWindow = NULL; + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; g.MovingWindow = NULL; g.ColorModifiers.clear(); @@ -4274,6 +4273,7 @@ static void FindHoveredWindow() ImGuiContext& g = *GImGui; ImGuiWindow* hovered_window = NULL; + ImGuiWindow* hovered_window_ignoring_moving_window = NULL; if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) hovered_window = g.MovingWindow; @@ -4306,16 +4306,17 @@ static void FindHoveredWindow() continue; } - // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches. if (hovered_window == NULL) hovered_window = window; - if (hovered_window) + if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow)) + hovered_window_ignoring_moving_window = window; + if (hovered_window && hovered_window_ignoring_moving_window) break; } g.HoveredWindow = hovered_window; g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; - + g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window; } // Test if mouse cursor is hovering given rectangle @@ -9145,6 +9146,7 @@ void ImGui::NavUpdateWindowingOverlay() PopStyleVar(); } + //----------------------------------------------------------------------------- // [SECTION] DRAG AND DROP //----------------------------------------------------------------------------- @@ -9334,7 +9336,8 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) return false; ImGuiWindow* window = g.CurrentWindow; - if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow) return false; IM_ASSERT(id != 0); if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) @@ -9362,7 +9365,8 @@ bool ImGui::BeginDragDropTarget() ImGuiWindow* window = g.CurrentWindow; if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; - if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow) return false; const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect; @@ -10584,6 +10588,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); diff --git a/imgui_internal.h b/imgui_internal.h index e5d72c74..317288a2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1136,6 +1136,7 @@ struct ImGuiContext ImGuiWindow* CurrentWindow; // Window being drawn into ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. 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; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; @@ -1342,6 +1343,7 @@ struct ImGuiContext CurrentWindow = NULL; HoveredWindow = NULL; HoveredRootWindow = NULL; + HoveredWindowUnderMovingWindow = NULL; MovingWindow = NULL; WheelingWindow = NULL; WheelingWindowTimer = 0.0f; From 5d87941451c8e0fc2ebf589b08b7e18cb13fd21b Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 2 Aug 2020 11:54:34 +0200 Subject: [PATCH 159/223] Fixed ImFontConfig::GlyphExtraSpacing and ImFontConfig::PixelSnapH settings being pulled from the merged/target font settings when merging fonts, instead of being pulled from the source font settings. --- docs/CHANGELOG.txt | 3 ++ imgui.h | 2 +- imgui_draw.cpp | 51 +++++++++++++++++++++----------- misc/freetype/imgui_freetype.cpp | 15 ++++------ 4 files changed, 44 insertions(+), 27 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c2850811..118813b7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,9 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- Fonts: Fixed ImFontConfig::GlyphExtraSpacing and ImFontConfig::PixelSnapH settings being pulled + from the merged/target font settings when merging fonts, instead of being pulled from the source + font settings. - ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - This change will facilitate the wider use of thick borders in future style changes. diff --git a/imgui.h b/imgui.h index 00ea2f3d..80dcf771 100644 --- a/imgui.h +++ b/imgui.h @@ -2386,7 +2386,7 @@ struct ImFont 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 AddGlyph(ImFontConfig* src_cfg, 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 SetGlyphVisible(ImWchar c, bool visible); IMGUI_API void SetFallbackChar(ImWchar c); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ad44b671..e9529e01 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2285,8 +2285,11 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) if (src_tmp.GlyphsCount == 0) continue; + // When merging fonts with MergeMode=true: + // - We can have multiple input fonts writing into a same destination font. + // - dst_font->ConfigData is != from cfg which is our source configuration. ImFontConfig& cfg = atlas->ConfigData[src_i]; - ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) + ImFont* dst_font = cfg.DstFont; const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels); int unscaled_ascent, unscaled_descent, unscaled_line_gap; @@ -2300,20 +2303,13 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) { + // Register glyph const int codepoint = src_tmp.GlyphsList[glyph_i]; const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i]; - - const float char_advance_x_org = pc.xadvance; - const float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX); - float char_off_x = font_off_x; - if (char_advance_x_org != char_advance_x_mod) - char_off_x += cfg.PixelSnapH ? ImFloor((char_advance_x_mod - char_advance_x_org) * 0.5f) : (char_advance_x_mod - char_advance_x_org) * 0.5f; - - // Register glyph stbtt_aligned_quad q; float dummy_x = 0.0f, dummy_y = 0.0f; stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &dummy_x, &dummy_y, &q, 0); - dst_font->AddGlyph((ImWchar)codepoint, q.x0 + char_off_x, q.y0 + font_off_y, q.x1 + char_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, char_advance_x_mod); + dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance); } } @@ -2468,10 +2464,11 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) if (r->Font == NULL || r->GlyphID == 0) continue; + // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, GlyphExtraSpacing, PixelSnapH IM_ASSERT(r->Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; atlas->CalcCustomRectUV(r, &uv0, &uv1); - r->Font->AddGlyph((ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); + r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX); } // Build all fonts lookup tables @@ -2881,8 +2878,29 @@ void ImFont::GrowIndex(int new_size) // x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero. // Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis). -void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +// 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font. +void ImFont::AddGlyph(ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) { + if (cfg != NULL) + { + // Clamp & recenter if needed + const float advance_x_original = advance_x; + advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX); + if (advance_x != advance_x_original) + { + float char_off_x = cfg->PixelSnapH ? ImFloor((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; + x0 += char_off_x; + x1 += char_off_x; + } + + // Snap to pixel + if (cfg->PixelSnapH) + advance_x = IM_ROUND(advance_x); + + // Bake spacing + advance_x += cfg->GlyphExtraSpacing.x; + } + Glyphs.resize(Glyphs.Size + 1); ImFontGlyph& glyph = Glyphs.back(); glyph.Codepoint = (unsigned int)codepoint; @@ -2895,14 +2913,13 @@ void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, glyph.V0 = v0; glyph.U1 = u1; glyph.V1 = v1; - glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX - - if (ConfigData->PixelSnapH) - glyph.AdvanceX = IM_ROUND(glyph.AdvanceX); + glyph.AdvanceX = advance_x; // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round) + // We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling. + float pad = ContainerAtlas->TexGlyphPadding + 0.99f; DirtyLookupTables = true; - MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f); + MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad); } void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index b76bc6e0..1a03be0c 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -544,8 +544,11 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns if (src_tmp.GlyphsCount == 0) continue; + // When merging fonts with MergeMode=true: + // - We can have multiple input fonts writing into a same destination font. + // - dst_font->ConfigData is != from cfg which is our source configuration. ImFontConfig& cfg = atlas->ConfigData[src_i]; - ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) + ImFont* dst_font = cfg.DstFont; const float ascent = src_tmp.Font.Info.Ascender; const float descent = src_tmp.Font.Info.Descender; @@ -576,14 +579,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns for (int y = info.Height; y > 0; y--, blit_dst += blit_dst_stride, blit_src += blit_src_stride) memcpy(blit_dst, blit_src, blit_src_stride); - float char_advance_x_org = info.AdvanceX; - float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX); - float char_off_x = font_off_x; - if (char_advance_x_org != char_advance_x_mod) - char_off_x += cfg.PixelSnapH ? IM_FLOOR((char_advance_x_mod - char_advance_x_org) * 0.5f) : (char_advance_x_mod - char_advance_x_org) * 0.5f; - // Register glyph - float x0 = info.OffsetX + char_off_x; + float x0 = info.OffsetX + font_off_x; float y0 = info.OffsetY + font_off_y; float x1 = x0 + info.Width; float y1 = y0 + info.Height; @@ -591,7 +588,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns float v0 = (ty) / (float)atlas->TexHeight; float u1 = (tx + info.Width) / (float)atlas->TexWidth; float v1 = (ty + info.Height) / (float)atlas->TexHeight; - dst_font->AddGlyph((ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, char_advance_x_mod); + dst_font->AddGlyph(&cfg, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX); } src_tmp.Rects = NULL; From a876ad877db800061ac87a370c41488d6f1a5fe1 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 18:04:58 +0200 Subject: [PATCH 160/223] Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. + comments --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 14 ++++++++++++-- imgui_internal.h | 7 ++++--- imgui_widgets.cpp | 3 +++ 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 118813b7..bd308f37 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,8 @@ Other Changes: - Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) +- Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) + from marking the window as moved. - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.cpp b/imgui.cpp index 28c975e2..2778bc32 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3061,10 +3061,13 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) return false; if (!IsMouseHoveringRect(bb.Min, bb.Max)) return false; - if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) + if (g.NavDisableMouseHover) return false; - if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) + if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None) || (window->DC.ItemFlags & ImGuiItemFlags_Disabled)) + { + g.HoveredIdDisabled = true; return false; + } // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level // hover test in widgets code. We could also decide to split this function is two. @@ -3364,9 +3367,15 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (root_window != NULL && !is_closed_popup) { StartMouseMovingWindow(g.HoveredWindow); + + // Cancel moving if clicked outside of title bar if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; + + // Cancel moving if clicked over an item which was disabled or inhibited by popups + if (g.HoveredId == 0 && g.HoveredIdDisabled) + g.MovingWindow = NULL; } else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { @@ -3723,6 +3732,7 @@ void ImGui::NewFrame() g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; + g.HoveredIdDisabled = false; // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore) if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) diff --git a/imgui_internal.h b/imgui_internal.h index 317288a2..f587637f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1144,8 +1144,9 @@ struct ImGuiContext // Item/widgets state and tracking information ImGuiID HoveredId; // Hovered widget - bool HoveredIdAllowOverlap; ImGuiID HoveredIdPreviousFrame; + bool HoveredIdAllowOverlap; + bool HoveredIdDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. float HoveredIdTimer; // Measure contiguous hovering time float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active ImGuiID ActiveId; // Active widget @@ -1348,9 +1349,9 @@ struct ImGuiContext WheelingWindow = NULL; WheelingWindowTimer = 0.0f; - HoveredId = 0; + HoveredId = HoveredIdPreviousFrame = 0; HoveredIdAllowOverlap = false; - HoveredIdPreviousFrame = 0; + HoveredIdDisabled = false; HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; ActiveId = 0; ActiveIdIsAlive = 0; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ecae7d0a..ee4d1a8a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -595,6 +595,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } } + // Process while held bool held = false; if (g.ActiveId == id) { @@ -615,6 +616,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0; if ((release_in || release_anywhere) && !g.DragDropActive) { + // Report as pressed when releasing the mouse (this is the most common path) bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[mouse_button]; bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps if (!is_double_click_release && !is_repeating_already) @@ -627,6 +629,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { + // When activated using Nav, we hold on the ActiveID until activation button is released if (g.NavActivateDownId != id) ClearActiveID(); } From 4929a8e4a5795ba2148a59621aa579f490b03427 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 18:37:19 +0200 Subject: [PATCH 161/223] InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) and allowed to pass them to InvisibleButton(). --- docs/CHANGELOG.txt | 5 +++++ docs/TODO.txt | 1 + imgui.cpp | 2 ++ imgui.h | 19 +++++++++++++++++-- imgui_internal.h | 43 ++++++++++++++++++------------------------- imgui_widgets.cpp | 6 +++--- 6 files changed, 46 insertions(+), 30 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bd308f37..ea67baa6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,11 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) + and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. + This is a small but rather important change because lots of multi-button behaviors could previously + only be achieved using lower-level/internal API. Now also available via high-level InvisibleButton() + with is a de-facto versatile building block to creating custom widgets with the public API. - Fonts: Fixed ImFontConfig::GlyphExtraSpacing and ImFontConfig::PixelSnapH settings being pulled from the merged/target font settings when merging fonts, instead of being pulled from the source font settings. diff --git a/docs/TODO.txt b/docs/TODO.txt index 9502e264..413301d0 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 - popups: clicking outside (to close popup) and holding shouldn't drag window below. - popups: add variant using global identifier similar to Begin/End (#402) - popups: border options. richer api like BeginChild() perhaps? (#197) + - popups: flags could be reworked to allow both mouse buttons as index (0..5 and as flags using higher-bit) allowing to or them. - popups/modals: although it is sometimes convenient that popups/modals lifetime is owned by imgui, we could also a bool-owned-by-user api as long as Begin() return value testing is enforced. - tooltip: drag and drop with tooltip near monitor edges lose/changes its last direction instead of locking one. The drag and drop tooltip should always follow without changing direction. diff --git a/imgui.cpp b/imgui.cpp index 2778bc32..efa38ffe 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4455,6 +4455,7 @@ bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button) return g.IO.MouseDoubleClicked[button]; } +// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame. // [Internal] This doesn't test if the button is pressed bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold) { @@ -7848,6 +7849,7 @@ void ImGui::EndPopup() g.WithinEndChild = false; } +// Open a popup if mouse is released over the item bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui.h b/imgui.h index 80dcf771..f3b28d74 100644 --- a/imgui.h +++ b/imgui.h @@ -153,6 +153,7 @@ typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: f typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() @@ -437,7 +438,7 @@ namespace ImGui // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. 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, frequently 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, ImGuiButtonFlags flags = 0); // flexible 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 @@ -446,7 +447,7 @@ namespace ImGui IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1, 0), const char* overlay = NULL); - IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses // Widgets: Combo Box // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. @@ -877,6 +878,7 @@ enum ImGuiTreeNodeFlags_ // small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. // It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. // - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. +// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). enum ImGuiPopupFlags_ { ImGuiPopupFlags_None = 0, @@ -1221,6 +1223,19 @@ enum ImGuiStyleVar_ #endif }; +// Flags for InvisibleButton() [extended in imgui_internal.h] +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default) + ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button + ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button + + // [Internal] + ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, + ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft +}; + // Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() enum ImGuiColorEditFlags_ { diff --git a/imgui_internal.h b/imgui_internal.h index f587637f..e0f8ae02 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -604,32 +604,25 @@ enum ImGuiItemStatusFlags_ #endif }; -enum ImGuiButtonFlags_ +// Extend ImGuiButtonFlags_ +enum ImGuiButtonFlagsPrivate_ { - ImGuiButtonFlags_None = 0, - ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat - ImGuiButtonFlags_PressedOnClick = 1 << 1, // return true on click (mouse down event) - ImGuiButtonFlags_PressedOnClickRelease = 1 << 2, // [Default] return true on click + release on same item <-- this is what the majority of Button are using - ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 3, // return true on click + release even if the release event is not done while hovering the item - ImGuiButtonFlags_PressedOnRelease = 1 << 4, // return true on release (default requires click+release) - ImGuiButtonFlags_PressedOnDoubleClick = 1 << 5, // return true on double-click (default requires click+release) - ImGuiButtonFlags_PressedOnDragDropHold = 1 << 6, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) - ImGuiButtonFlags_FlattenChildren = 1 << 7, // allow interactions even if a child window is overlapping - ImGuiButtonFlags_AllowItemOverlap = 1 << 8, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap() - ImGuiButtonFlags_DontClosePopups = 1 << 9, // disable automatically closing parent popup on press // [UNUSED] - ImGuiButtonFlags_Disabled = 1 << 10, // disable interactions - ImGuiButtonFlags_AlignTextBaseLine = 1 << 11, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine - ImGuiButtonFlags_NoKeyModifiers = 1 << 12, // disable mouse interaction if a key modifier is held - ImGuiButtonFlags_NoHoldingActiveId = 1 << 13, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) - ImGuiButtonFlags_NoNavFocus = 1 << 14, // don't override navigation focus when activated - ImGuiButtonFlags_NoHoveredOnFocus = 1 << 15, // don't report as hovered when nav focus is on this item - ImGuiButtonFlags_MouseButtonLeft = 1 << 16, // [Default] react on left mouse button - ImGuiButtonFlags_MouseButtonRight = 1 << 17, // react on right mouse button - ImGuiButtonFlags_MouseButtonMiddle = 1 << 18, // react on center mouse button - - ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, - ImGuiButtonFlags_MouseButtonShift_ = 16, - ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft, + ImGuiButtonFlags_PressedOnClick = 1 << 4, // return true on click (mouse down event) + ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, // [Default] return true on click + release on same item <-- this is what the majority of Button are using + ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item + ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release) + ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) + ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat + ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping + ImGuiButtonFlags_AllowItemOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap() + ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press // [UNUSED] + ImGuiButtonFlags_Disabled = 1 << 14, // disable interactions + ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + ImGuiButtonFlags_NoKeyModifiers = 1 << 16, // disable mouse interaction if a key modifier is held + ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) + ImGuiButtonFlags_NoNavFocus = 1 << 18, // don't override navigation focus when activated + ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ee4d1a8a..8e8bfca9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -685,7 +685,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags bool ImGui::Button(const char* label, const ImVec2& size_arg) { - return ButtonEx(label, size_arg, 0); + return ButtonEx(label, size_arg, ImGuiButtonFlags_None); } // Small buttons fits within text without additional vertical spacing. @@ -701,7 +701,7 @@ bool ImGui::SmallButton(const char* label) // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) -bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -718,7 +718,7 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held); + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); return pressed; } From 912c45ab232754ad7fe016efa880b1a066db8965 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 19:13:42 +0200 Subject: [PATCH 162/223] Demo: Improve "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. --- docs/CHANGELOG.txt | 2 + imgui_demo.cpp | 117 ++++++++++++++++++++++++++++++--------------- 2 files changed, 80 insertions(+), 39 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ea67baa6..70acf40c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,8 @@ Other Changes: by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] +- Demo: Improve "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. + Also showcase using InvisibleButton() will multiple mouse buttons flags. - Demo: Tweak "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2acee763..0ce046c5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4859,13 +4859,13 @@ static void ShowExampleAppCustomRendering(bool* p_open) // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not // exposed outside (to avoid messing with your types) In this example we are not using the maths operators! - ImDrawList* draw_list = ImGui::GetWindowDrawList(); if (ImGui::BeginTabBar("##TabBar")) { if (ImGui::BeginTabItem("Primitives")) { ImGui::PushItemWidth(-ImGui::GetFontSize() * 10); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); // Draw gradients // (note that those are currently exacerbating our sRGB/Linear issues) @@ -4949,56 +4949,95 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::BeginTabItem("Canvas")) { - static ImVector points; + struct ItemLine { ImVec2 p0, p1; ItemLine(const ImVec2& _p0, const ImVec2& _p1) { p0 = _p0; p1 = _p1; } }; + static ImVector lines; + static ImVec2 scrolling(0.0f, 0.0f); + static bool show_grid = true; 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 with SetCursorPos(max). - ImVec2 canvas_p = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + + ImGui::Checkbox("Show grid", &show_grid); + ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu."); + + // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. + // Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls. + // To use a child window instead we could use, e.g: + // ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding + // ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color + // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_NoMove); + // ImGui::PopStyleColor(); + // ImGui::PopStyleVar(); + // [...] + // ImGui::EndChild(); + + // Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive() + ImVec2 canvas_p0 = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f; if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f; - draw_list->AddRectFilledMultiColor(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.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_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), IM_COL32(255, 255, 255, 255)); + ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y); - bool adding_preview = false; - ImGui::InvisibleButton("canvas", canvas_sz); - ImVec2 mouse_pos_global = ImGui::GetIO().MousePos; - ImVec2 mouse_pos_canvas = ImVec2(mouse_pos_global.x - canvas_p.x, mouse_pos_global.y - canvas_p.y); + // Draw border and background color + ImGuiIO& io = ImGui::GetIO(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255)); + draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255)); + + // This will catch our interactions + ImGui::InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight); + const bool is_hovered = ImGui::IsItemHovered(); // Hovered + const bool is_active = ImGui::IsItemActive(); // Held + const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin + const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y); + + // Add first and second point + if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + lines.push_back(ItemLine(mouse_pos_in_canvas, mouse_pos_in_canvas)); + adding_line = true; + } if (adding_line) { - adding_preview = true; - points.push_back(mouse_pos_canvas); - if (!ImGui::IsMouseDown(0)) - adding_line = adding_preview = false; + lines.back().p1 = mouse_pos_in_canvas; + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) + adding_line = false; } - if (ImGui::IsItemHovered()) + + // Pan (using zero mouse threshold) + if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, 0.0f)) { - if (!adding_line && ImGui::IsMouseClicked(0)) - { - points.push_back(mouse_pos_canvas); - adding_line = true; - } - if (ImGui::IsMouseClicked(1) && !points.empty()) - { - adding_line = adding_preview = false; - points.pop_back(); - points.pop_back(); - } + scrolling.x += io.MouseDelta.x; + scrolling.y += io.MouseDelta.y; } - // Draw all lines in the canvas (with a clipping rectangle so they don't stray out of it). - draw_list->PushClipRect(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), true); - for (int i = 0; i < points.Size - 1; i += 2) - draw_list->AddLine(ImVec2(canvas_p.x + points[i].x, canvas_p.y + points[i].y), ImVec2(canvas_p.x + points[i + 1].x, canvas_p.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); + // Context menu (under default mouse threshold) + // We intentionally use the same button to demonstrate using mouse drag threshold. Some may feel panning should rely on same threshold. + ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); + if (drag_delta.x == 0.0f && drag_delta.y == 0.0f) + ImGui::OpenPopupContextItem("context"); + if (ImGui::BeginPopup("context")) + { + if (adding_line) + lines.pop_back(); + adding_line = false; + if (ImGui::MenuItem("Remove one", NULL, false, lines.Size > 0)) { lines.pop_back(); } + if (ImGui::MenuItem("Remove all", NULL, false, lines.Size > 0)) { lines.clear(); } + ImGui::EndPopup(); + } + + // Draw grid + all lines in the canvas + draw_list->PushClipRect(canvas_p0, canvas_p1, true); + if (show_grid) + { + const float GRID_STEP = 64.0f; + for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40)); + for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40)); + } + for (int n = 0; n < lines.Size; n++) + draw_list->AddLine(ImVec2(origin.x + lines[n].p0.x, origin.y + lines[n].p0.y), ImVec2(origin.x + lines[n].p1.x, origin.y + lines[n].p1.y), IM_COL32(255, 255, 0, 255), 2.0f); draw_list->PopClipRect(); - if (adding_preview) - points.pop_back(); + ImGui::EndTabItem(); } From 55041ac3bee2e7ac4e024103e3aa4555233f814a Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 19:25:41 +0200 Subject: [PATCH 163/223] Demo: Removed thin triangle and aligned code. --- imgui_demo.cpp | 55 ++++++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0ce046c5..774968eb 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4869,21 +4869,22 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Draw gradients // (note that those are currently exacerbating our sRGB/Linear issues) + // Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well.. ImGui::Text("Gradients"); ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); { ImVec2 p0 = ImGui::GetCursorScreenPos(); ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); - ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); - ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255)); draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient1", gradient_size); } { ImVec2 p0 = ImGui::GetCursorScreenPos(); ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); - ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)); - ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255)); draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient2", gradient_size); } @@ -4904,6 +4905,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::SliderInt("Circle segments", &circle_segments_override_v, 3, 40)) circle_segments_override = true; ImGui::ColorEdit4("Color", &colf.x); + const ImVec2 p = ImGui::GetCursorScreenPos(); const ImU32 col = ImColor(colf); const float spacing = 10.0f; @@ -4911,38 +4913,39 @@ static void ShowExampleAppCustomRendering(bool* p_open) const ImDrawCornerFlags corners_all = ImDrawCornerFlags_All; const ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight; const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; - float x = p.x + 4.0f, y = p.y + 4.0f; + float x = p.x + 4.0f; + float y = p.y + 4.0f; for (int n = 0; n < 2; n++) { // First line uses a thickness of 1.0f, second line uses the configurable thickness float th = (n == 0) ? 1.0f : thickness; - draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle - draw_list->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->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle + draw_list->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->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides); x += sz + spacing; // N-gon - draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments);x += sz + spacing; // Circle - draw_list->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->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides); x += sz + spacing; // N-gon + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments); x += sz + spacing; // Circle + draw_list->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.8f, (sz + spacing) * 3)); + ImGui::Dummy(ImVec2((sz + spacing) * 8.8f, (sz + spacing) * 3.0f)); ImGui::PopItemWidth(); ImGui::EndTabItem(); } From 963839373cf376b29eb1a5b990cccd40b50d75f3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 21:19:12 +0200 Subject: [PATCH 164/223] Demo tweaks + general removal of the word dummy were possible with no issues (kept the API call). --- docs/CHANGELOG.txt | 8 ++-- docs/FAQ.md | 10 ++--- docs/TODO.txt | 1 - examples/example_null/main.cpp | 2 +- examples/imgui_impl_opengl3.cpp | 6 +-- imgui.cpp | 20 +++++----- imgui.h | 14 +++---- imgui_demo.cpp | 67 +++++++++++++++++---------------- imgui_draw.cpp | 4 +- imgui_widgets.cpp | 11 +++--- 10 files changed, 73 insertions(+), 70 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70acf40c..bdc30ccb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -573,7 +573,7 @@ Other Changes: 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. +- Backends: SDL2: Added ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. (#2482, #2632) [@josiahmanson] - Examples: Added SDL2+DirectX11 example application. (#2632, #2612, #2482) [@vincenthamm] @@ -733,7 +733,7 @@ Other Changes: - 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 +- Examples: OpenGL: Added a test GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - 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] @@ -841,7 +841,7 @@ 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! + If for some reason your time step calculation gives you a zero value, replace it with a arbitrary small value! Other Changes: @@ -1332,7 +1332,7 @@ Other Changes: - 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) -- Fonts: When building font atlas, glyphs that are missing in the fonts are not using the glyph slot to render a dummy/default glyph. Saves space and allow merging fonts with +- Fonts: When building font atlas, glyphs that are missing in the fonts are not using the glyph slot to render the default glyph. Saves space and allow merging fonts with overlapping font ranges such as FontAwesome5 which split out the Brands separately from the Solid fonts. (#1703, #1671) - Misc: Added IMGUI_CHECKVERSION() macro to compare version string and data structure sizes in order to catch issues with mismatching compilation unit settings. (#1695, #1769) - Misc: Added IMGUI_DISABLE_MATH_FUNCTIONS in imconfig.h to make it easier to redefine wrappers for std/crt math functions. diff --git a/docs/FAQ.md b/docs/FAQ.md index adce4d40..b5fbcc90 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -111,11 +111,11 @@ e.g. `if (ImGui::GetIO().WantCaptureMouse) { ... }` **Note:** You should always pass your mouse/keyboard inputs to Dear ImGui, even when the io.WantCaptureXXX flag are set false. This is because imgui needs to detect that you clicked in the void to unfocus its own windows. -**Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs. +**Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs. -**Note:** Those flags are updated by `ImGui::NewFrame()`. However it is generally more correct and easier that you poll flags from the previous frame, then submit your inputs, then call `NewFrame()`. If you attempt to do the opposite (which is generally harder) you are likely going to submit your inputs after `NewFrame()`, and therefore too late. +**Note:** Those flags are updated by `ImGui::NewFrame()`. However it is generally more correct and easier that you poll flags from the previous frame, then submit your inputs, then call `NewFrame()`. If you attempt to do the opposite (which is generally harder) you are likely going to submit your inputs after `NewFrame()`, and therefore too late. -**Note:** If you are using a touch device, you may find use for an early call to `UpdateHoveredWindowAndCaptureFlags()` to correctly dispatch your initial touch. We will work on better out-of-the-box touch support in the future. +**Note:** If you are using a touch device, you may find use for an early call to `UpdateHoveredWindowAndCaptureFlags()` to correctly dispatch your initial touch. We will work on better out-of-the-box touch support in the future. **Note:** Text input widget releases focus on the "KeyDown" event of the Return key, so the subsequent "KeyUp" event that your application receive will typically have `io.WantCaptureKeyboard == false`. Depending on your application logic it may or not be inconvenient to receive that KeyUp event. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.) @@ -453,7 +453,7 @@ ImGui::End(); - To generate colors: you can use the macro `IM_COL32(255,255,255,255)` to generate them at compile time, or use `ImGui::GetColorU32(IM_COL32(255,255,255,255))` or `ImGui::GetColorU32(ImVec4(1.0f,1.0f,1.0f,1.0f))` to generate a color that is multiplied by the current value of `style.Alpha`. - Math operators: if you have setup `IM_VEC2_CLASS_EXTRA` in `imconfig.h` to bind your own math types, you can use your own math types and their natural operators instead of ImVec2. ImVec2 by default doesn't export any math operators in the public API. You may use `#define IMGUI_DEFINE_MATH_OPERATORS` `#include "imgui_internal.h"` to use the internally defined math operators, but instead prefer using your own math library and set it up in `imconfig.h`. - You can use `ImGui::GetBackgroundDrawList()` or `ImGui::GetForegroundDrawList()` to access draw lists which will be displayed behind and over every other dear imgui windows (one bg/fg drawlist per viewport). This is very convenient if you need to quickly display something on the screen that is not associated to a dear imgui window. -- You can also create your own dummy window and draw inside it. 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 also create your own empty window and draw inside it. 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 create your own ImDrawList instance. You'll need to initialize them with `ImGui::GetDrawListSharedData()`, or create your own instancing ImDrawListSharedData, and then call your renderer function with your own ImDrawList or ImDrawData data. ##### [Return to Index](#index) @@ -464,7 +464,7 @@ ImGui::End(); ### Q: How should I handle DPI in my application? -The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. +The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. Your application may want to detect DPI change and reload the font and reset style being frames. diff --git a/docs/TODO.txt b/docs/TODO.txt index 413301d0..9d9ea950 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -365,7 +365,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - 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: no way to run a root-most GetID() with ImGui:: api since there's always a Debug window in the stack. (mentioned in #2960) - 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) diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index aa2f6dba..72381f0a 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -1,4 +1,4 @@ -// dear imgui: null/dummy example application +// dear imgui: "null" 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" diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index cb60304d..21e8852b 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -25,7 +25,7 @@ // 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. +// 2019-03-15: OpenGL: Added a 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. @@ -179,7 +179,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) strcpy(g_GlslVersionString, glsl_version); strcat(g_GlslVersionString, "\n"); - // Dummy construct to make it easily visible in the IDE and debugger which GL loader has been selected. + // Debugging construct to make it easily visible in the IDE and debugger which GL loader has been selected. // The code actually never uses the 'gl_loader' variable! It is only here so you can read it! // If auto-detection fails or doesn't select the same GL loader file as used by your application, // you are likely to get a crash below. @@ -204,7 +204,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) gl_loader = "none"; #endif - // Make a dummy GL call (we don't actually need the result) + // Make an arbitrary 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; diff --git a/imgui.cpp b/imgui.cpp index efa38ffe..057001ba 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -417,7 +417,7 @@ CODE - 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! + - 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 an arbitrary 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. Kept redirection typedef (will obsolete). @@ -1663,8 +1663,8 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) // Not optimal but we very rarely use this function. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end) { - unsigned int dummy = 0; - return ImTextCharFromUtf8(&dummy, in_text, in_text_end); + unsigned int unused = 0; + return ImTextCharFromUtf8(&unused, in_text, in_text_end); } static inline int ImTextCountUtf8BytesFromChar(unsigned int c) @@ -2160,7 +2160,7 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items *out_items_display_end = end; } -static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) +static void SetCursorPosYAndSetupForPrevLine(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. @@ -2192,7 +2192,7 @@ void ImGuiListClipper::Begin(int count, float items_height) { ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display if (DisplayStart > 0) - SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor + SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor StepNo = 2; } } @@ -2203,7 +2203,7 @@ void ImGuiListClipper::End() return; // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX) - SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; StepNo = 3; } @@ -2237,7 +2237,7 @@ bool ImGuiListClipper::Step() StepNo = 3; return true; } - if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + if (StepNo == 2) // Step 2: empty step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. { IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); StepNo = 3; @@ -3040,7 +3040,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 calling 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; @@ -4728,7 +4728,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, b { FocusWindow(child_window); NavInitWindow(child_window, false); - SetActiveID(id + 1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item + SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item g.ActiveIdSource = ImGuiInputSource_Nav; } return ret; @@ -7849,7 +7849,7 @@ void ImGui::EndPopup() g.WithinEndChild = false; } -// Open a popup if mouse is released over the item +// Open a popup if mouse button is released over the item bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui.h b/imgui.h index f3b28d74..40fa6cc8 100644 --- a/imgui.h +++ b/imgui.h @@ -1330,16 +1330,16 @@ enum ImGuiCond_ // 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. +// Defining a custom placement new() with a custom 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() +struct ImNewWrapper {}; +inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewWrapper, 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 +#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR) +#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } //----------------------------------------------------------------------------- @@ -1843,7 +1843,7 @@ struct ImGuiStorage // ImGui::Text("line number %d", i); // - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). // - 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. -// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) +// - (Step 2: empty step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) // - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. struct ImGuiListClipper { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 774968eb..e267872f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1243,7 +1243,7 @@ static void ShowDemoWindowWidgets() static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); - // Create a dummy array of contiguous float values to plot + // Fill an array of contiguous float values to plot // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float // and the sizeof() of your structure in the "stride" parameter. static float values[90] = {}; @@ -1251,7 +1251,7 @@ static void ShowDemoWindowWidgets() static double refresh_time = 0.0; if (!animate || refresh_time == 0.0) refresh_time = ImGui::GetTime(); - while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 Hz rate for the demo + while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo { static float phase = 0.0f; values[values_offset] = cosf(phase); @@ -1351,7 +1351,7 @@ static void ShowDemoWindowWidgets() ImGui::Text("Color button with Custom Picker Popup:"); - // Generate a dummy default palette. The palette will persist and can be edited. + // Generate a default palette. The palette will persist and can be edited. static bool saved_palette_init = true; static ImVec4 saved_palette[32] = {}; if (saved_palette_init) @@ -1932,8 +1932,8 @@ 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); + static char unused_str[] = "This widget is only here to be able to tab-out of the widgets above."; + ImGui::InputText("unused", unused_str, IM_ARRAYSIZE(unused_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 associated to the title bar of a window. @@ -2376,7 +2376,7 @@ static void ShowDemoWindowLayout() ImGui::SameLine(0.0f, spacing); if (ImGui::TreeNode("Node##1")) { - // Dummy tree data + // Placeholder tree data for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); @@ -2392,7 +2392,7 @@ static void ShowDemoWindowLayout() ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); if (node_open) { - // Dummy tree data + // Placeholder tree data for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); @@ -2693,7 +2693,7 @@ static void ShowDemoWindowLayout() ImGui::TextWrapped("(Click and drag)"); ImVec2 pos = ImGui::GetCursorScreenPos(); ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); - ImGui::InvisibleButton("##dummy", size); + ImGui::InvisibleButton("##empty", size); if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) { offset.x += ImGui::GetIO().MouseDelta.x; @@ -2869,8 +2869,8 @@ static void ShowDemoWindowPopups() ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); ImGui::Separator(); - //static int dummy_i = 0; - //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0"); + //static int unused_i = 0; + //ImGui::Combo("Combo", &unused_i, "Delete\0Delete harder\0"); static bool dont_ask_me_next_time = false; ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); @@ -2892,7 +2892,7 @@ static void ShowDemoWindowPopups() { if (ImGui::BeginMenu("File")) { - if (ImGui::MenuItem("Dummy menu item")) {} + if (ImGui::MenuItem("Some menu item")) {} ImGui::EndMenu(); } ImGui::EndMenuBar(); @@ -2911,8 +2911,8 @@ static void ShowDemoWindowPopups() // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value // of the bool actually doesn't matter here. - bool dummy_open = true; - if (ImGui::BeginPopupModal("Stacked 2", &dummy_open)) + bool unused_open = true; + if (ImGui::BeginPopupModal("Stacked 2", &unused_open)) { ImGui::Text("Hello from Stacked The Second!"); if (ImGui::Button("Close")) @@ -3247,7 +3247,7 @@ static void ShowDemoWindowMisc() if (ImGui::TreeNode("Tabbing")) { ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); - static char buf[32] = "dummy"; + static char buf[32] = "hello"; ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); @@ -3903,7 +3903,7 @@ static void ShowExampleAppMainMenuBar() // (future version will add explicit flags to BeginMenu() to request processing shortcuts) static void ShowExampleMenuFile() { - ImGui::MenuItem("(dummy menu)", NULL, false, false); + ImGui::MenuItem("(demo menu)", NULL, false, false); if (ImGui::MenuItem("New")) {} if (ImGui::MenuItem("Open", "Ctrl+O")) {} if (ImGui::BeginMenu("Open Recent")) @@ -4067,8 +4067,8 @@ 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 Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); 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); } @@ -4558,7 +4558,7 @@ static void ShowExampleAppLayout(bool* p_open) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- -static void ShowDummyObject(const char* prefix, int uid) +static void ShowPlaceholderObject(const char* prefix, int uid) { // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. ImGui::PushID(uid); @@ -4570,13 +4570,13 @@ static void ShowDummyObject(const char* prefix, int uid) ImGui::NextColumn(); if (node_open) { - static float dummy_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; + static float placeholder_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; for (int i = 0; i < 8; i++) { ImGui::PushID(i); // Use field index as identifier. if (i < 2) { - ShowDummyObject("Child", 424242); + ShowPlaceholderObject("Child", 424242); } else { @@ -4587,9 +4587,9 @@ static void ShowDummyObject(const char* prefix, int uid) ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); if (i >= 5) - ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + ImGui::InputFloat("##value", &placeholder_members[i], 1.0f); else - ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::DragFloat("##value", &placeholder_members[i], 0.01f); ImGui::NextColumn(); } ImGui::PopID(); @@ -4619,9 +4619,9 @@ static void ShowExampleAppPropertyEditor(bool* p_open) ImGui::Columns(2); ImGui::Separator(); - // Iterate dummy objects with dummy members (all the same data) + // Iterate placeholder objects (all the same data) for (int obj_i = 0; obj_i < 3; obj_i++) - ShowDummyObject("Object", obj_i); + ShowPlaceholderObject("Object", obj_i); ImGui::Columns(1); ImGui::Separator(); @@ -4955,10 +4955,12 @@ static void ShowExampleAppCustomRendering(bool* p_open) struct ItemLine { ImVec2 p0, p1; ItemLine(const ImVec2& _p0, const ImVec2& _p1) { p0 = _p0; p1 = _p1; } }; static ImVector lines; static ImVec2 scrolling(0.0f, 0.0f); - static bool show_grid = true; + static bool opt_enable_grid = true; + static bool opt_enable_context_menu = true; static bool adding_line = false; - ImGui::Checkbox("Show grid", &show_grid); + ImGui::Checkbox("Enable grid", &opt_enable_grid); + ImGui::Checkbox("Enable context menu", &opt_enable_context_menu); ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu."); // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. @@ -5005,17 +5007,18 @@ static void ShowExampleAppCustomRendering(bool* p_open) adding_line = false; } - // Pan (using zero mouse threshold) - if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, 0.0f)) + // Pan (we use a zero mouse threshold when there's no context menu) + // You may decide to make that threshold dynamic based on whether the mouse is hovering something etc. + const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f; + if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan)) { scrolling.x += io.MouseDelta.x; scrolling.y += io.MouseDelta.y; } // Context menu (under default mouse threshold) - // We intentionally use the same button to demonstrate using mouse drag threshold. Some may feel panning should rely on same threshold. ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); - if (drag_delta.x == 0.0f && drag_delta.y == 0.0f) + if (opt_enable_context_menu && ImGui::IsMouseReleased(ImGuiMouseButton_Right) && drag_delta.x == 0.0f && drag_delta.y == 0.0f) ImGui::OpenPopupContextItem("context"); if (ImGui::BeginPopup("context")) { @@ -5029,7 +5032,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Draw grid + all lines in the canvas draw_list->PushClipRect(canvas_p0, canvas_p1, true); - if (show_grid) + if (opt_enable_grid) { const float GRID_STEP = 64.0f; for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP) @@ -5095,7 +5098,7 @@ struct MyDocument void DoForceClose() { Open = false; Dirty = false; } void DoSave() { Dirty = false; } - // Display dummy contents for the Document + // Display placeholder contents for the Document static void DisplayContents(MyDocument* doc) { ImGui::PushID(doc); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e9529e01..890c0c2c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2307,8 +2307,8 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) const int codepoint = src_tmp.GlyphsList[glyph_i]; const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i]; stbtt_aligned_quad q; - float dummy_x = 0.0f, dummy_y = 0.0f; - stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &dummy_x, &dummy_y, &q, 0); + float unused_x = 0.0f, unused_y = 0.0f; + stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0); dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance); } } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8e8bfca9..55dc6433 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5205,9 +5205,9 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask); SetCursorScreenPos(backup_pos); - ImVec4 dummy_ref_col; - memcpy(&dummy_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4)); - ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags); + ImVec4 previewing_ref_col; + memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4)); + ColorPicker4("##previewing_picker", &previewing_ref_col.x, picker_flags); PopID(); } PopItemWidth(); @@ -5679,7 +5679,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags // - Selectable() //------------------------------------------------------------------------- -// Tip: pass a non-visible label (e.g. "##dummy") then you can use the space to draw other text or image. +// Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. // With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowItemOverlap are also frequently used flags. // FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. @@ -7121,7 +7121,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, const ImGuiStyle& style = g.Style; const ImGuiID id = TabBarCalcTabID(tab_bar, label); - // If the user called us with *p_open == false, we early out and don't render. We make a dummy call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. + // If the user called us with *p_open == false, we early out and don't render. + // We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); if (p_open && !*p_open) { From db886f395372d9e313758933d96ab63767fa8701 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 4 Aug 2020 12:05:15 +0200 Subject: [PATCH 165/223] Demo: Rework Clipping section. Fix for static analysis. Added bindings in Readme. --- docs/CHANGELOG.txt | 5 ++-- docs/README.md | 4 +-- docs/TODO.txt | 2 ++ imgui.cpp | 4 +-- imgui_demo.cpp | 71 +++++++++++++++++++++++++++++++++++++--------- 5 files changed, 66 insertions(+), 20 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bdc30ccb..ec58fce5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,9 +68,10 @@ Other Changes: by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] -- Demo: Improve "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. +- Demo: Improved "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. Also showcase using InvisibleButton() will multiple mouse buttons flags. -- Demo: Tweak "Child Windows" section. +- Demo: Improved "Layout & Scrolling" -> "Clipping" section. +- Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] diff --git a/docs/README.md b/docs/README.md index a0ca6483..9579ee22 100644 --- a/docs/README.md +++ b/docs/README.md @@ -113,8 +113,8 @@ Officially maintained bindings (in repository): - Frameworks: Emscripten, Allegro5, Marmalade. Third-party bindings (see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings/) page): -- Languages: C, C#/.Net, ChaiScript, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... -- Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. +- Languages: C, C# and: Beef, ChaiScript, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... +- Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. - Note that C bindings ([cimgui](https://github.com/cimgui/cimgui)) are auto-generated, you can use its json/lua output to generate bindings for other languages. Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. diff --git a/docs/TODO.txt b/docs/TODO.txt index 9d9ea950..a96693b3 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -393,6 +393,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - backends: bgfx: https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - backends: mscriptem: 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) + - bindings: ways to use clang ast dump to generate bindings or helpers for bindings? (e.g. clang++ -Xclang -ast-dump=json imgui.h) + - optimization: replace vsnprintf with stb_printf? using IMGUI_USE_STB_SPRINTF.(#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 057001ba..ab41ba10 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3373,8 +3373,8 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; - // Cancel moving if clicked over an item which was disabled or inhibited by popups - if (g.HoveredId == 0 && g.HoveredIdDisabled) + // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already) + if (g.HoveredIdDisabled) g.MovingWindow = NULL; } else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e267872f..b04c7db6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2684,23 +2684,66 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Clipping")) { - static ImVec2 size(100, 100), offset(50, 20); - ImGui::TextWrapped( - "On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. " - "Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. " - "The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + static ImVec2 size(100.0f, 100.0f); + static ImVec2 offset(30.0f, 30.0f); ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); - ImGui::TextWrapped("(Click and drag)"); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); - ImGui::InvisibleButton("##empty", size); - if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) + ImGui::TextWrapped("(Click and drag to scroll)"); + + for (int n = 0; n < 3; n++) { - offset.x += ImGui::GetIO().MouseDelta.x; - offset.y += ImGui::GetIO().MouseDelta.y; + if (n > 0) + ImGui::SameLine(); + ImGui::PushID(n); + ImGui::BeginGroup(); // Lock X position + + ImGui::InvisibleButton("##empty", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + offset.x += ImGui::GetIO().MouseDelta.x; + offset.y += ImGui::GetIO().MouseDelta.y; + } + const ImVec2 p0 = ImGui::GetItemRectMin(); + const ImVec2 p1 = ImGui::GetItemRectMax(); + const char* text_str = "Line 1 hello\nLine 2 clip me!"; + const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + switch (n) + { + case 0: + HelpMarker( + "Using ImGui::PushClipRect():\n" + "Will alter ImGui hit-testing logic + ImDrawList rendering.\n" + "(use this if you want your clipping rectangle to affect interactions)"); + ImGui::PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + ImGui::PopClipRect(); + break; + case 1: + HelpMarker( + "Using ImDrawList::PushClipRect():\n" + "Will alter ImDrawList rendering only.\n" + "(use this as a shortcut if you are only using ImDrawList calls)"); + draw_list->PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + draw_list->PopClipRect(); + break; + case 2: + HelpMarker( + "Using ImDrawList::AddText() with a fine ClipRect:\n" + "Will alter only this specific ImDrawList::AddText() rendering.\n" + "(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)"); + ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert. + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect); + break; + } + ImGui::EndGroup(); + ImGui::PopID(); } - ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x + size.x, pos.y + size.y), IM_COL32(90, 90, 120, 255)); - ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x + offset.x, pos.y + offset.y), IM_COL32_WHITE, "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::TreePop(); } } From a24578ec094b51f739dd788b53028c411c55a3eb Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 14:58:44 +0200 Subject: [PATCH 166/223] Examples: Switch most VS projects to enable Edit & Continue by default (may need to upgrade projects to latest toolchain) --- examples/example_allegro5/example_allegro5.vcxproj | 1 + examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj | 1 + examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj | 1 + examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj | 1 + examples/example_glut_opengl2/example_glut_opengl2.vcxproj | 1 + examples/example_sdl_directx11/example_sdl_directx11.vcxproj | 1 + examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj | 3 ++- examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj | 1 + examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj | 1 + .../example_win32_directx10/example_win32_directx10.vcxproj | 1 + .../example_win32_directx11/example_win32_directx11.vcxproj | 1 + examples/example_win32_directx9/example_win32_directx9.vcxproj | 1 + 12 files changed, 13 insertions(+), 1 deletion(-) diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index c86dcb2b..ace88555 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index b265fea0..5cb59b87 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 47d25380..3d670bf5 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index 9e2c9b38..65458eb9 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index 9a239516..ac8f6a76 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled $(GLUT_INCLUDE_DIR);..\..;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj index 804bd500..b32034e5 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -106,6 +106,7 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index 83a6a8a0..8bba2071 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -19,7 +19,7 @@ - {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} + {4168B148-B7DE-4A31-8497-19AFA6B83360} example_sdl_opengl2 8.1 @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj index 54aaa796..c516c999 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj index ac701a2a..8a6eab4c 100644 --- a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj +++ b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 5c3aa69f..6182b687 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -100,6 +100,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); + EditAndContinue true diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index bcb71bc4..3e4db23e 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -99,6 +99,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); + EditAndContinue true diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index 25bdd859..cf944ae5 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -100,6 +100,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + EditAndContinue true From 473a01adb0c334dc4c7f6432cc55098a9e6ac2d6 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 17:09:40 +0200 Subject: [PATCH 167/223] Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll limits. (#3379) + Demo: Rename "Layout" to "Layout & Scrolling". --- docs/CHANGELOG.txt | 4 +++ imgui.cpp | 66 ++++++++++++++++++++++++++++------------------ imgui.h | 4 +-- imgui_demo.cpp | 8 +++--- 4 files changed, 49 insertions(+), 33 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ec58fce5..7cc16314 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,10 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll + limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many + side-effects. The behavior is still present in SetScrollHere functions as they are more explicitly + aiming at making widgets visible. May later be moved to a flag. - InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. This is a small but rather important change because lots of multi-button behaviors could previously diff --git a/imgui.cpp b/imgui.cpp index ab41ba10..e6d7f61d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -805,7 +805,7 @@ static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock static void SetCurrentWindow(ImGuiWindow* window); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); -static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list); static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window); @@ -5819,7 +5819,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) 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->Scroll = CalcNextScrollFromScrollTargetAndClamp(window); window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); // DRAWING @@ -7325,30 +7325,20 @@ void ImGui::EndGroup() // [SECTION] SCROLLING //----------------------------------------------------------------------------- -static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) { - 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->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->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height); } scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f)); @@ -7380,7 +7370,7 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_ 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); + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); delta_scroll = next_scroll - window->Scroll; } @@ -7441,10 +7431,10 @@ void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) window->ScrollTargetCenterRatio.y = 0.0f; } - +// Note that a local position will vary depending on initial scroll value +// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size 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 IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); window->ScrollTargetCenterRatio.x = center_x_ratio; @@ -7452,10 +7442,8 @@ void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x 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 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; + local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); window->ScrollTargetCenterRatio.y = center_y_ratio; } @@ -7472,15 +7460,34 @@ void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio); } +// Tweak: snap on edges when aiming at an item very close to the edge, +// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +// When we refactor the scrolling API this may be configurable with a flag? +// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. +static float CalcScrollSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio) +{ + if (target <= snap_min + snap_threshold) + return ImLerp(snap_min, target, center_ratio); + if (target >= snap_max - snap_threshold) + return ImLerp(target, snap_max, center_ratio); + return target; +} + // 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); + float spacing_x = g.Style.ItemSpacing.x; + float target_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio); + + // Tweak: snap on edges when aiming at an item very close to the edge + const float snap_x_threshold = ImMax(0.0f, window->WindowPadding.x - spacing_x); + const float snap_x_min = window->DC.CursorStartPos.x - window->WindowPadding.x; + const float snap_x_max = window->DC.CursorStartPos.x + window->ContentSize.x + window->WindowPadding.x; + target_x = CalcScrollSnap(target_x, snap_x_min, snap_x_max, snap_x_threshold, center_x_ratio); + + SetScrollFromPosX(window, target_x - window->Pos.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. @@ -7488,9 +7495,16 @@ 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); + float spacing_y = g.Style.ItemSpacing.y; + float target_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); + + // Tweak: snap on edges when aiming at an item very close to the edge + const float snap_y_threshold = ImMax(0.0f, window->WindowPadding.y - spacing_y); + const float snap_y_min = window->DC.CursorStartPos.y - window->WindowPadding.y; + const float snap_y_max = window->DC.CursorStartPos.y + window->ContentSize.y + window->WindowPadding.y; + target_y = CalcScrollSnap(target_y, snap_y_min, snap_y_max, snap_y_threshold, center_y_ratio); + + SetScrollFromPosY(window, target_y - window->Pos.y, center_y_ratio); } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 40fa6cc8..c135ada2 100644 --- a/imgui.h +++ b/imgui.h @@ -333,8 +333,8 @@ namespace ImGui // Windows Scrolling IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] - IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X - IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x + 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. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b04c7db6..bc4cd1c2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2490,11 +2490,9 @@ static void ShowDemoWindowLayout() ImGui::Spacing(); HelpMarker( "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" - "Using 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."); + "Because 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++) { From fc61018b1c42be13e4e5a7f1111435dbba750a25 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 17:10:06 +0200 Subject: [PATCH 168/223] Demo: Renamed "Layout" -> "Layout & Scrolling". Fixed usage of local struct as template class (c++11). --- imgui_demo.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bc4cd1c2..1e5c59b8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1960,7 +1960,7 @@ static void ShowDemoWindowWidgets() static void ShowDemoWindowLayout() { - if (!ImGui::CollapsingHeader("Layout")) + if (!ImGui::CollapsingHeader("Layout & Scrolling")) return; if (ImGui::TreeNode("Child windows")) @@ -4993,8 +4993,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::BeginTabItem("Canvas")) { - struct ItemLine { ImVec2 p0, p1; ItemLine(const ImVec2& _p0, const ImVec2& _p1) { p0 = _p0; p1 = _p1; } }; - static ImVector lines; + static ImVector points; static ImVec2 scrolling(0.0f, 0.0f); static bool opt_enable_grid = true; static bool opt_enable_context_menu = true; @@ -5038,12 +5037,13 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Add first and second point if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { - lines.push_back(ItemLine(mouse_pos_in_canvas, mouse_pos_in_canvas)); + points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_in_canvas); adding_line = true; } if (adding_line) { - lines.back().p1 = mouse_pos_in_canvas; + points.back() = mouse_pos_in_canvas; if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) adding_line = false; } @@ -5064,10 +5064,10 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::BeginPopup("context")) { if (adding_line) - lines.pop_back(); + points.resize(points.size() - 2); adding_line = false; - if (ImGui::MenuItem("Remove one", NULL, false, lines.Size > 0)) { lines.pop_back(); } - if (ImGui::MenuItem("Remove all", NULL, false, lines.Size > 0)) { lines.clear(); } + if (ImGui::MenuItem("Remove one", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); } + if (ImGui::MenuItem("Remove all", NULL, false, points.Size > 0)) { points.clear(); } ImGui::EndPopup(); } @@ -5081,8 +5081,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP) draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40)); } - for (int n = 0; n < lines.Size; n++) - draw_list->AddLine(ImVec2(origin.x + lines[n].p0.x, origin.y + lines[n].p0.y), ImVec2(origin.x + lines[n].p1.x, origin.y + lines[n].p1.y), IM_COL32(255, 255, 0, 255), 2.0f); + for (int n = 0; n < points.Size; n += 2) + draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); draw_list->PopClipRect(); ImGui::EndTabItem(); From 8074b4914834e2892000fc1f359fdb8cf84e88ac Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 19:23:00 +0200 Subject: [PATCH 169/223] Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). (#3187, #3386) # Conflicts: # imgui_widgets.cpp --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui_internal.h | 5 +++-- imgui_widgets.cpp | 10 ++++++---- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7cc16314..c9d14d56 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). + Also fixed related text clipping when used in a column after the first one. (#3187, #3386) - Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many side-effects. The behavior is still present in SetScrollHere functions as they are more explicitly diff --git a/imgui.cpp b/imgui.cpp index e6d7f61d..c6127355 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5898,6 +5898,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) 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; + window->ParentWorkRect = window->WorkRect; // [LEGACY] Content Region // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. diff --git a/imgui_internal.h b/imgui_internal.h index e0f8ae02..65e6e9e7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1015,7 +1015,7 @@ struct ImGuiColumns float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() - ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns() + ImRect HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns() ImVector Columns; ImDrawListSplitter Splitter; @@ -1612,7 +1612,8 @@ struct IMGUI_API ImGuiWindow ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. 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 ContentRegionRect over time (from 1.71+ onward). + ImRect WorkRect; // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ImRect ParentWorkRect; // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack? ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). ImRect ContentRegionRect; // 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. ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 55dc6433..1d4362d0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5704,8 +5704,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ItemSize(size, 0.0f); // Fill horizontal space - const float min_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ContentRegionRect.Min.x : pos.x; - const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ContentRegionRect.Max.x : GetContentRegionMaxAbs().x; + const float min_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Min.x : pos.x; + const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) size.x = ImMax(label_size.x, max_x - min_x); @@ -7665,7 +7665,8 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostInitialClipRect = window->ClipRect; - columns->HostWorkRect = window->WorkRect; + columns->HostBackupParentWorkRect = window->ParentWorkRect; + window->ParentWorkRect = 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 @@ -7845,7 +7846,8 @@ void ImGui::EndColumns() } columns->IsBeingResized = is_being_resized; - window->WorkRect = columns->HostWorkRect; + window->WorkRect = window->ParentWorkRect; + window->ParentWorkRect = columns->HostBackupParentWorkRect; window->DC.CurrentColumns = NULL; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); From b15b25bccd108832aee7b8e75a53072830c353fe Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Aug 2020 16:35:29 +0200 Subject: [PATCH 170/223] TabBar: made a change to that declared ideal width (for auto-resize) won't lag by an extra frame. Vaguely relate to underlying (uncommited) work for #3291 --- imgui_widgets.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1d4362d0..1378613c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6657,9 +6657,9 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->CurrFrameVisible = g.FrameCount; tab_bar->FramePadding = g.Style.FramePadding; - // Layout - ItemSize(ImVec2(tab_bar->OffsetMaxIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); + // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap window->DC.CursorPos.x = tab_bar->BarRect.Min.x; + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + g.Style.ItemSpacing.y; // Draw separator const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); @@ -6685,7 +6685,7 @@ void ImGui::EndTabBar() IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); return; } - if (tab_bar->WantLayout) + if (tab_bar->WantLayout) // Fallback in case no TabItem have been submitted TabBarLayout(tab_bar); // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). @@ -6871,6 +6871,11 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Clear name buffers if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) tab_bar->TabsNames.Buf.resize(0); + + // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) + ImGuiWindow* window = g.CurrentWindow; + window->DC.CursorPos = tab_bar->BarRect.Min; + ItemSize(ImVec2(tab_bar->OffsetMaxIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. From ede8825fb2d28142ce43d944f8f9ce58cadf5054 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Aug 2020 15:24:00 +0200 Subject: [PATCH 171/223] Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. Broken by a06eb833 (#3390) --- docs/CHANGELOG.txt | 1 + examples/example_glfw_vulkan/main.cpp | 1 + examples/example_sdl_vulkan/main.cpp | 1 + 3 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c9d14d56..76703d74 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,6 +80,7 @@ Other Changes: - Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] +- Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. (#3390) [@RoryO] ----------------------------------------------------------------------- diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 80763a01..58d0ab7f 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -513,6 +513,7 @@ int main(int, char**) const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); if (!is_minimized) { + memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); FramePresent(wd); } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 0a2ea9ee..6de7afab 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -513,6 +513,7 @@ int main(int, char**) const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); if (!is_minimized) { + memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); FramePresent(wd); } From 90b152f265250d85fa180efcab01a9951d499f2d Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Aug 2020 16:26:16 +0200 Subject: [PATCH 172/223] ImFontAtlas: Fixed multiple rebuild with same inputs erroneously increased ConfigDataCount. CI: Update Ubuntu 18.04 > 20.04 (motivated by #3369) Fix Freetype warning. --- .github/workflows/build.yml | 2 +- imgui_draw.cpp | 1 + misc/freetype/imgui_freetype.cpp | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b3b910f2..274ca2a6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -180,7 +180,7 @@ jobs: run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' Linux: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v1 with: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 890c0c2c..39209287 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2328,6 +2328,7 @@ void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* f font->ClearOutputData(); font->FontSize = font_config->SizePixels; font->ConfigData = font_config; + font->ConfigDataCount = 0; font->ContainerAtlas = atlas; font->Ascent = ascent; font->Descent = descent; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 1a03be0c..3d62dc4b 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -382,7 +382,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns dst_tmp.GlyphsSet.Create(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++) + for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++) { if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite) continue; From 89ac87cd91baa25dfa4bca3796588eef34f3cadf Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 11:30:19 +0200 Subject: [PATCH 173/223] Internals: Added SetLastItemData, rename ImGuiItemHoveredDataBackup to ImGuiLastItemDataBackup. --- imgui.cpp | 15 ++++++++++++--- imgui_internal.h | 7 ++++--- imgui_widgets.cpp | 4 ++-- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c6127355..1e541e11 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3100,6 +3100,15 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged return false; } +// This is also inlined in ItemAdd() +// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect! +void ImGui::SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags item_flags, const ImRect& item_rect) +{ + window->DC.LastItemId = item_id; + window->DC.LastItemStatusFlags = item_flags; + window->DC.LastItemRect = item_rect; +} + // Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) { @@ -5980,9 +5989,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // 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; - window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; - window->DC.LastItemRect = title_bar_rect; + SetLastItemData(window, window->MoveId, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect); + #ifdef IMGUI_ENABLE_TEST_ENGINE if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId); @@ -6959,6 +6967,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) #endif } + // Equivalent to calling SetLastItemData() window->DC.LastItemId = id; window->DC.LastItemRect = bb; window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None; diff --git a/imgui_internal.h b/imgui_internal.h index 65e6e9e7..79a81f99 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -96,7 +96,7 @@ 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 -struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data +struct ImGuiLastItemDataBackup; // Backup and restore IsItemHovered() internal data struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiNavMoveResult; // Result of a gamepad/keyboard directional navigation move query result struct ImGuiNextWindowData; // Storage for SetNextWindow** functions @@ -1664,14 +1664,14 @@ public: }; // 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. -struct ImGuiItemHoveredDataBackup +struct ImGuiLastItemDataBackup { ImGuiID LastItemId; ImGuiItemStatusFlags LastItemStatusFlags; ImRect LastItemRect; ImRect LastItemDisplayRect; - ImGuiItemHoveredDataBackup() { Backup(); } + ImGuiLastItemDataBackup() { Backup(); } void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; } void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; } }; @@ -1839,6 +1839,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 void SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags status_flags, const ImRect& item_rect); 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_w, float default_h); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1378613c..78115734 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5661,7 +5661,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags // 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; + ImGuiLastItemDataBackup last_item_backup; float button_size = g.FontSize; 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; @@ -7410,7 +7410,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, close_button_visible = true; if (close_button_visible) { - ImGuiItemHoveredDataBackup last_item_backup; + ImGuiLastItemDataBackup last_item_backup; 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))) From 209a6a751cbd86c5534df050cd0839a093511a19 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 11:33:30 +0200 Subject: [PATCH 174/223] Revert "Examples: Switch most VS projects to enable Edit & Continue by default (may need to upgrade projects to latest toolchain)" This reverts commit a24578ec094b51f739dd788b53028c411c55a3eb. /ZI not supported on 64-bit on some toolchains, leaving to default is best? --- examples/example_allegro5/example_allegro5.vcxproj | 1 - examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj | 1 - examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj | 1 - examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj | 1 - examples/example_glut_opengl2/example_glut_opengl2.vcxproj | 1 - examples/example_sdl_directx11/example_sdl_directx11.vcxproj | 1 - examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj | 3 +-- examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj | 1 - examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj | 1 - .../example_win32_directx10/example_win32_directx10.vcxproj | 1 - .../example_win32_directx11/example_win32_directx11.vcxproj | 1 - examples/example_win32_directx9/example_win32_directx9.vcxproj | 1 - 12 files changed, 1 insertion(+), 13 deletions(-) diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index ace88555..c86dcb2b 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index 5cb59b87..b265fea0 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 3d670bf5..47d25380 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index 65458eb9..9e2c9b38 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index ac8f6a76..9a239516 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled $(GLUT_INCLUDE_DIR);..\..;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj index b32034e5..804bd500 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -106,7 +106,6 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index 8bba2071..83a6a8a0 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -19,7 +19,7 @@ - {4168B148-B7DE-4A31-8497-19AFA6B83360} + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} example_sdl_opengl2 8.1 @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj index c516c999..54aaa796 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj index 8a6eab4c..ac701a2a 100644 --- a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj +++ b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 6182b687..5c3aa69f 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -100,7 +100,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); - EditAndContinue true diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index 3e4db23e..bcb71bc4 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -99,7 +99,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); - EditAndContinue true diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index cf944ae5..25bdd859 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -100,7 +100,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; - EditAndContinue true From acf043a67589e718b630e27df4ddcefe0693d320 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 11:58:37 +0200 Subject: [PATCH 175/223] Docking: Moved code unjustly in DockNodeTreeFindNodeByPos() out of it and into caller (should have no side-effect ideally). Removed dupe in Begin() from earlier merge. --- imgui.cpp | 39 +++++++++++++++++++-------------------- imgui_internal.h | 4 ++-- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fbb2bff6..58d515ab 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6056,10 +6056,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; - // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. - window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); - window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; - // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive) @@ -11757,7 +11753,7 @@ namespace ImGui static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child); 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* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos); static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node); // Settings @@ -14026,13 +14022,13 @@ ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node) return NULL; } -ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos) +ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos) { if (!node->IsVisible) return NULL; ImGuiContext& g = *GImGui; - const float dock_spacing = g.Style.ItemInnerSpacing.x; + const float dock_spacing = g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? ImRect r(node->Pos, node->Pos + node->Size); r.Expand(dock_spacing * 0.5f); bool inside = r.Contains(pos); @@ -14041,20 +14037,11 @@ ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos) if (node->IsLeafNode()) return node; - if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[0], pos)) + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos)) return hovered_node; - if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[1], pos)) + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos)) return hovered_node; - // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) - // In this case we need to fallback into any leaf mode, possibly the central node. - if (node->IsDockSpace() && node->IsRootNode()) - { - if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. - return node->CentralNode; - return DockNodeTreeFindFallbackLeafNode(node); - } - return NULL; } @@ -14876,7 +14863,19 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) ImGuiDockNode* node = NULL; bool allow_null_target_node = false; if (window->DockNodeAsHost) - node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + { + node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + + // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + if (node && node->IsDockSpace() && node->IsRootNode()) + { + if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + node = node->CentralNode; + else + node = DockNodeTreeFindFallbackLeafNode(node); + } + } else if (window->DockNode) // && window->DockIsActive) node = window->DockNode; else @@ -15975,7 +15974,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) { ImGuiDockNode* root_node = DockNodeGetRootNode(node); - if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos)) + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(root_node, g.IO.MousePos)) if (hovered_node != node) continue; char buf[64] = ""; diff --git a/imgui_internal.h b/imgui_internal.h index 8c7601c8..6f29af1e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1085,8 +1085,8 @@ enum ImGuiDockNodeFlagsPrivate_ ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 18, // [EXPERIMENTAL] Prevent this node from splitting another window/node. ImGuiDockNodeFlags_NoDockingOverMe = 1 << 19, // [EXPERIMENTAL] Prevent another window/node to be docked over this node. ImGuiDockNodeFlags_NoDockingOverOther = 1 << 20, // [EXPERIMENTAL] Prevent this node to be docked over another window/node. - ImGuiDockNodeFlags_NoResizeX = 1 << 21, // [EXPERIMENTAL] - ImGuiDockNodeFlags_NoResizeY = 1 << 22, // [EXPERIMENTAL] + ImGuiDockNodeFlags_NoResizeX = 1 << 21, // [EXPERIMENTAL] + ImGuiDockNodeFlags_NoResizeY = 1 << 22, // [EXPERIMENTAL] ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, ImGuiDockNodeFlags_NoResizeFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking, From 85a661d276a27063b39209fd52deab1a793bfbed Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 12:52:33 +0200 Subject: [PATCH 176/223] Docking: Storing HoveredDockNode in context which can be useful for easily detecting e.g. hovering an empty node. (#3398) --- imgui.cpp | 81 +++++++++++++++++++++++------------------------- imgui_internal.h | 2 ++ 2 files changed, 40 insertions(+), 43 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 58d515ab..30f31a72 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11892,6 +11892,16 @@ void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; + // Store hovered dock node. We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut. + g.HoveredDockNode = NULL; + if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow) + { + if (hovered_window->DockNode) + g.HoveredDockNode = hovered_window->DockNode; + else if (hovered_window->DockNodeAsHost) + g.HoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); + } + // Process Docking requests for (int n = 0; n < dc->Requests.Size; n++) if (dc->Requests[n].Type == ImGuiDockRequestType_Dock) @@ -14027,8 +14037,7 @@ ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVe if (!node->IsVisible) return NULL; - ImGuiContext& g = *GImGui; - const float dock_spacing = g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? + const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? ImRect r(node->Pos, node->Pos + node->Size); r.Expand(dock_spacing * 0.5f); bool inside = r.Contains(pos); @@ -14860,26 +14869,19 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { // Select target node - ImGuiDockNode* node = NULL; - bool allow_null_target_node = false; - if (window->DockNodeAsHost) - { - node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + // (we should not assume that g.HoveredDockNode is != NULL when window is a host dock node: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos) + ImGuiDockNode* node = g.HoveredDockNode; + const bool allow_null_target_node = window->DockNode == NULL && window->DockNodeAsHost == NULL; - // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) - // In this case we need to fallback into any leaf mode, possibly the central node. - if (node && node->IsDockSpace() && node->IsRootNode()) - { - if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. - node = node->CentralNode; - else - node = DockNodeTreeFindFallbackLeafNode(node); - } + // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + if (window->DockNodeAsHost && node && node->IsDockSpace() && node->IsRootNode()) + { + if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + node = node->CentralNode; + else + node = DockNodeTreeFindFallbackLeafNode(node); } - else if (window->DockNode) // && window->DockIsActive) - node = window->DockNode; - else - allow_null_target_node = true; // Dock into a regular window 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); @@ -15824,6 +15826,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ImGui::SameLine(); if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } + ImGui::Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (!root_nodes_only || node->IsRootNode()) @@ -15967,29 +15970,21 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK // Overlay: Display Docking info - if (show_docking_nodes && g.IO.KeyCtrl) - { - ImGuiDockContext* dc = &g.DockContext; - for (int n = 0; n < dc->Nodes.Data.Size; n++) - if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) - { - ImGuiDockNode* root_node = DockNodeGetRootNode(node); - if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(root_node, g.IO.MousePos)) - if (hovered_node != node) - continue; - 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, "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); - 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); - } + if (show_docking_nodes && g.IO.KeyCtrl && g.HoveredDockNode) + { + char buf[64] = ""; + char* p = buf; + ImGuiDockNode* node = g.HoveredDockNode; + 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); + 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); } #endif // #ifdef IMGUI_HAS_DOCK diff --git a/imgui_internal.h b/imgui_internal.h index 6f29af1e..e3253fb4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1296,6 +1296,7 @@ struct ImGuiContext ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + ImGuiDockNode* HoveredDockNode; 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; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; @@ -1515,6 +1516,7 @@ struct ImGuiContext HoveredWindow = NULL; HoveredRootWindow = NULL; HoveredWindowUnderMovingWindow = NULL; + HoveredDockNode = NULL; MovingWindow = NULL; WheelingWindow = NULL; WheelingWindowTimer = 0.0f; From 009276b6cbd20ee697a209370d647945877e7e39 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 15:31:48 +0200 Subject: [PATCH 177/223] Backends: Allegro 5: Fixed horizontal scrolling direction with mouse wheel / touch pads (#3394, #2424, #1463) [@nobody-special666] Amend 7dea158175615dc8939c57a06641bac911e33e8c + Fix vsproj GUID --- docs/CHANGELOG.txt | 4 +++- examples/example_allegro5/example_allegro5.vcxproj | 2 +- examples/imgui_impl_allegro5.cpp | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 76703d74..b30685f5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,7 +49,7 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) -- Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). +- Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). Also fixed related text clipping when used in a column after the first one. (#3187, #3386) - Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many @@ -80,6 +80,8 @@ Other Changes: - Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] +- Backends: Allegro 5: Fixed horizontal scrolling direction with mouse wheel / touch pads (it seems + like Allegro 5 reports it differently from GLFW and SDL). (#3394, #2424, #1463) [@nobody-special666] - Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. (#3390) [@RoryO] diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index c86dcb2b..f5fadc37 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -19,7 +19,7 @@ - {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} + {73F235B5-7D31-4FC6-8682-DDC5A097B9C1} example_allegro5 8.1 diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 4a467c30..ca2cfae4 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) +// 2020-08-10: Inputs: Fixed horizontal mouse wheel direction. // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 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(). @@ -332,7 +333,7 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) if (ev->mouse.display == g_Display) { io.MouseWheel += ev->mouse.dz; - io.MouseWheelH += ev->mouse.dw; + io.MouseWheelH -= ev->mouse.dw; io.MousePos = ImVec2(ev->mouse.x, ev->mouse.y); } return true; From dbc70f21a90b0d7af93abf178ac6a0c6fa4b406b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 15:53:34 +0200 Subject: [PATCH 178/223] Docking: Fixed docking overlay bits appearing at (0,0), because of 43bd80a4. Most typically noticable when disabling multi-viewport. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 30f31a72..f03f787a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11684,7 +11684,7 @@ struct ImGuiDockPreviewData float SplitRatio; ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() - ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; } + ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); } }; // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes) From a5ba26806f19bb85a7f146e166aa2f61e99e70a3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 16:28:46 +0200 Subject: [PATCH 179/223] Make moving window prevent its active id from being stolen (#3392, #3243, #1738) Amend 7b3d379, 615e9ae3 --- imgui.cpp | 9 ++++++--- imgui_internal.h | 1 + imgui_widgets.cpp | 3 ++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f03f787a..9a8c8b3b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2979,6 +2979,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) } g.ActiveId = id; g.ActiveIdAllowOverlap = false; + g.ActiveIdNoClearOnFocusLoss = false; g.ActiveIdWindow = window; g.ActiveIdHasBeenEditedThisFrame = false; if (id) @@ -2996,7 +2997,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) void ImGui::ClearActiveID() { - SetActiveID(0, NULL); + SetActiveID(0, NULL); // g.ActiveId = 0; } void ImGui::SetHoveredID(ImGuiID id) @@ -3401,6 +3402,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) FocusWindow(window); SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; + g.ActiveIdNoClearOnFocusLoss = true; g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; bool can_move_window = true; @@ -6775,8 +6777,9 @@ void ImGui::FocusWindow(ImGuiWindow* window) // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. - if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window && !active_id_window_is_dock_node_host) - ClearActiveID(); + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window) + if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host) + ClearActiveID(); // Passing NULL allow to disable keyboard focus if (!window) diff --git a/imgui_internal.h b/imgui_internal.h index e3253fb4..2dada7af 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1314,6 +1314,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 ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. 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; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 374e6b5d..1103167e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7395,8 +7395,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Undock DockContextQueueUndockWindow(&g, docked_window); g.MovingWindow = docked_window; - g.ActiveId = g.MovingWindow->MoveId; + SetActiveID(g.MovingWindow->MoveId, g.MovingWindow); g.ActiveIdClickOffset -= g.MovingWindow->Pos - bb.Min; + g.ActiveIdNoClearOnFocusLoss = true; } } } From 8241cd6284b496bba6a5800502b02f9f68af0324 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 16:28:46 +0200 Subject: [PATCH 180/223] Make moving window prevent its active id from being stolen (#3392, #3243, #1738) Amend 7b3d379, 615e9ae3 # Conflicts: # imgui.cpp # imgui_widgets.cpp --- imgui.cpp | 11 ++++++++--- imgui_internal.h | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1e541e11..c2e3bbef 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2927,6 +2927,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) } g.ActiveId = id; g.ActiveIdAllowOverlap = false; + g.ActiveIdNoClearOnFocusLoss = false; g.ActiveIdWindow = window; g.ActiveIdHasBeenEditedThisFrame = false; if (id) @@ -2944,7 +2945,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) void ImGui::ClearActiveID() { - SetActiveID(0, NULL); + SetActiveID(0, NULL); // g.ActiveId = 0; } void ImGui::SetHoveredID(ImGuiID id) @@ -3301,6 +3302,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) FocusWindow(window); SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; + g.ActiveIdNoClearOnFocusLoss = true; g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; bool can_move_window = true; @@ -6147,9 +6149,12 @@ void ImGui::FocusWindow(ImGuiWindow* window) ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; - // Steal focus on active widgets + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) - ClearActiveID(); + if (!g.ActiveIdNoClearOnFocusLoss) + ClearActiveID(); // Passing NULL allow to disable keyboard focus if (!window) diff --git a/imgui_internal.h b/imgui_internal.h index 79a81f99..5118d819 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1147,6 +1147,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 ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. 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; From a4dd4d60b4afcea8185bca773249bd1ec641d726 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 17:34:14 +0200 Subject: [PATCH 181/223] CI: moved static analysis to a separate project + fix (uninitialized variable, was harmless in this case). --- .github/workflows/build.yml | 35 ---------------------- .github/workflows/static-analysis.yml | 43 +++++++++++++++++++++++++++ docs/README.md | 3 +- imgui_internal.h | 1 + 4 files changed, 46 insertions(+), 36 deletions(-) create mode 100644 .github/workflows/static-analysis.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 274ca2a6..a404f465 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -398,38 +398,3 @@ jobs: source ./emsdk_env.sh popd make -C examples/example_emscripten - - Static-Analysis: - runs-on: ubuntu-18.04 - steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 - - - name: Install Dependencies - env: - PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }} - run: | - if [[ "$PVS_STUDIO_LICENSE" != "" ]]; - then - echo "$PVS_STUDIO_LICENSE" > pvs-studio.lic - wget -q https://files.viva64.com/etc/pubkey.txt - sudo apt-key add pubkey.txt - sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list - sudo apt-get update - sudo apt-get install -y pvs-studio - fi - - - name: PVS-Studio static analysis - run: | - if [[ ! -f pvs-studio.lic ]]; - then - echo "PVS Studio license is missing. No analysis will be performed." - echo "If you have a PVS Studio license please create a project secret named PVS_STUDIO_LICENSE with your license." - echo "You may use a free license. More information at https://www.viva64.com/en/b/0457/" - exit 0 - fi - cd examples/example_null - pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 - pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log - plog-converter -a 'GA:1,2;OP:1' -t errorfile -w pvs-studio.log diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml new file mode 100644 index 00000000..7967d532 --- /dev/null +++ b/.github/workflows/static-analysis.yml @@ -0,0 +1,43 @@ +name: static-analysis + +on: + push: {} + pull_request: {} + schedule: + - cron: '0 9 * * *' + +jobs: + PVS-Studio: + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v1 + with: + fetch-depth: 1 + + - name: Install Dependencies + env: + PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }} + run: | + if [[ "$PVS_STUDIO_LICENSE" != "" ]]; + then + echo "$PVS_STUDIO_LICENSE" > pvs-studio.lic + wget -q https://files.viva64.com/etc/pubkey.txt + sudo apt-key add pubkey.txt + sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list + sudo apt-get update + sudo apt-get install -y pvs-studio + fi + + - name: PVS-Studio static analysis + run: | + if [[ ! -f pvs-studio.lic ]]; + then + echo "PVS Studio license is missing. No analysis will be performed." + echo "If you have a PVS Studio license please create a project secret named PVS_STUDIO_LICENSE with your license." + echo "You may use a free license. More information at https://www.viva64.com/en/b/0457/" + exit 0 + fi + cd examples/example_null + pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 + pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log + plog-converter -a 'GA:1,2;OP:1' -t errorfile -w pvs-studio.log diff --git a/docs/README.md b/docs/README.md index 9579ee22..1259a638 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,7 @@ Dear ImGui ===== -[![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) +[![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) [![Static Analysis Status](https://github.com/ocornut/imgui/workflows/static-analysis/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=static-analysis) + (This library is available under a free and permissive license, 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.) diff --git a/imgui_internal.h b/imgui_internal.h index 5118d819..e923a6af 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1352,6 +1352,7 @@ struct ImGuiContext ActiveIdTimer = 0.0f; ActiveIdIsJustActivated = false; ActiveIdAllowOverlap = false; + ActiveIdNoClearOnFocusLoss = false; ActiveIdHasBeenPressedBefore = false; ActiveIdHasBeenEditedBefore = false; ActiveIdHasBeenEditedThisFrame = false; From 214dd68ec1d62b5a885967a0e66194a8bfbfbbeb Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 22:05:26 +0200 Subject: [PATCH 182/223] Comments, clarifying ClosePopupsOverWindow(). --- docs/README.md | 10 +++++----- imgui.cpp | 24 ++++++++++++++++-------- imgui_internal.h | 8 ++++---- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/docs/README.md b/docs/README.md index 1259a638..58fb208e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -98,7 +98,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas ![screenshot demo](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png) You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: -- [imgui-demo-binaries-20190715.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows binaries, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). +- [imgui-demo-binaries-20200412.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). The demo applications are not 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()` (see [FAQ](https://www.dearimgui.org/faq)). @@ -126,7 +126,7 @@ Some of the goals for 2020 are: - Work on docking. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch) - Work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) - Work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) -- Work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957)) +- Work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957), in public [tables](https://github.com/ocornut/imgui/tree/tables) branch looking for feedback) - Work on automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) - Make the examples look better, improve styles, improve font support, make the examples hi-DPI and multi-DPI aware. @@ -145,7 +145,7 @@ Custom engine ### Support, Frequently Asked Questions (FAQ) -Most common questions will be answered by the [Frequently Asked Questions (FAQ)](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) page. +See: [Frequently Asked Questions (FAQ)](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) where common questions are answered. See: [Wiki](https://github.com/ocornut/imgui/wiki) for many links, references, articles. @@ -161,7 +161,7 @@ Private support is available for paying business customers (E-mail: _contact @ d We 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. Many projects are using this branch and it is kept in sync with master regularly. +Advanced users may want to use the `docking` branch with [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features. This branch is kept in sync with master regularly. **Who uses Dear ImGui?** @@ -220,7 +220,7 @@ Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT li Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). -Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub. +Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Also thank you to everyone posting feedback, questions and patches on GitHub. License ------- diff --git a/imgui.cpp b/imgui.cpp index c2e3bbef..a9aabfdb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6098,7 +6098,7 @@ void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; ImGuiWindow* current_front_window = g.Windows.back(); - if (current_front_window == window || current_front_window->RootWindow == window) + if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better) return; for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window if (g.Windows[i] == window) @@ -7696,13 +7696,14 @@ void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) } } +// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. +// This function closes any popups that are over 'ref_window'. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size == 0) return; - // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. // Don't close our own child popup windows. int popup_count_to_keep = 0; if (ref_window) @@ -7717,13 +7718,20 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) continue; - // 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 (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window) + // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow) + // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3: + // Window -> Popup1 -> Popup2 -> Popup3 + // - Each popups may contain child windows, which is why we compare ->RootWindow! + // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child + bool ref_window_is_descendent_of_popup = false; + for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++) + if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window) if (popup_window->RootWindow == ref_window->RootWindow) - popup_or_descendent_is_ref_window = true; - if (!popup_or_descendent_is_ref_window) + { + ref_window_is_descendent_of_popup = true; + break; + } + if (!ref_window_is_descendent_of_popup) break; } } diff --git a/imgui_internal.h b/imgui_internal.h index e923a6af..e362a04b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1127,10 +1127,10 @@ struct ImGuiContext ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow* int WindowsActiveCount; // Number of unique windows submitted by frame ImGuiWindow* CurrentWindow; // Window being drawn into - ImGuiWindow* HoveredWindow; // Will catch mouse inputs - ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. + ImGuiWindow* HoveredRootWindow; // == HoveredWindow ? HoveredWindow->RootWindow : NULL, merely a shortcut to avoid null test in some situation. ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. - ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. + ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; float WheelingWindowTimer; @@ -1632,7 +1632,7 @@ struct IMGUI_API ImGuiWindow ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) ImDrawList DrawListInst; ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL. - ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. + ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window == Top-level window. ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. From a9626e1162c3742307553108aff8a443c20bb73c Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Aug 2020 11:51:47 +0200 Subject: [PATCH 183/223] Docking: Made DockBuilderAddNode() automatically call DockBuilderRemoveNode(). (#3399, #2109) --- imgui.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9a8c8b3b..13dfcc42 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14316,10 +14316,15 @@ void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) // - 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. +// - Existing node with a same id will be removed. ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) { ImGuiContext* ctx = GImGui; ImGuiDockNode* node = NULL; + + if (id != 0) + DockBuilderRemoveNode(id); + if (flags & ImGuiDockNodeFlags_DockSpace) { DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly); @@ -14327,10 +14332,7 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) } else { - if (id != 0) - node = DockContextFindNodeByID(ctx, id); - if (!node) - node = DockContextAddNode(ctx, id); + node = DockContextAddNode(ctx, id); node->LocalFlags = flags; } node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame. From 0e5b1ea297f9a0764c59ca29810c6b05c39fe6d2 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Wed, 12 Aug 2020 16:26:42 +0200 Subject: [PATCH 184/223] CI: imscripten fastcomp backend is now deprecated (#3402) Fastcomp backend was introduced here: https://github.com/ocornut/imgui/commit/14b18697e653de80f75af18113033b2086846194 Emscripten changelog: https://emscripten.org/docs/introducing_emscripten/release_notes.html?highlight=2.0.0:%2008/10/2020 Emscripten issue: https://github.com/emscripten-core/emsdk/pull/590 Updated CHANGELOG.txt --- .github/workflows/build.yml | 4 ++-- docs/CHANGELOG.txt | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a404f465..eea8eaa3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -389,8 +389,8 @@ jobs: wget -q https://github.com/emscripten-core/emsdk/archive/master.tar.gz tar -xvf master.tar.gz emsdk-master/emsdk update - emsdk-master/emsdk install latest-fastcomp - emsdk-master/emsdk activate latest-fastcomp + emsdk-master/emsdk install latest + emsdk-master/emsdk activate latest - name: Build example_emscripten run: | diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b30685f5..718cdecd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,7 @@ Other Changes: - Backends: Allegro 5: Fixed horizontal scrolling direction with mouse wheel / touch pads (it seems like Allegro 5 reports it differently from GLFW and SDL). (#3394, #2424, #1463) [@nobody-special666] - Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. (#3390) [@RoryO] +- CI: Emscripten has stopped their support for their fastcomp backend, switching to latest sdk [@Xipiryon] ----------------------------------------------------------------------- From 46d75202b82dba5e32105219d2ea5947648a4ed8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Aug 2020 12:55:42 +0200 Subject: [PATCH 185/223] Tab Bar: Allow calling SetTabItemClosed() after a tab has been submitted (will process next frame). + larger combo height on TabBarTabListPopupButton() --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 1 + imgui_internal.h | 9 +++++---- imgui_widgets.cpp | 21 +++++++++++---------- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 718cdecd..989f8079 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,7 @@ Other Changes: limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many side-effects. The behavior is still present in SetScrollHere functions as they are more explicitly aiming at making widgets visible. May later be moved to a flag. +- Tab Bar: Allow calling SetTabItemClosed() after a tab has been submitted (will process next frame). - InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. This is a small but rather important change because lots of multi-button behaviors could previously diff --git a/docs/TODO.txt b/docs/TODO.txt index a96693b3..c0f01841 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -161,6 +161,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - dock: merge docking branch (#2109) - dock: dock out from a collapsing header? would work nicely but need emitting window to keep submitting the code. + - tabs: while dragging/reordering a tab, close button decoration shouldn't appear on other tabs - 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) - tabs: TabItem could honor SetNextItemWidth()? diff --git a/imgui_internal.h b/imgui_internal.h index e362a04b..ce1fef49 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1696,19 +1696,20 @@ enum ImGuiTabItemFlagsPrivate_ ImGuiTabItemFlags_NoCloseButton = 1 << 20 // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) }; -// Storage for one active tab item (sizeof() 26~32 bytes) +// Storage for one active tab item (sizeof() 28~32 bytes) struct ImGuiTabItem { ImGuiID ID; 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 ContentWidth; // Width of actual contents, stored during BeginTabItem() call + ImS16 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames + bool WantClose; // Marked as closed by SetTabItemClosed() - ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; } + ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; WantClose = false; } }; // Storage for a tab bar (sizeof() 92~96 bytes) @@ -1743,7 +1744,7 @@ struct ImGuiTabBar 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); + IM_ASSERT(tab->NameOffset != -1 && (int)tab->NameOffset < TabsNames.Buf.Size); return TabsNames.Buf.Data + tab->NameOffset; } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 78115734..64f2f890 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6709,15 +6709,17 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiContext& g = *GImGui; tab_bar->WantLayout = false; - // Garbage collect + // Garbage collect by compacting list int tab_dst_n = 0; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; - if (tab->LastFrameVisible < tab_bar->PrevFrameVisible) + if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose) { - if (tab->ID == tab_bar->SelectedTabId) - tab_bar->SelectedTabId = 0; + // Remove tab + if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; } continue; } if (tab_dst_n != tab_src_n) @@ -7039,7 +7041,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); + bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest); PopStyleColor(2); ImGuiTabItem* tab_to_select = NULL; @@ -7167,7 +7169,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab->Flags = flags; // Append name with zero-terminator - tab->NameOffset = tab_bar->TabsNames.size(); + tab->NameOffset = (ImS16)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. @@ -7316,9 +7318,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. -// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem(). +// To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). // Tabs closed by the close button will automatically be flagged to avoid this issue. -// FIXME: We should aim to support calling SetTabItemClosed() after the tab submission (for next frame) void ImGui::SetTabItemClosed(const char* label) { ImGuiContext& g = *GImGui; @@ -7326,9 +7327,9 @@ void ImGui::SetTabItemClosed(const char* label) if (is_within_manual_tab_bar) { 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); + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + tab->WantClose = true; // Will be processed by next call to TabBarLayout() } } From a252a287bf9ca69b2d749c5f5619b2f9a809d76c Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Sun, 24 May 2020 18:05:09 +0900 Subject: [PATCH 186/223] Drags, Sliders: Logarithmic: WIP experiments with trying to make logarithmic sliders sensible (#3361, #1823, #1316, #642) --- imgui_internal.h | 8 +++- imgui_widgets.cpp | 107 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 107 insertions(+), 8 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ce1fef49..5d24a624 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -348,6 +348,12 @@ IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* #define ImCeil(X) ceilf(X) static inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision static inline double ImPow(double x, double y) { return pow(x, y); } +static inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision +static inline double ImLog(double x) { return log(x); } +static inline float ImAbs(float x) { return fabsf(x); } +static inline double ImAbs(double x) { return fabs(x); } +static inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : ((x > 0.0f) ? 1.0f : 0.0f); } // Sign operator - returns -1, 0 or 1 based on sign of argument +static inline double ImSign(double x) { return (x < 0.0) ? -1.0 : ((x > 0.0) ? 1.0 : 0.0); } #endif // - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double // (Exceptionally using templates here but we could also redefine them for those types) @@ -1987,7 +1993,7 @@ namespace ImGui // 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, 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 float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 64f2f890..974c2f67 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2374,15 +2374,57 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // - VSliderInt() //------------------------------------------------------------------------- +// Convert a value v in the output space of a slider into a parametric position on the slider itself template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon) { if (v_min == v_max) return 0.0f; - const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (power == 0.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); - if (is_power) + if (is_logarithmic) + { + bool flipped = v_max < v_min; + + if (flipped) // Handle the case where the range is backwards + ImSwap(v_min, v_max); + + // Fudge min/max to avoid getting close to log(0) + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_min == 0.0f) && (v_max < 0.0f)) + v_min_fudged = -logarithmic_zero_epsilon; + else if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float result; + + if (v_clamped <= v_min_fudged) + result = 0.0f; // Workaround for values that are in-range but below our fudge + else if (v_clamped >= v_max_fudged) + result = 1.0f; // Workaround for values that are in-range but above our fudge + else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions + { + float zero_point = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + if (v == 0.0f) + result = zero_point; // Special case for exactly zero + else if (v < 0.0f) + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point; + else + result = zero_point + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point)); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); + else + result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged)); + + return flipped ? (1.0f - result) : result; + } + else if (is_power) { if (v_clamped < 0.0f) { @@ -2409,7 +2451,8 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_power = (power != 1.0f) && is_decimal; + const bool is_logarithmic = (power == 0.0f) && is_decimal; + const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; @@ -2437,6 +2480,14 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; } + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + } + // Process interacting with the slider bool value_changed = false; if (g.ActiveId == id) @@ -2468,7 +2519,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if ((decimal_precision > 0) || is_power) { @@ -2496,7 +2547,49 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { TYPE v_new; - if (is_power) + if (is_logarithmic) + { + // We special-case the extents because otherwise our fudging can lead to "mathematically correct" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value + if (clicked_t <= 0.0f) + v_new = v_min; + else if (clicked_t >= 1.0f) + v_new = v_max; + else + { + bool flipped = v_max < v_min; + + // Fudge min/max to avoid getting silly results close to zero + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_min == 0.0f) && (v_max < 0.0f)) + v_min_fudged = -logarithmic_zero_epsilon; + else if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + if (flipped) + ImSwap(v_min_fudged, v_max_fudged); + + float clicked_t_with_flip = flipped ? (1.0f - clicked_t) : clicked_t; + + if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts + { + float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + if (clicked_t_with_flip == zero_point) + v_new = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) + else if (clicked_t_with_flip < zero_point) + v_new = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (clicked_t_with_flip / zero_point)))); + else + v_new = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((clicked_t_with_flip - zero_point) / (1.0f - zero_point)))); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + v_new = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - clicked_t_with_flip))); + else + v_new = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)clicked_t_with_flip)); + } + } + else if (is_power) { // Account for power curve scale on both sides of the zero if (clicked_t < linear_zero_pos) @@ -2558,7 +2651,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // 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); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon); 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); From 9f98b4e7f2479e69108952476d8146817385ee72 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Tue, 2 Jun 2020 15:36:20 +0900 Subject: [PATCH 187/223] Drags, Sliders: Logarithmic: Added logarithmic mode support to drag widgets, extended API to add flags to drag/sliders (#3361, #1823, #1316, #642) --- imgui.h | 82 ++++++--- imgui_internal.h | 32 ++-- imgui_widgets.cpp | 451 +++++++++++++++++++++++++++++++--------------- 3 files changed, 379 insertions(+), 186 deletions(-) diff --git a/imgui.h b/imgui.h index c135ada2..a030ebdb 100644 --- a/imgui.h +++ b/imgui.h @@ -168,6 +168,7 @@ typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: f typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() +typedef int ImGuiDragSliderFlags; // -> enum ImGuiDragSliderFlags_ // Flags: for SliderFloat()/DragFloat()/etc // Other types #ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx'] @@ -465,36 +466,57 @@ namespace ImGui // - 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_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - 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); - IMGUI_API bool DragFloat4(const char* label, float v[4], 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 DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, float power = 1.0f); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f); + 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", ImGuiDragSliderFlags flags = 0); // 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", ImGuiDragSliderFlags flags = 0); + 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", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + + // [Obsolete] + // Old drag functions that take a power term instead of flags + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - 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. - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg"); - IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f); + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + + // [Obsolete] + // Old slider functions that take a power term instead of flags + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); // Widgets: Input with Keyboard // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. @@ -1282,6 +1304,14 @@ enum ImGuiColorEditFlags_ #endif }; +// Flags for configuring drag/slider widgets +enum ImGuiDragSliderFlags_ +{ + ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert + ImGuiDragSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? + ImGuiDragSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) +}; + // Identify a mouse button. // Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. enum ImGuiMouseButton_ diff --git a/imgui_internal.h b/imgui_internal.h index 5d24a624..4f5d26c7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -114,7 +114,6 @@ struct ImGuiWindowSettings; // Storage for a window .ini settings (we ke 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 typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() @@ -123,7 +122,6 @@ typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // F 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() typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() @@ -633,18 +631,6 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; -enum ImGuiSliderFlags_ -{ - ImGuiSliderFlags_None = 0, - ImGuiSliderFlags_Vertical = 1 << 0 -}; - -enum ImGuiDragFlags_ -{ - ImGuiDragFlags_None = 0, - ImGuiDragFlags_Vertical = 1 << 0 -}; - // Extend ImGuiSelectableFlags_ enum ImGuiSelectableFlagsPrivate_ { @@ -1981,19 +1967,27 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags); - IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags); + IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags 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 SetNextItemOpen() data, if any. May return true when logging IMGUI_API void TreePushOverrideID(ImGuiID id); + // Internal implementations for some of the exposed functions (use the non-internal versions instead) + IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); // 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, 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, float logarithmic_zero_epsilon); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragSliderFlags 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, ImGuiDragSliderFlags 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, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 974c2f67..8f94426b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1997,13 +1997,14 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiContext& g = *GImGui; - const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); 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_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; + const bool is_power = (power != 1.0f && !is_logarithmic && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); const bool is_locked = (v_min > v_max); if (is_locked) return false; @@ -2034,6 +2035,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (axis == ImGuiAxis_Y) adjust_delta = -adjust_delta; + // For logarithmic use our range is effectively 0..1 so scale the delta into that range + if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0 + adjust_delta /= (float)(v_max - v_min); + // 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; @@ -2056,7 +2061,21 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_cur = *v; FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; - if (is_power) + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + + // Convert to parametric space, apply delta, convert back + // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + float v_new_parametric = v_old_parametric + g.DragCurrentAccum; + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + v_old_ref_for_accum_remainder = v_old_parametric; + } + else if (is_power) { // Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); @@ -2074,7 +2093,14 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false; - if (is_power) + if (is_logarithmic) + { + // Convert to parametric space, apply delta, convert back + // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); + } + else if (is_power) { FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder); @@ -2104,8 +2130,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { + IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + ImGuiContext& g = *GImGui; if (g.ActiveId == id) { @@ -2137,9 +2165,8 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v return false; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +// Internal implementation - see below for entry points +bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2198,7 +2225,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); // Drag behavior - const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, power, ImGuiDragFlags_None); + const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, power, flags); if (value_changed) MarkItemEdited(id); @@ -2214,7 +2241,21 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, return value_changed; } -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +// Obsolete version with power parameter +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, (ImGuiDragSliderFlags)0); +} + +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, 1.0f, flags); +} + +// Internal implementation - see below for entry points +bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2231,7 +2272,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, power); + value_changed |= DragScalarInternal("", data_type, p_data, v_speed, p_min, p_max, format, power, flags); PopID(); PopItemWidth(); p_data = (void*)((char*)p_data + type_size); @@ -2249,27 +2290,63 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data return value_changed; } +// Obsolete version with power parameter +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); +} + +// Internal implementation +bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2283,14 +2360,14 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu float min = (v_min >= v_max) ? -FLT_MAX : v_min; float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power); + bool value_changed = DragScalarInternal("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); max = (v_min >= v_max) ? FLT_MAX : v_max; if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power); + value_changed |= DragScalarInternal("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2300,28 +2377,39 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu return value_changed; } +// Obsolete version with power parameter +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) +{ + return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) +{ + return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, 1.0f, flags); +} + // NB: v_speed is float to allow adjusting the drag speed with more precision -bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format); + return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format); + return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format); + return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format); + return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max) +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2335,14 +2423,14 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ int min = (v_min >= v_max) ? INT_MIN : v_min; int max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format); + bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); max = (v_min >= v_max) ? INT_MAX : v_max; if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format); + value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2374,14 +2462,14 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // - VSliderInt() //------------------------------------------------------------------------- -// Convert a value v in the output space of a slider into a parametric position on the slider itself +// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) { if (v_min == v_max) return 0.0f; - const bool is_logarithmic = (power == 0.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) @@ -2442,16 +2530,114 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); } +// Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) +template +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) +{ + if (v_min == v_max) + return (TYPE)0.0f; + + const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); + + TYPE result; + if (is_logarithmic) + { + // We special-case the extents because otherwise our fudging can lead to "mathematically correct" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value + if (t <= 0.0f) + result = v_min; + else if (t >= 1.0f) + result = v_max; + else + { + bool flipped = v_max < v_min; // Check if range is "backwards" + + // Fudge min/max to avoid getting silly results close to zero + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + if (flipped) + ImSwap(v_min_fudged, v_max_fudged); + + // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range + + if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts + { + float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + if (t_with_flip == zero_point) + result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) + else if (t_with_flip < zero_point) + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point)))); + else + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point) / (1.0f - zero_point)))); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); + else + result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip)); + } + } + else if (is_power) + { + // Account for power curve scale on both sides of the zero + if (t < linear_zero_pos) + { + // Negative: rescale to the negative range before powering + float a = 1.0f - (t / linear_zero_pos); + a = ImPow(a, power); + result = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); + } + else + { + // Positive: rescale to the positive range before powering + float a; + if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) + a = (t - linear_zero_pos) / (1.0f - linear_zero_pos); + else + a = t; + a = ImPow(a, power); + result = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); + } + } + else + { + // Linear slider + if (is_decimal) + { + result = ImLerp(v_min, v_max, t); + } + else + { + // For integer values we want the clicking position to match the grab box so we round above + // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + FLOATTYPE v_new_off_f = (v_max - v_min) * t; + TYPE v_new_off_floor = (TYPE)(v_new_off_f); + TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5); + if (v_new_off_floor < v_new_off_round) + result = v_min + v_new_off_round; + else + result = v_min + v_new_off_floor; + } + } + + return result; +} + // FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template -bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (power == 0.0f) && is_decimal; + const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; @@ -2519,7 +2705,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if ((decimal_precision > 0) || is_power) { @@ -2546,91 +2732,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new; - if (is_logarithmic) - { - // We special-case the extents because otherwise our fudging can lead to "mathematically correct" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value - if (clicked_t <= 0.0f) - v_new = v_min; - else if (clicked_t >= 1.0f) - v_new = v_max; - else - { - bool flipped = v_max < v_min; - - // Fudge min/max to avoid getting silly results close to zero - FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; - FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; - - // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) - if ((v_min == 0.0f) && (v_max < 0.0f)) - v_min_fudged = -logarithmic_zero_epsilon; - else if ((v_max == 0.0f) && (v_min < 0.0f)) - v_max_fudged = -logarithmic_zero_epsilon; - - if (flipped) - ImSwap(v_min_fudged, v_max_fudged); - - float clicked_t_with_flip = flipped ? (1.0f - clicked_t) : clicked_t; - - if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts - { - float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space - if (clicked_t_with_flip == zero_point) - v_new = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) - else if (clicked_t_with_flip < zero_point) - v_new = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (clicked_t_with_flip / zero_point)))); - else - v_new = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((clicked_t_with_flip - zero_point) / (1.0f - zero_point)))); - } - else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider - v_new = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - clicked_t_with_flip))); - else - v_new = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)clicked_t_with_flip)); - } - } - else if (is_power) - { - // Account for power curve scale on both sides of the zero - if (clicked_t < linear_zero_pos) - { - // Negative: rescale to the negative range before powering - float a = 1.0f - (clicked_t / linear_zero_pos); - a = ImPow(a, power); - v_new = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); - } - else - { - // Positive: rescale to the positive range before powering - float a; - if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) - a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); - else - a = clicked_t; - a = ImPow(a, power); - v_new = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); - } - } - else - { - // Linear slider - if (is_decimal) - { - v_new = ImLerp(v_min, v_max, clicked_t); - } - else - { - // For integer values we want the clicking position to match the grab box so we round above - // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. - FLOATTYPE v_new_off_f = (v_max - v_min) * clicked_t; - TYPE v_new_off_floor = (TYPE)(v_new_off_f); - TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5); - if (v_new_off_floor < v_new_off_round) - v_new = v_min + v_new_off_round; - else - v_new = v_min + v_new_off_floor; - } - } + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); // Round to user desired precision based on format string v_new = RoundScalarWithFormatT(format, data_type, v_new); @@ -2651,7 +2753,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // 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, logarithmic_zero_epsilon); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); 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); @@ -2667,8 +2769,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // For 32-bit and larger types, slider bounds are limited to half the natural type range. // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. -bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) { + IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) return false; @@ -2703,9 +2807,8 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type return false; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +// Internal implementation +bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2762,7 +2865,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, ImGuiSliderFlags_None, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -2782,8 +2885,20 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat return value_changed; } -// Add multiple sliders on 1 line for compact edition of multiple components -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +{ + return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); +} + +bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2800,7 +2915,7 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power); + value_changed |= SliderScalarInternal("", data_type, v, v_min, v_max, format, power, flags); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); @@ -2818,57 +2933,94 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i return value_changed; } +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) +{ + return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); +} + +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } -bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format) +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiDragSliderFlags flags) { if (format == NULL) format = "%.0f deg"; float v_deg = (*v_rad) * 360.0f / (2 * IM_PI); - bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags); *v_rad = v_deg * (2 * IM_PI) / 360.0f; return value_changed; } -bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format) +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format); + return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format) +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format); + return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format) +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format); + return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format) +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format); + return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); } -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +// Internal implementation +bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2908,7 +3060,7 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, ImGuiSliderFlags_Vertical, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiDragSliderFlags_Vertical, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -2927,14 +3079,31 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d return value_changed; } +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +{ + return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) { return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } -bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format) +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format); + return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } //------------------------------------------------------------------------- From 152dae9e2aeab833b753541a974cecbb9a0eb2b9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 14:52:26 +0200 Subject: [PATCH 188/223] Drags, Sliders: Logarithmic: Split back flags into drag/slider flags. Moved to an obsolete section. (#3361, #1823, #1316, #642) --- imgui.h | 113 ++++++++++---------- imgui_internal.h | 24 ++--- imgui_widgets.cpp | 261 +++++++++++++++++++++++----------------------- 3 files changed, 200 insertions(+), 198 deletions(-) diff --git a/imgui.h b/imgui.h index a030ebdb..3ee9074b 100644 --- a/imgui.h +++ b/imgui.h @@ -157,6 +157,7 @@ typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: f typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() +typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragFloat(), DragInt() etc. 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. @@ -164,11 +165,11 @@ typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: f typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super) typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderFloat(), SliderInt() etc. typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() -typedef int ImGuiDragSliderFlags; // -> enum ImGuiDragSliderFlags_ // Flags: for SliderFloat()/DragFloat()/etc // Other types #ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx'] @@ -466,57 +467,36 @@ namespace ImGui // - 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_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - 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", ImGuiDragSliderFlags flags = 0); // 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", ImGuiDragSliderFlags flags = 0); - 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", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - - // [Obsolete] - // Old drag functions that take a power term instead of flags - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + 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", ImGuiDragFlags flags = 0); // 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", ImGuiDragFlags flags = 0); + 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", ImGuiDragFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - 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. - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - - // [Obsolete] - // Old slider functions that take a power term instead of flags - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); // Widgets: Input with Keyboard // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. @@ -1304,12 +1284,22 @@ enum ImGuiColorEditFlags_ #endif }; -// Flags for configuring drag/slider widgets -enum ImGuiDragSliderFlags_ +// Flags for DragFloat(), DragInt() etc. +enum ImGuiDragFlags_ +{ + ImGuiDragFlags_None = 0, + ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert + ImGuiDragFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? + ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) +}; + +// Flags for SliderFloat(), SliderInt() etc. +enum ImGuiSliderFlags_ { - ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert - ImGuiDragSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? - ImGuiDragSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert + ImGuiSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? + ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) }; // Identify a mouse button. @@ -1715,6 +1705,23 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.78 (from July 2020) + // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); // OBSOLETED in 1.77 (from June 2020) static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupContextItem(str_id, mb); } // Passing a mouse button to ImGuiPopupFlags is legal static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } diff --git a/imgui_internal.h b/imgui_internal.h index 4f5d26c7..9f4573f4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1967,27 +1967,27 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags); - IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags); + IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_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 SetNextItemOpen() data, if any. May return true when logging IMGUI_API void TreePushOverrideID(ImGuiID id); // Internal implementations for some of the exposed functions (use the non-internal versions instead) - IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); + IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); + IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); + IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); // 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, T v_min, T v_max, const char* format, float power, ImGuiDragSliderFlags 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, ImGuiDragSliderFlags 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, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); + 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, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8f94426b..16f095dd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1997,13 +1997,13 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiContext& g = *GImGui; - const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; + const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; const bool is_power = (power != 1.0f && !is_logarithmic && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); const bool is_locked = (v_min > v_max); if (is_locked) @@ -2130,9 +2130,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT(((flags == 0) || (flags >= ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragFlags flags - has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2166,7 +2166,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } // Internal implementation - see below for entry points -bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2241,21 +2241,15 @@ bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* return value_changed; } -// Obsolete version with power parameter -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) -{ - return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, (ImGuiDragSliderFlags)0); -} - // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, 1.0f, flags); } // Internal implementation - see below for entry points -bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2290,63 +2284,33 @@ bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void return value_changed; } -// Obsolete version with power parameter -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) -{ - return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); -} - -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } // Internal implementation -bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2377,39 +2341,33 @@ bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, flo return value_changed; } -// Obsolete version with power parameter -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) -{ - return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); -} - -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, 1.0f, flags); } // NB: v_speed is float to allow adjusting the drag speed with more precision -bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2441,6 +2399,46 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ return value_changed; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// Obsolete versions with power parameter +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, ImGuiDragFlags_None); +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); +} + +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) +{ + return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); +} + +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //------------------------------------------------------------------------- // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. //------------------------------------------------------------------------- @@ -2464,12 +2462,12 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) @@ -2532,13 +2530,13 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); TYPE result; @@ -2630,14 +2628,14 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m // FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template -bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal; const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; @@ -2769,9 +2767,9 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // For 32-bit and larger types, slider bounds are limited to half the natural type range. // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. -bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT(((flags == 0) || (flags >= ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiSliderFlags flags - has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) @@ -2808,7 +2806,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type } // Internal implementation -bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2887,18 +2885,12 @@ bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, voi // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) -{ - return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); -} - -bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2934,62 +2926,32 @@ bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, vo } // Add multiple sliders on 1 line for compact edition of multiple components -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) -{ - return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); -} - -bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) -{ - return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); -} - -bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) { if (format == NULL) format = "%.0f deg"; @@ -2999,28 +2961,28 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl return value_changed; } -bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); } // Internal implementation -bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3060,7 +3022,7 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiDragSliderFlags_Vertical, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiSliderFlags_Vertical, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -3079,33 +3041,66 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa return value_changed; } -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { - return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); } -bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { - return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); + return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// Obsolete versions with power parameter +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) { - return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); + return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); } -bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) { - return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); + return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); +} + +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) +{ + return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); +} + +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +{ + return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) +{ + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); +} + +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //------------------------------------------------------------------------- // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. //------------------------------------------------------------------------- From 43c099f31ebe89e94d4e54223f3a2d0dc84f8bce Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 18:00:50 +0200 Subject: [PATCH 189/223] Drags, Sliders: Logarithmic: Moved flags to internals, allowing 1.0f to pass by. (#3361, #1823, #1316, #642) --- imgui.h | 10 ++++----- imgui_demo.cpp | 54 +++++++++++++++++++++++------------------------ imgui_internal.h | 12 +++++++++++ imgui_widgets.cpp | 4 ++-- 4 files changed, 45 insertions(+), 35 deletions(-) diff --git a/imgui.h b/imgui.h index 3ee9074b..dc62afc0 100644 --- a/imgui.h +++ b/imgui.h @@ -1288,18 +1288,16 @@ enum ImGuiColorEditFlags_ enum ImGuiDragFlags_ { ImGuiDragFlags_None = 0, - ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert - ImGuiDragFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? - ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) }; // Flags for SliderFloat(), SliderInt() etc. enum ImGuiSliderFlags_ { ImGuiSliderFlags_None = 0, - ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert - ImGuiSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? - ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1e5c59b8..587964f6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -629,7 +629,7 @@ 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); + ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); static float angle = 0.0f; ImGui::SliderAngle("slider angle", &angle); @@ -1557,34 +1557,34 @@ static void ShowDemoWindowWidgets() 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); 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(); 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); + ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f"); + ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiDragFlags_Logarithmic); + ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); + ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiDragFlags_Logarithmic); 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"); - ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); - ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); - ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); - ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%I64d"); - ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%I64d"); - ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%I64d"); - ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%I64u ms"); - ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms"); - ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms"); - ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); - ImGui::SliderScalar("slider float low^2", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", 2.0f); - ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); - ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams", 1.0f); - ImGui::SliderScalar("slider double low^2",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", 2.0f); - ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams", 1.0f); + 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"); + ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); + ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); + ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); + ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%I64d"); + ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%I64d"); + ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%I64d"); + ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%I64u ms"); + ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms"); + ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms"); + ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); + ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); + ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); + ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); static bool inputs_step = true; ImGui::Text("Inputs"); diff --git a/imgui_internal.h b/imgui_internal.h index 9f4573f4..c2d58a18 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -631,6 +631,18 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; +// Extend ImGuiDragFlags_ +enum ImGuiDragFlagsPrivate_ +{ + ImGuiDragFlags_Vertical = 1 << 20 // Should this widget be orientated vertically? +}; + +// Extend ImGuiSliderFlags_ +enum ImGuiSliderFlagsPrivate_ +{ + ImGuiSliderFlags_Vertical = 1 << 20 // Should this slider be orientated vertically? +}; + // Extend ImGuiSelectableFlags_ enum ImGuiSelectableFlagsPrivate_ { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 16f095dd..6de8ce12 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2132,7 +2132,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2769,7 +2769,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiSliderFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) From 7607aea018a603fac69aa2ce373eacce757dcb03 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 19:33:03 +0200 Subject: [PATCH 190/223] Drags, Sliders: Removed power features. Old entry points will pass-through if power=1.0f, otherwise assert + safe fallback. Remove 3 redirection functions (#3361, #1823, #1316, #642) --- docs/CHANGELOG.txt | 32 +++++ imgui.cpp | 8 ++ imgui.h | 27 ++-- imgui_internal.h | 19 +-- imgui_widgets.cpp | 311 +++++++++++++-------------------------------- 5 files changed, 148 insertions(+), 249 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 989f8079..5348ad15 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,32 @@ HOW TO UPDATE? VERSION 1.78 WIP (In Progress) ----------------------------------------------------------------------- +Breaking Changes: + +- Obsoleted use of the trailing 'float power=1.0f' parameter for those functions: [@Shironekoben, @ocornut] + - DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN() + - SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN() + - VSliderFloat(), VSliderScalar() + Replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). + The type of those flags are ImGuiDragFlags and ImGuiSliderFlags (underlying int storage). + Worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. + In short, when calling those functions: + - If you omitted the 'power' parameter (likely!), you are not affected. + - If you set the 'power' parameter to 1.0f (same as previous default value): + - Your compiler may warn on float>int conversion. + - Everything else will work. + - You can replace the 1.0f value with 0 to fix the warning, and be technically correct. + - If you set the 'power' parameter to >1.0f (to enable non-linear editing): + - Your compiler may warn on float>int conversion. + - Code will assert at runtime for IM_ASSERT(power == 1.0f) with the following assert description: + "Call Drag function with ImGuiDragFlags_Logarithmic instead of using the old 'float power' function!". + - In case asserts are disabled, the code will not crash and enable the _Logarithmic flag. + - You can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic + to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + See https://github.com/ocornut/imgui/issues/3361 for all details. + Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). + For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. + Other Changes: - Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. @@ -42,6 +68,12 @@ Other Changes: flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. +- Drag, Slider: Added ImGuiDragFlags and ImGuiSliderFlags parameters. + For float functions they replace the old trailing 'float power=1.0' parameter. + (See #3361 and the "Breaking Changes" block above for all details). +- Drag, Slider: Added ImGuiDragFlags_Logarithmic/ImGuiSliderFlags_Logarithmic flags to + enable logarithmic editing (generally more precision around zero), as a replacement to the old + 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.cpp b/imgui.cpp index a9aabfdb..197ce1f9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,14 @@ 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. + - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). + replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). + worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: + - if you omitted the 'power' parameter (likely!), you are not affected. + - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct. + - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic flag to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + see https://github.com/ocornut/imgui/issues/3361 for all details. + kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. diff --git a/imgui.h b/imgui.h index dc62afc0..59eb6d04 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,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.78 WIP" -#define IMGUI_VERSION_NUM 17703 +#define IMGUI_VERSION_NUM 17704 #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) @@ -467,6 +467,8 @@ namespace ImGui // - 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_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiDragFlags flags=0' argument. + // If you get a warning converting a float to ImGuiDragFlags, read https://github.com/ocornut/imgui/issues/3361 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", ImGuiDragFlags flags = 0); // 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", ImGuiDragFlags flags = 0); 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", ImGuiDragFlags flags = 0); @@ -483,6 +485,8 @@ namespace ImGui // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - 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. + // - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); @@ -1703,23 +1707,20 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { - // OBSOLETED in 1.78 (from July 2020) + // OBSOLETED in 1.78 (from August 2020) // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); + static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } + static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } + static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } + static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.77 (from June 2020) static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupContextItem(str_id, mb); } // Passing a mouse button to ImGuiPopupFlags is legal static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } diff --git a/imgui_internal.h b/imgui_internal.h index c2d58a18..95ce67c0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1979,27 +1979,20 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags); - IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags); + IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, 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 SetNextItemOpen() data, if any. May return true when logging IMGUI_API void TreePushOverrideID(ImGuiID id); - // Internal implementations for some of the exposed functions (use the non-internal versions instead) - IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); - IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); - IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); - IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); // 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, 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, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, 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, ImGuiSliderFlags flags, ImRect* out_grab_bb); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6de8ce12..65021bba 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1997,14 +1997,13 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiDragFlags flags) { 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 is_clamped = (v_min < v_max); const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; - const bool is_power = (power != 1.0f && !is_logarithmic && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); const bool is_locked = (v_min > v_max); if (is_locked) return false; @@ -2043,8 +2042,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // 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 = 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) + if (is_just_activated || is_already_past_limits_and_pushing_outward) { g.DragCurrentAccum = 0.0f; g.DragCurrentAccumDirty = false; @@ -2069,20 +2067,11 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, flags); v_old_ref_for_accum_remainder = v_old_parametric; } - else if (is_power) - { - // Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range - FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); - FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min)); - v_cur = v_min + (SIGNEDTYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min); - v_old_ref_for_accum_remainder = v_old_norm_curved; - } else { v_cur += (SIGNEDTYPE)g.DragCurrentAccum; @@ -2096,15 +2085,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } - else if (is_power) - { - FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); - g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder); - } else { g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v); @@ -2130,9 +2113,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { - IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has a power term been mistakenly cast to flags?"); + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiDragFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2149,32 +2133,30 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v switch (data_type) { - case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } - case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } - case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } - case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } - case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, power, flags); - case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, power, flags); - case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, power, flags); - case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, power, flags); - case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, power, flags); - case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, power, flags); + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, flags); + case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, flags); + case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, flags); + case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, flags); + case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, flags); + case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, flags); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); return false; } -// Internal implementation - see below for entry points -bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. +// Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - if (power != 1.0f) - IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds - ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); @@ -2225,7 +2207,7 @@ bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); // Drag behavior - const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, power, flags); + const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags); if (value_changed) MarkItemEdited(id); @@ -2241,15 +2223,7 @@ bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* return value_changed; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) -{ - return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, 1.0f, flags); -} - -// Internal implementation - see below for entry points -bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2266,7 +2240,7 @@ bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragScalarInternal("", data_type, p_data, v_speed, p_min, p_max, format, power, flags); + value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags); PopID(); PopItemWidth(); p_data = (void*)((char*)p_data + type_size); @@ -2284,11 +2258,6 @@ bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void return value_changed; } -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) -{ - return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, 1.0f, flags); -} - bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); @@ -2309,8 +2278,7 @@ bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } -// Internal implementation -bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragFlags flags) +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2324,14 +2292,14 @@ bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, flo float min = (v_min >= v_max) ? -FLT_MAX : v_min; float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - bool value_changed = DragScalarInternal("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power, flags); + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); max = (v_min >= v_max) ? FLT_MAX : v_max; if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - value_changed |= DragScalarInternal("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power, flags); + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2341,11 +2309,6 @@ bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, flo return value_changed; } -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) -{ - return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, 1.0f, flags); -} - // NB: v_speed is float to allow adjusting the drag speed with more precision bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { @@ -2401,40 +2364,29 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -// Obsolete versions with power parameter +// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, ImGuiDragFlags_None); + ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds + drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + } + return DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, drag_flags); } bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); -} - -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) -{ - return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); + ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds + drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + } + return DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, drag_flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -2462,13 +2414,12 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); - const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) { @@ -2510,19 +2461,6 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return flipped ? (1.0f - result) : result; } - else if (is_power) - { - if (v_clamped < 0.0f) - { - const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min)); - return (1.0f - ImPow(f, 1.0f / power)) * linear_zero_pos; - } - else - { - const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min))); - return linear_zero_pos + ImPow(f, 1.0f / power) * (1.0f - linear_zero_pos); - } - } // Linear slider return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); @@ -2530,14 +2468,13 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); - const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); TYPE result; if (is_logarithmic) @@ -2580,28 +2517,6 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip)); } } - else if (is_power) - { - // Account for power curve scale on both sides of the zero - if (t < linear_zero_pos) - { - // Negative: rescale to the negative range before powering - float a = 1.0f - (t / linear_zero_pos); - a = ImPow(a, power); - result = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); - } - else - { - // Positive: rescale to the positive range before powering - float a; - if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) - a = (t - linear_zero_pos) / (1.0f - linear_zero_pos); - else - a = t; - a = ImPow(a, power); - result = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); - } - } else { // Linear slider @@ -2628,7 +2543,7 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m // FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template -bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; @@ -2636,7 +2551,6 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal; - const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; @@ -2649,21 +2563,6 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ 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); - linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0)); - } - else - { - // Same sign - linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; - } - float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true if (is_logarithmic) { @@ -2703,9 +2602,9 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; - if ((decimal_precision > 0) || is_power) + if (decimal_precision > 0) { delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds if (IsNavInputDown(ImGuiNavInput_TweakSlow)) @@ -2730,7 +2629,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, flags); // Round to user desired precision based on format string v_new = RoundScalarWithFormatT(format, data_type, v_new); @@ -2751,7 +2650,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // 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, logarithmic_zero_epsilon, flags); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); 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); @@ -2767,9 +2666,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // For 32-bit and larger types, slider bounds are limited to half the natural type range. // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. -bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) { - IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has a power term been mistakenly cast to flags?"); + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) @@ -2777,36 +2677,37 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type switch (data_type) { - case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } - case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } - case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } - case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } case ImGuiDataType_S32: IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, flags, out_grab_bb); case ImGuiDataType_U32: IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, flags, out_grab_bb); case ImGuiDataType_S64: IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, flags, out_grab_bb); case ImGuiDataType_U64: IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, flags, out_grab_bb); case ImGuiDataType_Float: IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f); - return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, flags, out_grab_bb); case ImGuiDataType_Double: IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f); - return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, flags, out_grab_bb); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); return false; } -// Internal implementation -bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2863,7 +2764,7 @@ bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, voi // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -2883,14 +2784,8 @@ bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, voi return value_changed; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) -{ - return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, 1.0f, flags); -} - -bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags) +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2907,7 +2802,7 @@ bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, vo PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= SliderScalarInternal("", data_type, v, v_min, v_max, format, power, flags); + value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); @@ -2925,12 +2820,6 @@ bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, vo return value_changed; } -// Add multiple sliders on 1 line for compact edition of multiple components -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) -{ - return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, 1.0f, flags); -} - bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); @@ -2981,8 +2870,7 @@ bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); } -// Internal implementation -bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3022,7 +2910,7 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiSliderFlags_Vertical, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -3041,11 +2929,6 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa return value_changed; } -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) -{ - return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, 1.0f, flags); -} - bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); @@ -3058,45 +2941,27 @@ bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -// Obsolete versions with power parameter +// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) { - return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); + ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + slider_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return SliderScalar(label, data_type, p_data, p_min, p_max, format, slider_flags); } bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) { - return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); -} - -bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) -{ - return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); -} - -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) -{ - return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); -} - -bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) -{ - return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); + ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + slider_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return SliderScalarN(label, data_type, v, components, v_min, v_max, format, slider_flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS From 170d02bd99f0d3d5d01e3b5ace51160c5c0f7cc1 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 17:39:22 +0200 Subject: [PATCH 191/223] Drags, Sliders: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force clamping value when using CTRL+Click to type in a value manually. (#1829, #3209) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 8 +++++-- imgui_demo.cpp | 39 +++++++++++++++++++++++++++---- imgui_widgets.cpp | 57 ++++++++++++++++++++++------------------------ 4 files changed, 70 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5348ad15..ebdfb898 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -74,6 +74,8 @@ Other Changes: - Drag, Slider: Added ImGuiDragFlags_Logarithmic/ImGuiSliderFlags_Logarithmic flags to enable logarithmic editing (generally more precision around zero), as a replacement to the old 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] +- Drag, Slider: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force + clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.h b/imgui.h index 59eb6d04..1bf0f4a5 100644 --- a/imgui.h +++ b/imgui.h @@ -464,6 +464,7 @@ namespace ImGui // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - 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. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - 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_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. @@ -485,6 +486,7 @@ namespace ImGui // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - 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. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. @@ -1293,7 +1295,8 @@ enum ImGuiDragFlags_ { ImGuiDragFlags_None = 0, ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. - ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiDragFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) }; // Flags for SliderFloat(), SliderInt() etc. @@ -1301,7 +1304,8 @@ enum ImGuiSliderFlags_ { ImGuiSliderFlags_None = 0, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. - ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiSliderFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 587964f6..62a7d1fe 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1488,6 +1488,38 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } + if (ImGui::TreeNode("Drag/Slider Flags")) + { + // Demonstrate using advanced flags for DragXXX functions + static ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + ImGui::CheckboxFlags("ImGuiDragFlags_ClampOnInput", (unsigned int*)&drag_flags, ImGuiDragFlags_ClampOnInput); + ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); + ImGui::CheckboxFlags("ImGuiDragFlags_Logarithmic", (unsigned int*)&drag_flags, ImGuiDragFlags_Logarithmic); + ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + + static float drag_f = 0.5f; + static int drag_i = 50; + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%f", drag_flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%f", drag_flags); + ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", drag_flags); + + // Demonstrate using advanced flags for SliderXXX functions + static ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_ClampOnInput); + ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&slider_flags, ImGuiSliderFlags_Logarithmic); + ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + + static float slider_f = 0.5f; + static int slider_i = 50; + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, NULL, slider_flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, NULL, slider_flags); + + ImGui::TreePop(); + } + if (ImGui::TreeNode("Range Widgets")) { static float begin = 10, end = 90; @@ -3853,10 +3885,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" "Using those settings here will give you poor quality results."); static float window_scale = 1.0f; - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale only this window - ImGui::SetWindowFontScale(IM_MAX(window_scale, MIN_SCALE)); - if (ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale everything - io.FontGlobalScale = IM_MAX(io.FontGlobalScale, MIN_SCALE); + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput)) // Scale only this window + ImGui::SetWindowFontScale(window_scale); + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput); // Scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 65021bba..7b3bb996 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1910,10 +1910,11 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b } template -static bool ClampBehaviorT(T* v, T v_min, T v_max) +static bool ClampBehaviorT(T* v, const T* v_min, const T* v_max) { - if (*v < v_min) { *v = v_min; return true; } - if (*v > v_max) { *v = v_max; return true; } + // Clamp, both sides are optional + if (v_min && *v < *v_min) { *v = *v_min; return true; } + if (v_max && *v > *v_max) { *v = *v_max; return true; } return false; } @@ -1921,16 +1922,16 @@ bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_m { switch (data_type) { - case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, *(const ImS8* )p_min, *(const ImS8* )p_max); - case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, *(const ImU8* )p_min, *(const ImU8* )p_max); - case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, *(const ImS16* )p_min, *(const ImS16* )p_max); - case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, *(const ImU16* )p_min, *(const ImU16* )p_max); - case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, *(const ImS32* )p_min, *(const ImS32* )p_max); - case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, *(const ImU32* )p_min, *(const ImU32* )p_max); - case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, *(const ImS64* )p_min, *(const ImS64* )p_max); - case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, *(const ImU64* )p_min, *(const ImU64* )p_max); - case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, *(const float* )p_min, *(const float* )p_max); - case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, *(const double*)p_min, *(const double*)p_max); + case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); + case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); + case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); + case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); + case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); + case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); + case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); + case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); + case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, (const float* )p_min, (const float* )p_max); + case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, (const double*)p_min, (const double*)p_max); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); @@ -2197,9 +2198,12 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, } } - // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); + { + // Only clamp CTRL+Click input when ImGuiDragFlags_ClampInput is set + const bool is_clamp_input = (flags & ImGuiDragFlags_ClampOnInput) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + } // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -2753,9 +2757,12 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat } } - // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); + { + // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + } // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -3081,20 +3088,10 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* return value_changed; } -// Note that Drag/Slider functions are currently NOT forwarding the min/max values clamping values! +// Note that Drag/Slider functions are only forwarding the min/max values clamping values if the +// ImGuiDragFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. -// In the future we should add flags to Slider/Drag to specify how to enforce min/max values with CTRL+Click. -// See GitHub issues #1829 and #3209 -// In the meanwhile, you can easily "wrap" those functions to enforce clamping, using wrapper functions, e.g. -// bool SliderFloatClamp(const char* label, float* v, float v_min, float v_max) -// { -// float v_backup = *v; -// if (!SliderFloat(label, v, v_min, v_max)) -// return false; -// *v = ImClamp(*v, v_min, v_max); -// return v_backup != *v; -// } bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) { ImGuiContext& g = *GImGui; @@ -3117,7 +3114,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG // Apply new value (or operations) then clamp DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL); - if (p_clamp_min && p_clamp_max) + if (p_clamp_min || p_clamp_max) DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); // Only mark as edited if new value is different From 8018623c5b478e050fbfd8df1882ca94cccaeaec Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 23:01:10 +0200 Subject: [PATCH 192/223] Drags, Sliders: Added ImGuiDragFlags_NoRoundToFormat / ImGuiSliderFlags_NoRoundToFormat flags (#642) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 6 ++++-- imgui_demo.cpp | 18 ++++++++++++------ imgui_widgets.cpp | 6 ++++-- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ebdfb898..2936c201 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,8 @@ Other Changes: 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] - Drag, Slider: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). +- Drag, Slider: Added ImGuiDragFlags_NoRoundToFormat/ImGuiSliderFlags_NoRoundToFormat flags + to disable rounding underlying value to match precision of the display format string. (#642) - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.h b/imgui.h index 1bf0f4a5..feaeb811 100644 --- a/imgui.h +++ b/imgui.h @@ -1296,7 +1296,8 @@ enum ImGuiDragFlags_ ImGuiDragFlags_None = 0, ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiDragFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) + ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) + ImGuiDragFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) }; // Flags for SliderFloat(), SliderInt() etc. @@ -1305,7 +1306,8 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_None = 0, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiSliderFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) + ImGuiSliderFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 62a7d1fe..1f737cc5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1496,13 +1496,16 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); ImGui::CheckboxFlags("ImGuiDragFlags_Logarithmic", (unsigned int*)&drag_flags, ImGuiDragFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + ImGui::CheckboxFlags("ImGuiDragFlags_NoRoundToFormat", (unsigned int*)&drag_flags, ImGuiDragFlags_NoRoundToFormat); + ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); static float drag_f = 0.5f; static int drag_i = 50; - ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%f", drag_flags); - ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%f", drag_flags); + ImGui::Text("Underlying float value: %f", drag_f); + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", drag_flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", drag_flags); ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", drag_flags); // Demonstrate using advanced flags for SliderXXX functions @@ -1511,11 +1514,14 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&slider_flags, ImGuiSliderFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoRoundToFormat); + ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); static float slider_f = 0.5f; static int slider_i = 50; - ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, NULL, slider_flags); - ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, NULL, slider_flags); + ImGui::Text("Underlying float value: %f", slider_f); + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", slider_flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", slider_flags); ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7b3bb996..239c125d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2079,7 +2079,8 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const } // Round to user desired precision based on format string - v_cur = RoundScalarWithFormatT(format, data_type, v_cur); + if (!(flags & ImGuiDragFlags_NoRoundToFormat)) + v_cur = RoundScalarWithFormatT(format, data_type, v_cur); // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false; @@ -2636,7 +2637,8 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, flags); // Round to user desired precision based on format string - v_new = RoundScalarWithFormatT(format, data_type, v_new); + if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); // Apply result if (*v != v_new) From f75b29e7be08b7abeb2df295a087cb79cff0252d Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 Jul 2020 13:41:14 +0200 Subject: [PATCH 193/223] Drags, Sliders: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning widget into a text input with CTRL+Click or Nav Enter. --- docs/CHANGELOG.txt | 2 ++ imgui.h | 10 ++++++---- imgui_demo.cpp | 4 ++++ imgui_widgets.cpp | 14 ++++++++------ 4 files changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2936c201..23959298 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -78,6 +78,8 @@ Other Changes: clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). - Drag, Slider: Added ImGuiDragFlags_NoRoundToFormat/ImGuiSliderFlags_NoRoundToFormat flags to disable rounding underlying value to match precision of the display format string. (#642) +- Drag, Slider: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning + widget into a text input with CTRL+Click or Nav Enter. - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.h b/imgui.h index feaeb811..d5eb1476 100644 --- a/imgui.h +++ b/imgui.h @@ -1296,8 +1296,9 @@ enum ImGuiDragFlags_ ImGuiDragFlags_None = 0, ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) - ImGuiDragFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiDragFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiDragFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiDragFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget }; // Flags for SliderFloat(), SliderInt() etc. @@ -1306,8 +1307,9 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_None = 0, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) - ImGuiSliderFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiSliderFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1f737cc5..6771367c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1498,6 +1498,8 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); ImGui::CheckboxFlags("ImGuiDragFlags_NoRoundToFormat", (unsigned int*)&drag_flags, ImGuiDragFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); + ImGui::CheckboxFlags("ImGuiDragFlags_NoInput", (unsigned int*)&drag_flags, ImGuiDragFlags_NoInput); + ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); static float drag_f = 0.5f; static int drag_i = 50; @@ -1516,6 +1518,8 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoInput); + ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); static float slider_f = 0.5f; static int slider_i = 50; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 239c125d..fddb2cb1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2179,10 +2179,11 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Tabbing or CTRL-clicking on Drag turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - bool temp_input_is_active = TempInputIsActive(id); + const bool temp_input_allowed = (flags & ImGuiDragFlags_NoInput) == 0; + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - const bool focus_requested = FocusableItemRegister(window, id); + const bool focus_requested = temp_input_allowed && FocusableItemRegister(window, 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) @@ -2191,7 +2192,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, SetFocusID(id, window); FocusWindow(window); g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); - if (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id) + if (temp_input_allowed && (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id)) { temp_input_is_active = true; FocusableItemUnregister(window); @@ -2740,10 +2741,11 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Tabbing or CTRL-clicking on Slider turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - bool temp_input_is_active = TempInputIsActive(id); + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - const bool focus_requested = FocusableItemRegister(window, id); + const bool focus_requested = temp_input_allowed && FocusableItemRegister(window, id); const bool clicked = (hovered && g.IO.MouseClicked[0]); if (focus_requested || clicked || g.NavActivateId == id || g.NavInputId == id) { @@ -2751,7 +2753,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat SetFocusID(id, window); FocusWindow(window); g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); - if (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id) + if (temp_input_allowed && (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id)) { temp_input_is_active = true; FocusableItemUnregister(window); From fa279a6aa047b6ab01bca55424b44b4046ca1e20 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Sun, 26 Jul 2020 11:42:06 +0900 Subject: [PATCH 194/223] Drags, Sliders: Added deadzone to make selecting 0.0 on linear sliders easier, slider navigation delta accumulation. (#3361, #1823, #1316, #642) --- imgui.cpp | 1 + imgui.h | 1 + imgui_demo.cpp | 1 + imgui_internal.h | 8 +++-- imgui_widgets.cpp | 74 ++++++++++++++++++++++++++++++++++++----------- 5 files changed, 66 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 197ce1f9..ad676996 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -933,6 +933,7 @@ ImGuiStyle::ImGuiStyle() 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. + LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. 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. TabMinWidthForUnselectedCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. diff --git a/imgui.h b/imgui.h index d5eb1476..6fca6f2b 100644 --- a/imgui.h +++ b/imgui.h @@ -1473,6 +1473,7 @@ struct ImGuiStyle float ScrollbarRounding; // Radius of grab corners for scrollbar. float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. float TabMinWidthForUnselectedCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6771367c..22301ed7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3784,6 +3784,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) 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("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); ImGui::Text("Alignment"); ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); diff --git a/imgui_internal.h b/imgui_internal.h index 95ce67c0..8f7ab0ff 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1280,6 +1280,8 @@ struct ImGuiContext float ColorEditLastSat; // Backup of last Saturation associated to LastColor[3], so we can restore Saturation in lossy RGB<>HSV round trips float ColorEditLastColor[3]; ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker. + float SliderCurrentAccum; // Accumulated slider delta when using navigation controls. + bool SliderCurrentAccumDirty; // Has the accumulated slider delta changed since last time we tried to apply it? 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 @@ -1433,6 +1435,8 @@ struct ImGuiContext ColorEditOptions = ImGuiColorEditFlags__OptionsDefault; ColorEditLastHue = ColorEditLastSat = 0.0f; ColorEditLastColor[0] = ColorEditLastColor[1] = ColorEditLastColor[2] = FLT_MAX; + SliderCurrentAccum = 0.0f; + SliderCurrentAccumDirty = false; DragCurrentAccumDirty = false; DragCurrentAccum = 0.0f; DragSpeedDefaultRatio = 1.0f / 100.0f; @@ -1991,8 +1995,8 @@ namespace ImGui // 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, T v_min, T v_max, const char* format, 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, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fddb2cb1..64e3bfca 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2061,6 +2061,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + const float zero_deadzone_size = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. @@ -2068,9 +2069,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, flags); + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); v_old_ref_for_accum_remainder = v_old_parametric; } else @@ -2087,7 +2088,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } else @@ -2420,7 +2421,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; @@ -2456,9 +2457,9 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m if (v == 0.0f) result = zero_point; // Special case for exactly zero else if (v < 0.0f) - result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point; + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * (zero_point - zero_deadzone_size); else - result = zero_point + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point)); + result = zero_point + zero_deadzone_size + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - (zero_point + zero_deadzone_size))); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); @@ -2474,7 +2475,7 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; @@ -2510,12 +2511,12 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts { float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space - if (t_with_flip == zero_point) + if ((t_with_flip >= (zero_point - zero_deadzone_size)) && (t_with_flip <= (zero_point + zero_deadzone_size))) result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) else if (t_with_flip < zero_point) - result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point)))); + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / (zero_point - zero_deadzone_size))))); else - result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point) / (1.0f - zero_point)))); + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - (zero_point + zero_deadzone_size)) / (1.0f - (zero_point + zero_deadzone_size))))); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); @@ -2567,14 +2568,16 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ 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_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + float zero_deadzone_size = 0.0f; // Only valid when is_logarithmic is true if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + zero_deadzone_size = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); } // Process interacting with the slider @@ -2602,13 +2605,15 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ { const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y; - if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + + if (g.ActiveIdIsJustActivated) { - ClearActiveID(); + g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation + g.SliderCurrentAccumDirty = false; } - else if (delta != 0.0f) + + if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if (decimal_precision > 0) { @@ -2625,17 +2630,52 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } if (IsNavInputDown(ImGuiNavInput_TweakFast)) delta *= 10.0f; + + g.SliderCurrentAccum += delta; + g.SliderCurrentAccumDirty = true; + + delta = g.SliderCurrentAccum; + } + + if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + { + ClearActiveID(); + } + else if (g.SliderCurrentAccumDirty) + { + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + set_new_value = true; if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits + { set_new_value = false; + g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate + } else + { + float old_clicked_t = clicked_t; + clicked_t = ImSaturate(clicked_t + delta); + + // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); + float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + + if (delta > 0) + g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); + else + g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta); + } + + g.SliderCurrentAccumDirty = false; } } if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); // Round to user desired precision based on format string if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) @@ -2657,7 +2697,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); 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); From fb0f2ebd41b305d0b6f3a4910b30129c1481520b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 Jul 2020 15:15:09 +0200 Subject: [PATCH 195/223] Drags, Sliders: Tweaks. --- docs/CHANGELOG.txt | 4 ++- docs/TODO.txt | 2 +- imgui.cpp | 1 + imgui_widgets.cpp | 81 ++++++++++++++++++++++++---------------------- 4 files changed, 47 insertions(+), 41 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 23959298..9cf625c5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,7 +59,7 @@ Breaking Changes: to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. See https://github.com/ocornut/imgui/issues/3361 for all details. Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). - For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. + For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. Other Changes: @@ -80,6 +80,8 @@ Other Changes: to disable rounding underlying value to match precision of the display format string. (#642) - Drag, Slider: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning widget into a text input with CTRL+Click or Nav Enter. +- Nav, Slider: Fix using keyboard/gamepad controls with certain logarithmic sliders where + pushing a direction near zero values would be cancelled out. [@Shironekoben] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/docs/TODO.txt b/docs/TODO.txt index c0f01841..1f6f8b94 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -181,7 +181,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - slider: step option (#1183) - slider style: fill % of the bar instead of positioning a drag. - knob: rotating knob widget (#942) - - drag float: power/logarithmic slider and drags are weird. (#1316) + - drag float: support for reversed drags (min > max) (removed is_locked, also see fdc526e) - drag float: up/down axis - 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) diff --git a/imgui.cpp b/imgui.cpp index ad676996..e29dc6ce 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -973,6 +973,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); + LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor); TabRounding = ImFloor(TabRounding * scale_factor); if (TabMinWidthForUnselectedCloseButton != FLT_MAX) TabMinWidthForUnselectedCloseButton = ImFloor(TabMinWidthForUnselectedCloseButton * scale_factor); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 64e3bfca..d42f4b20 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2060,8 +2060,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_cur = *v; FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; + IM_ASSERT(ImGuiDragFlags_Logarithmic == ImGuiSliderFlags_Logarithmic); + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true - const float zero_deadzone_size = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) + const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. @@ -2069,9 +2071,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); v_old_ref_for_accum_remainder = v_old_parametric; } else @@ -2088,7 +2090,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } else @@ -2421,7 +2423,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; @@ -2453,13 +2455,15 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m result = 1.0f; // Workaround for values that are in-range but above our fudge else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions { - float zero_point = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + float zero_point_center = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; if (v == 0.0f) - result = zero_point; // Special case for exactly zero + result = zero_point_center; // Special case for exactly zero else if (v < 0.0f) - result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * (zero_point - zero_deadzone_size); + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L; else - result = zero_point + zero_deadzone_size + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - (zero_point + zero_deadzone_size))); + result = zero_point_snap_R + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point_snap_R)); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); @@ -2475,7 +2479,7 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; @@ -2510,13 +2514,15 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts { - float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space - if ((t_with_flip >= (zero_point - zero_deadzone_size)) && (t_with_flip <= (zero_point + zero_deadzone_size))) + float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; + if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R) result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) - else if (t_with_flip < zero_point) - result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / (zero_point - zero_deadzone_size))))); + else if (t_with_flip < zero_point_center) + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L)))); else - result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - (zero_point + zero_deadzone_size)) / (1.0f - (zero_point + zero_deadzone_size))))); + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point_snap_R) / (1.0f - zero_point_snap_R)))); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); @@ -2548,7 +2554,7 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m return result; } -// FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. +// FIXME: Move more of the code into SliderBehavior() template bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) { @@ -2568,16 +2574,16 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ 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_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true - float zero_deadzone_size = 0.0f; // Only valid when is_logarithmic is true + float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); - zero_deadzone_size = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); + zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); } // Process interacting with the slider @@ -2603,49 +2609,46 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { - const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); - float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y; - if (g.ActiveIdIsJustActivated) { g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation g.SliderCurrentAccumDirty = false; } - if (delta != 0.0f) + const ImVec2 input_delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); + float input_delta = (axis == ImGuiAxis_X) ? input_delta2.x : -input_delta2.y; + if (input_delta != 0.0f) { const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if (decimal_precision > 0) { - delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds + input_delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds if (IsNavInputDown(ImGuiNavInput_TweakSlow)) - delta /= 10.0f; + input_delta /= 10.0f; } else { if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow)) - delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps + input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps else - delta /= 100.0f; + input_delta /= 100.0f; } if (IsNavInputDown(ImGuiNavInput_TweakFast)) - delta *= 10.0f; + input_delta *= 10.0f; - g.SliderCurrentAccum += delta; + g.SliderCurrentAccum += input_delta; g.SliderCurrentAccumDirty = true; - - delta = g.SliderCurrentAccum; } - + + float delta = g.SliderCurrentAccum; if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) { ClearActiveID(); } else if (g.SliderCurrentAccumDirty) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); - set_new_value = true; if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits { set_new_value = false; @@ -2653,15 +2656,15 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else { + set_new_value = true; float old_clicked_t = clicked_t; - clicked_t = ImSaturate(clicked_t + delta); // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) v_new = RoundScalarWithFormatT(format, data_type, v_new); - float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); if (delta > 0) g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); @@ -2675,7 +2678,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); // Round to user desired precision based on format string if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) @@ -2697,7 +2700,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); 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); From 7f8f0096d81d26b942fb40128ae8c1a28597d90d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 Jul 2020 15:34:14 +0200 Subject: [PATCH 196/223] Internals: Renamed SliderCalcRatioFromValueT() -> ScaleRatioFromValueT(), SliderCalcValueFromRatioT() -> ScaleValueFromRatioT(). Replaced drag/slider flags with a single bool is_logarithmic in those functions. --- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 34 ++++++++++++++++------------------ 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 8f7ab0ff..def3c4fb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1993,10 +1993,10 @@ 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 float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, 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, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d42f4b20..b6229890 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2060,8 +2060,6 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_cur = *v; FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; - IM_ASSERT(ImGuiDragFlags_Logarithmic == ImGuiSliderFlags_Logarithmic); - float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) if (is_logarithmic) @@ -2071,9 +2069,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float v_old_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + v_cur = ScaleValueFromRatioT(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); v_old_ref_for_accum_remainder = v_old_parametric; } else @@ -2090,7 +2088,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float v_new_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } else @@ -2403,6 +2401,8 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data //------------------------------------------------------------------------- // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. //------------------------------------------------------------------------- +// - ScaleRatioFromValueT<> [Internal] +// - ScaleValueFromRatioT<> [Internal] // - SliderBehaviorT<>() [Internal] // - SliderBehavior() [Internal] // - SliderScalar() @@ -2421,14 +2421,14 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data // - VSliderInt() //------------------------------------------------------------------------- -// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) +// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) +float ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) { if (v_min == v_max) return 0.0f; + IM_UNUSED(data_type); - const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) { @@ -2477,15 +2477,13 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); } -// Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) +// Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) +TYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) { if (v_min == v_max) return (TYPE)0.0f; - const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); TYPE result; if (is_logarithmic) @@ -2647,8 +2645,8 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (g.SliderCurrentAccumDirty) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); - + clicked_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits { set_new_value = false; @@ -2661,10 +2659,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ clicked_t = ImSaturate(clicked_t + delta); // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) v_new = RoundScalarWithFormatT(format, data_type, v_new); - float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float new_clicked_t = ScaleRatioFromValueT(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (delta > 0) g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); @@ -2678,7 +2676,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); // Round to user desired precision based on format string if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) @@ -2700,7 +2698,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float grab_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); 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); From f32663b33c62187fa12be591f668896e3be5b33e Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 Jul 2020 16:23:38 +0200 Subject: [PATCH 197/223] Drags, Sliders: Removed locking behavior with min > max (added in 1.73) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui_demo.cpp | 2 +- imgui_internal.h | 6 ++++-- imgui_widgets.cpp | 41 ++++++++++++++++++++--------------------- 5 files changed, 28 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9cf625c5..dfe76747 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,8 @@ Breaking Changes: See https://github.com/ocornut/imgui/issues/3361 for all details. Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. +- DragInt, DragFloat, DragScalar: Obsoleted use of v_min > v_max to lock edits (introduced in 1.73, this was not + demoed nor documented much, will be replaced a more generic ReadOnly feature). Other Changes: diff --git a/imgui.cpp b/imgui.cpp index e29dc6ce..c78ed393 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -380,6 +380,7 @@ CODE - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic flag to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. see https://github.com/ocornut/imgui/issues/3361 for all details. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. + - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiDragFlags_ReadOnly internal flag in the meantime. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 22301ed7..5578601f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1534,7 +1534,7 @@ static void ShowDemoWindowWidgets() { static float begin = 10, end = 90; static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiDragFlags_ClampOnInput); ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); ImGui::TreePop(); diff --git a/imgui_internal.h b/imgui_internal.h index def3c4fb..6d1c1cb6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -634,13 +634,15 @@ enum ImGuiButtonFlagsPrivate_ // Extend ImGuiDragFlags_ enum ImGuiDragFlagsPrivate_ { - ImGuiDragFlags_Vertical = 1 << 20 // Should this widget be orientated vertically? + ImGuiDragFlags_Vertical = 1 << 20, // Should this widget be orientated vertically? + ImGuiDragFlags_ReadOnly = 1 << 21 }; // Extend ImGuiSliderFlags_ enum ImGuiSliderFlagsPrivate_ { - ImGuiSliderFlags_Vertical = 1 << 20 // Should this slider be orientated vertically? + ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically? + ImGuiSliderFlags_ReadOnly = 1 << 21 }; // Extend ImGuiSelectableFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b6229890..52075823 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2005,9 +2005,6 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; - const bool is_locked = (v_min > v_max); - if (is_locked) - return false; // Default tweak speed if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX)) @@ -2131,7 +2128,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } if (g.ActiveId != id) return false; - if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiDragFlags_ReadOnly)) return false; switch (data_type) @@ -2285,6 +2282,7 @@ bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } +// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); @@ -2296,17 +2294,17 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); - float min = (v_min >= v_max) ? -FLT_MAX : v_min; - float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, flags); + float min_min = (v_min >= v_max) ? -FLT_MAX : v_min; + float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); - max = (v_min >= v_max) ? FLT_MAX : v_max; - if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, flags); + float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + float max_max = (v_min >= v_max) ? FLT_MAX : v_max; + ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2337,6 +2335,7 @@ bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } +// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); @@ -2348,17 +2347,17 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); - int min = (v_min >= v_max) ? INT_MIN : v_min; - int max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format, flags); + int min_min = (v_min >= v_max) ? INT_MIN : v_min; + int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); - max = (v_min >= v_max) ? INT_MAX : v_max; - if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format, flags); + int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + int max_max = (v_min >= v_max) ? INT_MAX : v_max; + ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2720,7 +2719,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; - if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) return false; switch (data_type) From d3fcc37e9eb76f1c82ccfd44f177e559234a553b Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Aug 2020 12:27:40 +0200 Subject: [PATCH 198/223] Update Emscripten readme about local XHR requests (#3412) --- examples/example_emscripten/README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten/README.md index dcb7c1a7..597ffaf7 100644 --- a/examples/example_emscripten/README.md +++ b/examples/example_emscripten/README.md @@ -7,6 +7,13 @@ - Then build using `make` while in the `example_emscripten/` directory. -- Note that Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: +- For local testing, you may need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
+_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ +
Easy local webserver: _"For example, Python has one built in, `python -m http.server` in Python 3 or `python -m SimpleHTTPServer` in Python 2. After doing that, you can visit http://localhost:8000/."_ + +Obsolete features: + +- Emscripten 2.0 (August 2020) obsoleted the fastcomp back-end, only llvm is supported. +- Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: `#EMS += -s BINARYEN_TRAP_MODE=clamp` From 14539b3ed2c0bb207967a7c9a8730c8662ccd521 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Aug 2020 12:34:19 +0200 Subject: [PATCH 199/223] Update Emscripten readme about emrun (#3412) --- examples/example_emscripten/README.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten/README.md index 597ffaf7..42bab014 100644 --- a/examples/example_emscripten/README.md +++ b/examples/example_emscripten/README.md @@ -1,19 +1,20 @@ -# How to Build +## 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 - +- You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. - Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools. - - Then build using `make` while in the `example_emscripten/` directory. -- For local testing, you may need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
+## How to Run + +To run on a local machine: +- Generally you may need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ -
Easy local webserver: _"For example, Python has one built in, `python -m http.server` in Python 3 or `python -m SimpleHTTPServer` in Python 2. After doing that, you can visit http://localhost:8000/."_ +- Emscripten SDK has a handy `emrun` command: `emrun example_emscripten.html` which will spawn a temporary local webserver. See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. +- Otherwise you may use Python builtin webserver: `python -m http.server` in Python 3 or `python -m SimpleHTTPServer` in Python 2. After doing that, you can visit http://localhost:8000/. -Obsolete features: +## Obsolete features: - Emscripten 2.0 (August 2020) obsoleted the fastcomp back-end, only llvm is supported. -- Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: - -`#EMS += -s BINARYEN_TRAP_MODE=clamp` +- Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: `#EMS += -s BINARYEN_TRAP_MODE=clamp` From b36d1d465dc25488455a6ab728d322e57b2fed3e Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Aug 2020 11:53:04 +0200 Subject: [PATCH 200/223] Docking: Untangle a little bit of the ActiveIdClickOffset mess. --- imgui.cpp | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 75699181..fdc76f7a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3414,7 +3414,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; g.ActiveIdNoClearOnFocusLoss = true; - g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos; bool can_move_window = true; if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) @@ -3447,15 +3447,9 @@ void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* nod const bool clicked = IsMouseClicked(0); const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f); if (can_undock_node && dragging) - { - DockContextQueueUndockNode(&g, node); - g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; - } + DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window) - { StartMouseMovingWindow(window); - g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos; - } } // Handle mouse moving window @@ -12775,11 +12769,10 @@ static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWind { ImGuiContext& g = *GImGui; IM_ASSERT(node->WantMouseMove == true); - ImVec2 backup_active_click_offset = g.ActiveIdClickOffset; StartMouseMovingWindow(window); + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. node->WantMouseMove = false; - g.ActiveIdClickOffset = backup_active_click_offset; } // Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. @@ -13296,7 +13289,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w window->DockTabItemRect = host_window->DC.LastItemRect; // Update navigation ID on menu layer - if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << 1)) == 0) + if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0) host_window->NavLastIds[1] = window->ID; } } From c6b01e8e1d12b246925842013a6d30e5024a94fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Aug 2020 17:02:58 +0200 Subject: [PATCH 201/223] Drag, Sliders: Merged ImGuiDragFlags back into ImGuiSliderFlags. (#3361, #1823, #1316, #642, #1829, #3209) Technically API breaking (but ImGuiDragFlags were pushed on master 16 hours ago) --- docs/CHANGELOG.txt | 29 ++++++++++--------- imgui.cpp | 4 +-- imgui.h | 56 +++++++++++++++---------------------- imgui_demo.cpp | 53 +++++++++++++++-------------------- imgui_internal.h | 11 ++------ imgui_widgets.cpp | 70 +++++++++++++++++++++++----------------------- 6 files changed, 98 insertions(+), 125 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dfe76747..0520ca9f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,8 +41,7 @@ Breaking Changes: - DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN() - SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN() - VSliderFloat(), VSliderScalar() - Replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). - The type of those flags are ImGuiDragFlags and ImGuiSliderFlags (underlying int storage). + Replaced the 'float power=1.0f' argument with ImGuiSliderFlags flags defaulting to 0 (as with all our flags). Worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. In short, when calling those functions: - If you omitted the 'power' parameter (likely!), you are not affected. @@ -53,10 +52,10 @@ Breaking Changes: - If you set the 'power' parameter to >1.0f (to enable non-linear editing): - Your compiler may warn on float>int conversion. - Code will assert at runtime for IM_ASSERT(power == 1.0f) with the following assert description: - "Call Drag function with ImGuiDragFlags_Logarithmic instead of using the old 'float power' function!". + "Call Drag function with ImGuiSliderFlags_Logarithmic instead of using the old 'float power' function!". - In case asserts are disabled, the code will not crash and enable the _Logarithmic flag. - - You can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic - to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + - You can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert + and get a _similar_ effect as previous uses of power >1.0f. See https://github.com/ocornut/imgui/issues/3361 for all details. Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. @@ -70,18 +69,18 @@ Other Changes: flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. -- Drag, Slider: Added ImGuiDragFlags and ImGuiSliderFlags parameters. +- Drag, Slider: ImGuiSliderFlags parameters. For float functions they replace the old trailing 'float power=1.0' parameter. (See #3361 and the "Breaking Changes" block above for all details). -- Drag, Slider: Added ImGuiDragFlags_Logarithmic/ImGuiSliderFlags_Logarithmic flags to - enable logarithmic editing (generally more precision around zero), as a replacement to the old - 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] -- Drag, Slider: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force - clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). -- Drag, Slider: Added ImGuiDragFlags_NoRoundToFormat/ImGuiSliderFlags_NoRoundToFormat flags - to disable rounding underlying value to match precision of the display format string. (#642) -- Drag, Slider: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning - widget into a text input with CTRL+Click or Nav Enter. +- Drag, Slider: Added ImGuiSliderFlags_Logarithmic flags to enable logarithmic editing + (generally more precision around zero), as a replacement to the old 'float power' parameter + which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] +- Drag, Slider: Added ImGuiSliderFlags_ClampOnInput flags to force clamping value when using + CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). +- Drag, Slider: Added ImGuiSliderFlags_NoRoundToFormat flags to disable rounding underlying + value to match precision of the display format string. (#642) +- Drag, Slider: Added ImGuiSliderFlags_NoInput to disable turning widget into a text input + with CTRL+Click or Nav Enter. - Nav, Slider: Fix using keyboard/gamepad controls with certain logarithmic sliders where pushing a direction near zero values would be cancelled out. [@Shironekoben] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both diff --git a/imgui.cpp b/imgui.cpp index c78ed393..59415898 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -377,10 +377,10 @@ CODE worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: - if you omitted the 'power' parameter (likely!), you are not affected. - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct. - - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic flag to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. see https://github.com/ocornut/imgui/issues/3361 for all details. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. - - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiDragFlags_ReadOnly internal flag in the meantime. + - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. diff --git a/imgui.h b/imgui.h index 6fca6f2b..0ddf24cd 100644 --- a/imgui.h +++ b/imgui.h @@ -157,7 +157,6 @@ typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: f typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() -typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragFloat(), DragInt() etc. 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. @@ -165,7 +164,7 @@ typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: f typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super) typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() -typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderFloat(), SliderInt() etc. +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() @@ -460,7 +459,7 @@ namespace ImGui IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1); - // Widgets: Drags + // Widgets: Drag Sliders // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - 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. @@ -468,22 +467,23 @@ namespace ImGui // - 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_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiDragFlags flags=0' argument. - // If you get a warning converting a float to ImGuiDragFlags, read https://github.com/ocornut/imgui/issues/3361 - 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", ImGuiDragFlags flags = 0); // 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", ImGuiDragFlags flags = 0); - 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", ImGuiDragFlags flags = 0); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragFlags flags = 0); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragFlags flags = 0); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); - - // Widgets: Sliders + // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + 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", ImGuiSliderFlags flags = 0); // 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", ImGuiSliderFlags flags = 0); + 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", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Regular Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - 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. // - Format string may also be set to NULL or use the default format ("%f" or "%d"). @@ -1290,26 +1290,16 @@ enum ImGuiColorEditFlags_ #endif }; -// Flags for DragFloat(), DragInt() etc. -enum ImGuiDragFlags_ -{ - ImGuiDragFlags_None = 0, - ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. - ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiDragFlags_NoRoundToFormat with this if using a format-string with small amount of digits. - ImGuiDragFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) - ImGuiDragFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget -}; - -// Flags for SliderFloat(), SliderInt() etc. +// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. enum ImGuiSliderFlags_ { ImGuiSliderFlags_None = 0, - ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) - ImGuiSliderFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_InvalidMask_ = 0x7000000F // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5578601f..28cef963 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1490,42 +1490,33 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Drag/Slider Flags")) { - // Demonstrate using advanced flags for DragXXX functions - static ImGuiDragFlags drag_flags = ImGuiDragFlags_None; - ImGui::CheckboxFlags("ImGuiDragFlags_ClampOnInput", (unsigned int*)&drag_flags, ImGuiDragFlags_ClampOnInput); + // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! + static ImGuiSliderFlags flags = ImGuiSliderFlags_None; + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", (unsigned int*)&flags, ImGuiSliderFlags_ClampOnInput); ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); - ImGui::CheckboxFlags("ImGuiDragFlags_Logarithmic", (unsigned int*)&drag_flags, ImGuiDragFlags_Logarithmic); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&flags, ImGuiSliderFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); - ImGui::CheckboxFlags("ImGuiDragFlags_NoRoundToFormat", (unsigned int*)&drag_flags, ImGuiDragFlags_NoRoundToFormat); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&flags, ImGuiSliderFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); - ImGui::CheckboxFlags("ImGuiDragFlags_NoInput", (unsigned int*)&drag_flags, ImGuiDragFlags_NoInput); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&flags, ImGuiSliderFlags_NoInput); ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + // Drags static float drag_f = 0.5f; static int drag_i = 50; ImGui::Text("Underlying float value: %f", drag_f); - ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", drag_flags); - ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", drag_flags); - ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", drag_flags); - - // Demonstrate using advanced flags for SliderXXX functions - static ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; - ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_ClampOnInput); - ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); - ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&slider_flags, ImGuiSliderFlags_Logarithmic); - ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoRoundToFormat); - ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoInput); - ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags); + ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags); + // Sliders static float slider_f = 0.5f; static int slider_i = 50; ImGui::Text("Underlying float value: %f", slider_f); - ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", slider_flags); - ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", slider_flags); + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", flags); ImGui::TreePop(); } @@ -1534,7 +1525,7 @@ static void ShowDemoWindowWidgets() { static float begin = 10, end = 90; static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiDragFlags_ClampOnInput); + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_ClampOnInput); ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); ImGui::TreePop(); @@ -1600,9 +1591,9 @@ 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"); - ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiDragFlags_Logarithmic); + ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic); ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); - ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiDragFlags_Logarithmic); + ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic); ImGui::Text("Sliders"); ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); @@ -1622,10 +1613,10 @@ static void ShowDemoWindowWidgets() ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms"); ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms"); ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); - ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic); ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); - ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic); ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); static bool inputs_step = true; @@ -3896,9 +3887,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" "Using those settings here will give you poor quality results."); static float window_scale = 1.0f; - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput)) // Scale only this window + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_ClampOnInput)) // Scale only this window ImGui::SetWindowFontScale(window_scale); - ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput); // Scale everything + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_ClampOnInput); // Scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); diff --git a/imgui_internal.h b/imgui_internal.h index 6d1c1cb6..c19d5017 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -631,13 +631,6 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; -// Extend ImGuiDragFlags_ -enum ImGuiDragFlagsPrivate_ -{ - ImGuiDragFlags_Vertical = 1 << 20, // Should this widget be orientated vertically? - ImGuiDragFlags_ReadOnly = 1 << 21 -}; - // Extend ImGuiSliderFlags_ enum ImGuiSliderFlagsPrivate_ { @@ -1985,7 +1978,7 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, 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); @@ -1997,7 +1990,7 @@ namespace ImGui // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); - template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiDragFlags flags); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags 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, ImGuiSliderFlags flags, ImRect* out_grab_bb); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 52075823..3331a66e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1998,13 +1998,13 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags) { ImGuiContext& g = *GImGui; - const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); - const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal; // Default tweak speed if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX)) @@ -2077,7 +2077,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const } // Round to user desired precision based on format string - if (!(flags & ImGuiDragFlags_NoRoundToFormat)) + if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) v_cur = RoundScalarWithFormatT(format, data_type, v_cur); // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. @@ -2113,10 +2113,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. - IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiDragFlags_Logarithmic flags instead."); + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2128,7 +2128,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } if (g.ActiveId != id) return false; - if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiDragFlags_ReadOnly)) + if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) return false; switch (data_type) @@ -2151,7 +2151,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. // Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2177,7 +2177,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Tabbing or CTRL-clicking on Drag turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - const bool temp_input_allowed = (flags & ImGuiDragFlags_NoInput) == 0; + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { @@ -2200,8 +2200,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (temp_input_is_active) { - // Only clamp CTRL+Click input when ImGuiDragFlags_ClampInput is set - const bool is_clamp_input = (flags & ImGuiDragFlags_ClampOnInput) != 0; + // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } @@ -2227,7 +2227,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, return value_changed; } -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2262,28 +2262,28 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data return value_changed; } -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } -// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) +// NB: You likely want to specify the ImGuiSliderFlags_ClampOnInput when using this. +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2296,14 +2296,14 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu float min_min = (v_min >= v_max) ? -FLT_MAX : v_min; float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); float max_max = (v_min >= v_max) ? FLT_MAX : v_max; - ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2315,28 +2315,28 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu } // NB: v_speed is float to allow adjusting the drag speed with more precision -bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } -// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. -bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragFlags flags) +// NB: You likely want to specify the ImGuiSliderFlags_ClampOnInput when using this. +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2349,14 +2349,14 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ int min_min = (v_min >= v_max) ? INT_MIN : v_min; int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); int max_max = (v_min >= v_max) ? INT_MAX : v_max; - ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2373,24 +2373,24 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None; if (power != 1.0f) { - IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds - drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + drag_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths } return DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, drag_flags); } bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None; if (power != 1.0f) { - IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds - drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + drag_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths } return DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, drag_flags); } @@ -3133,7 +3133,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* } // Note that Drag/Slider functions are only forwarding the min/max values clamping values if the -// ImGuiDragFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! +// ImGuiSliderFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) From 95c99aaa4be611716093edcb6b01146ab9483f30 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Aug 2020 17:50:45 +0200 Subject: [PATCH 202/223] Version 1.78 --- docs/CHANGELOG.txt | 38 +++++++++++------------ examples/README.txt | 2 +- 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.h | 6 ++-- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 12 files changed, 32 insertions(+), 28 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0520ca9f..89fdbdad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -32,7 +32,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.78 WIP (In Progress) + VERSION 1.78 (Released 2020-08-18) ----------------------------------------------------------------------- Breaking Changes: @@ -41,13 +41,13 @@ Breaking Changes: - DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN() - SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN() - VSliderFloat(), VSliderScalar() - Replaced the 'float power=1.0f' argument with ImGuiSliderFlags flags defaulting to 0 (as with all our flags). + Replaced the final 'float power=1.0f' argument with ImGuiSliderFlags defaulting to 0 (as with all our flags). Worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. In short, when calling those functions: - If you omitted the 'power' parameter (likely!), you are not affected. - If you set the 'power' parameter to 1.0f (same as previous default value): - Your compiler may warn on float>int conversion. - - Everything else will work. + - Everything else will work (but will assert if IMGUI_DISABLE_OBSOLETE_FUNCTIONS is defined). - You can replace the 1.0f value with 0 to fix the warning, and be technically correct. - If you set the 'power' parameter to >1.0f (to enable non-linear editing): - Your compiler may warn on float>int conversion. @@ -69,25 +69,25 @@ Other Changes: flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. -- Drag, Slider: ImGuiSliderFlags parameters. - For float functions they replace the old trailing 'float power=1.0' parameter. - (See #3361 and the "Breaking Changes" block above for all details). -- Drag, Slider: Added ImGuiSliderFlags_Logarithmic flags to enable logarithmic editing - (generally more precision around zero), as a replacement to the old 'float power' parameter - which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] -- Drag, Slider: Added ImGuiSliderFlags_ClampOnInput flags to force clamping value when using - CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). -- Drag, Slider: Added ImGuiSliderFlags_NoRoundToFormat flags to disable rounding underlying - value to match precision of the display format string. (#642) -- Drag, Slider: Added ImGuiSliderFlags_NoInput to disable turning widget into a text input - with CTRL+Click or Nav Enter. +- Drag, Slider: Added ImGuiSliderFlags parameters. + - For float functions they replace the old trailing 'float power=1.0' parameter. + (See #3361 and the "Breaking Changes" block above for all details). + - Added ImGuiSliderFlags_Logarithmic flag to enable logarithmic editing + (generally more precision around zero), as a replacement to the old 'float power' parameter + which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] + - Added ImGuiSliderFlags_ClampOnInput flag to force clamping value when using + CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). + - Added ImGuiSliderFlags_NoRoundToFormat flag to disable rounding underlying + value to match precision of the display format string. (#642) + - Added ImGuiSliderFlags_NoInput flag to disable turning widget into a text input + with CTRL+Click or Nav Enter. - Nav, Slider: Fix using keyboard/gamepad controls with certain logarithmic sliders where pushing a direction near zero values would be cancelled out. [@Shironekoben] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (Note that current code is going to show corrupted display if after - clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText + clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText() call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) - Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). @@ -109,15 +109,15 @@ Other Changes: path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - This change will facilitate the wider use of thick borders in future style changes. - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. - - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. - - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. + - Set `io.AntiAliasedLinesUseTex = false` to disable rendering using this method. + - Clear `ImFontAtlasFlags_NoBakedLines` in ImFontAtlas::Flags to disable baking data in texture. - ImDrawList: changed AddCircle(), AddCircleFilled() default num_segments from 12 to 0, effectively enabling auto-tessellation by default. Tweak tessellation in Style Editor->Rendering section, or by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] - Demo: Improved "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. - Also showcase using InvisibleButton() will multiple mouse buttons flags. + Also showcase using InvisibleButton() with multiple mouse buttons flags. - Demo: Improved "Layout & Scrolling" -> "Clipping" section. - Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. diff --git a/examples/README.txt b/examples/README.txt index 8c89ef00..9f0977ae 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.78 WIP + dear imgui, v1.78 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index f6b8b215..2e83e826 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -26,6 +26,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); 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); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 2cc36a7f..310dc04a 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -26,6 +26,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); 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); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 6ea896bc..4a263916 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -57,6 +57,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); 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); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index c8ad69f1..57a61c0d 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -24,6 +24,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); 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); diff --git a/imgui.cpp b/imgui.cpp index 59415898..d0840e24 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 0ddf24cd..83576022 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (headers) // Help: @@ -59,8 +59,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.78 WIP" -#define IMGUI_VERSION_NUM 17704 +#define IMGUI_VERSION "1.78" +#define IMGUI_VERSION_NUM 17800 #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 28cef963..77a7d870 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 39209287..487cdbd0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index c19d5017..22ce4634 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (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 3331a66e..1a10a2e8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (widgets code) /* From 5dc5610ad5ea9dae696ff51a6af310752c3207f7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Aug 2020 13:25:56 +0200 Subject: [PATCH 203/223] Docs: TODO, FAQ --- docs/CHANGELOG.txt | 7 +++++++ docs/FAQ.md | 4 ++-- docs/TODO.txt | 18 +++++++++++++++--- imgui.cpp | 2 +- imgui.h | 2 +- 5 files changed, 26 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 89fdbdad..40d65885 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -31,6 +31,13 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.79 WIP (In Progress) +----------------------------------------------------------------------- + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.78 (Released 2020-08-18) ----------------------------------------------------------------------- diff --git a/docs/FAQ.md b/docs/FAQ.md index b5fbcc90..2745b122 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -23,7 +23,7 @@ or view this file with any Markdown viewer. | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | **Q&A: Usage** | -| **[How can I have widgets with an empty label?
How can I have multiple widgets with the same label?
Why are multiple widgets reacting when I interact with one?](#q-how-can-i-have-widgets-with-an-empty-label)** | +| **[Why is my widget not reacting when I click on it?
How can I have multiple widgets with the same label?
Why are multiple widgets reacting when I interact with one?](#q-why-is-my-widget-not-reacting-when-i-click-on-it)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| | [How can I use my own math types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-math-types-instead-of-imvec2imvec4) | | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | @@ -173,9 +173,9 @@ Refer to rendering back-ends in the [examples/](https://github.com/ocornut/imgui # Q&A: Usage +### Q: Why is my widget not reacting when I click on it? ### Q: How can I have widgets with an empty label? ### Q: How can I have multiple widgets with the same label? -### Q: Why are multiple widgets reacting when I interact with one? A primer on labels and the ID Stack... diff --git a/docs/TODO.txt b/docs/TODO.txt index 1f6f8b94..ca026df0 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: top most window flag? (#2574) - window/size: manually triggered auto-fit (double-click on grip) shouldn't resize window down to viewport size? + - window/size: how to allow to e.g. auto-size vertically to fit contents, but be horizontally resizable? Assuming SetNextWindowSize() is modified to treat -1.0f on each axis as "keep as-is" (would be good but might break erroneous code): Problem is UpdateWindowManualResize() and lots of code treat (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) together. - 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: background options for child windows, border option (disable rounding). - window/child: allow resizing of child windows (possibly given min/max for each axis?.) @@ -35,6 +36,7 @@ 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/tabbing: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). + - window/id_stack: add e.g. window->GetIDFromPath() with support for leading / and ../ (#1390, #331) ! 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. @@ -54,6 +56,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: AddRect vs AddLine position confusing (#2441) - drawlist: channel splitter should be external helper and not stored in ImDrawList. + - drawlist: Add quadratic bezier curves? (#3127) - 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. @@ -78,6 +81,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - 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: preserve scrolling when unfocused? - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) - input text: expose CursorPos in char filter event (#816) - input text: try usage idiom of using InputText with data only exposed through get/set accessors, without extraneous copy/alloc. (#3009) @@ -134,7 +138,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - 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: flag to add horizontal separator above/below) - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) !- color: the color conversion helpers/types are a mess and needs sorting out. @@ -155,12 +159,16 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - clipper: horizontal clipping support. (#2580) - separator: expose flags (#759) + - separator: take indent into consideration (optional) - 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. + - tabs: "there is currently a problem because TabItem() will try to submit their own tooltip after 0.50 second, and this will have the effect of making your tooltip flicker once." -> tooltip priority work + - tabs: close button tends to overlap unsaved-document star + - tabs: consider showing the star at the same spot as the close button, like VS Code does. - tabs: while dragging/reordering a tab, close button decoration shouldn't appear on other tabs - 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) @@ -179,7 +187,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) - slider: relative dragging? + precision dragging - slider: step option (#1183) - - slider style: fill % of the bar instead of positioning a drag. + - slider: style: fill % of the bar instead of positioning a drag. - knob: rotating knob widget (#942) - drag float: support for reversed drags (min > max) (removed is_locked, also see fdc526e) - drag float: up/down axis @@ -232,13 +240,15 @@ 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/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height?) + - tree node: flag to disable formatting and/or detect "%s" + - tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height? format only %s/%c to be able to count 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) - settings/persistence: helpers to make TreeNodeBehavior persist (even during dev!) - may need to store some semantic and/or data type in ImGuiStoragePair - style: better default styles. (#707) + - style: PushStyleVar: allow direct access to individual float X/Y elements. - style: add a highlighted text color (for headers, etc.) - style: border types: out-screen, in-screen, etc. (#447) - style: add window shadow (fading away from the window. Paint-style calculation of vertices alpha after drawlist would be easier) @@ -285,6 +295,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - 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/layout/tabs: \t pulling position from base pos + step, or offset array (e.g. could be used in text edit, menus for simple icon+text alignment, etc.) - 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: custom separator for text wrapping. (#3002) @@ -383,6 +394,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: window minimize, maximize (#583) - examples: provide a zero frame-rate/idle example. - examples: dx11/dx12: try to use new swapchain blit models (#2970) + - backends: move to backends/ folder? - backends: report it better when not able to create texture? - backends: apple: example_apple should be using modern GL3. - backends: 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) diff --git a/imgui.cpp b/imgui.cpp index d0840e24..bb620003 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -657,9 +657,9 @@ CODE Q&A: Usage ---------- + Q: Why is my widget not reacting when I click on it? Q: How can I have widgets with an empty label? Q: How can I have multiple widgets with the same label? - Q: Why are multiple widgets reacting when I interact with one? Q: How can I display an image? What is ImTextureID, how does it works? Q: How can I use my own math types instead of ImVec2/ImVec4? Q: How can I interact with standard C++ types (such as std::string and std::vector)? diff --git a/imgui.h b/imgui.h index 83576022..d661ccfe 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,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.78" -#define IMGUI_VERSION_NUM 17800 +#define IMGUI_VERSION_NUM 17801 #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 4c201994d421089493a7a996978e8239ad619a20 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 11:21:15 +0200 Subject: [PATCH 204/223] DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) --- docs/CHANGELOG.txt | 3 ++ examples/example_win32_directx11/main.cpp | 5 ++ imgui_internal.h | 3 +- imgui_widgets.cpp | 58 +++++++++++++++++------ 4 files changed, 53 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 40d65885..83ac4df7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,9 @@ HOW TO UPDATE? Other Changes: +- DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case + where v_min == v_max. (#3361) + ----------------------------------------------------------------------- VERSION 1.78 (Released 2020-08-18) diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 310dc04a..d4920106 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -116,6 +116,11 @@ int main(int, char**) 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 + + static float f2 = 0.0f; + ImGui::DragFloat("f2 limit", &f2, 1.0f, 0.0f, 100.0f, NULL, ImGuiSliderFlags_ClampOnInput); + ImGui::DragFloat("f2", &f2, 1.0f, 0.0f, 0.0f, NULL, ImGuiSliderFlags_ClampOnInput); + 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) diff --git a/imgui_internal.h b/imgui_internal.h index 22ce4634..1e4384d0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1997,8 +1997,9 @@ 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* p_data, const char* format); - IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); + IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg_1, const void* arg_2); IMGUI_API bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* p_data, const char* format); + IMGUI_API int DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2); IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); // InputText diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1a10a2e8..188bb882 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1758,7 +1758,7 @@ int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type return 0; } -void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2) +void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2) { IM_ASSERT(op == '+' || op == '-'); switch (data_type) @@ -1910,11 +1910,39 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b } template -static bool ClampBehaviorT(T* v, const T* v_min, const T* v_max) +static int DataTypeCompareT(const T* lhs, const T* rhs) { - // Clamp, both sides are optional + if (*lhs < *rhs) return -1; + if (*lhs > *rhs) return +1; + return 0; +} + +int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2) +{ + switch (data_type) + { + case ImGuiDataType_S8: return DataTypeCompareT((const ImS8* )arg_1, (const ImS8* )arg_2); + case ImGuiDataType_U8: return DataTypeCompareT((const ImU8* )arg_1, (const ImU8* )arg_2); + case ImGuiDataType_S16: return DataTypeCompareT((const ImS16* )arg_1, (const ImS16* )arg_2); + case ImGuiDataType_U16: return DataTypeCompareT((const ImU16* )arg_1, (const ImU16* )arg_2); + case ImGuiDataType_S32: return DataTypeCompareT((const ImS32* )arg_1, (const ImS32* )arg_2); + case ImGuiDataType_U32: return DataTypeCompareT((const ImU32* )arg_1, (const ImU32* )arg_2); + case ImGuiDataType_S64: return DataTypeCompareT((const ImS64* )arg_1, (const ImS64* )arg_2); + case ImGuiDataType_U64: return DataTypeCompareT((const ImU64* )arg_1, (const ImU64* )arg_2); + case ImGuiDataType_Float: return DataTypeCompareT((const float* )arg_1, (const float* )arg_2); + case ImGuiDataType_Double: return DataTypeCompareT((const double*)arg_1, (const double*)arg_2); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return 0; +} + +template +static bool DataTypeClampT(T* v, const T* v_min, const T* v_max) +{ + // Clamp, both sides are optional, return true if modified if (v_min && *v < *v_min) { *v = *v_min; return true; } - if (v_max && *v > *v_max) { *v = *v_max; return true; } + if (v_max && *v > * v_max) { *v = *v_max; return true; } return false; } @@ -1922,16 +1950,16 @@ bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_m { switch (data_type) { - case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); - case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); - case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); - case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); - case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); - case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); - case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); - case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); - case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, (const float* )p_min, (const float* )p_max); - case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, (const double*)p_min, (const double*)p_max); + case ImGuiDataType_S8: return DataTypeClampT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); + case ImGuiDataType_U8: return DataTypeClampT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); + case ImGuiDataType_S16: return DataTypeClampT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); + case ImGuiDataType_U16: return DataTypeClampT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); + case ImGuiDataType_S32: return DataTypeClampT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); + case ImGuiDataType_U32: return DataTypeClampT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); + case ImGuiDataType_S64: return DataTypeClampT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); + case ImGuiDataType_U64: return DataTypeClampT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); + case ImGuiDataType_Float: return DataTypeClampT((float* )p_data, (const float* )p_min, (const float* )p_max); + case ImGuiDataType_Double: return DataTypeClampT((double*)p_data, (const double*)p_min, (const double*)p_max); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); @@ -2201,7 +2229,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (temp_input_is_active) { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set - const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; + const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } From 024993adf96f34dd9a176d594d2079242b68b94a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 11:25:05 +0200 Subject: [PATCH 205/223] Revert leftovers from 4c201994d421089493a7a996978e8239ad619a20 --- examples/example_win32_directx11/main.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index d4920106..310dc04a 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -116,11 +116,6 @@ int main(int, char**) 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 - - static float f2 = 0.0f; - ImGui::DragFloat("f2 limit", &f2, 1.0f, 0.0f, 100.0f, NULL, ImGuiSliderFlags_ClampOnInput); - ImGui::DragFloat("f2", &f2, 1.0f, 0.0f, 0.0f, NULL, ImGuiSliderFlags_ClampOnInput); - 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) From fc9ccad6b96de70219a644395b6a2bd069e61656 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 11:25:39 +0200 Subject: [PATCH 206/223] InputText: Add ImGuiInputTextFlags_CallbackEdit, selection helpers in ImGuiInputTextCallbackData(). Add simple InputText() callbacks demo. --- docs/CHANGELOG.txt | 5 ++++ imgui.h | 8 ++++-- imgui_demo.cpp | 61 +++++++++++++++++++++++++++++++++++++++++++++- imgui_internal.h | 1 + imgui_widgets.cpp | 11 ++++++++- 5 files changed, 82 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 83ac4df7..5479abb6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,8 +37,13 @@ HOW TO UPDATE? Other Changes: +- InputText: Added selection helpers in ImGuiInputTextCallbackData(). +- InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. + (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the + underlying buffer while focus is active). - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) +- Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). ----------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index d661ccfe..07058278 100644 --- a/imgui.h +++ b/imgui.h @@ -854,6 +854,7 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). 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) + ImGuiInputTextFlags_CallbackEdit = 1 << 19, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) // [Internal] ImGuiInputTextFlags_Multiline = 1 << 20, // For internal use by InputTextMultiline() ImGuiInputTextFlags_NoMarkEdited = 1 << 21 // For internal use by functions using InputText() before reformatting data @@ -1634,9 +1635,10 @@ struct ImGuiIO // Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. // The callback function should return 0 by default. // Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) +// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) +// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration // - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB // - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows -// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration // - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. // - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. struct ImGuiInputTextCallbackData @@ -1663,7 +1665,9 @@ struct ImGuiInputTextCallbackData IMGUI_API ImGuiInputTextCallbackData(); IMGUI_API void DeleteChars(int pos, int bytes_count); IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); - bool HasSelection() const { return SelectionStart != SelectionEnd; } + void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; } + void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } + bool HasSelection() const { return SelectionStart != SelectionEnd; } }; // Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 77a7d870..f9d1a9eb 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1177,8 +1177,11 @@ static void ShowDemoWindowWidgets() static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + ImGui::TreePop(); + } - ImGui::Text("Password input"); + if (ImGui::TreeNode("Password Input")) + { static char password[64] = "password123"; ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); @@ -1187,6 +1190,62 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } + if (ImGui::TreeNode("Completion, History, Edit Callbacks")) + { + struct Funcs + { + static int MyCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion) + { + data->InsertChars(data->CursorPos, ".."); + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory) + { + if (data->EventKey == ImGuiKey_UpArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Up!"); + data->SelectAll(); + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Down!"); + data->SelectAll(); + } + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) + { + // Toggle casing of first character + char c = data->Buf[0]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32; + data->BufDirty = true; + + // Increment a counter + int* p_int = (int*)data->UserData; + *p_int = *p_int + 1; + } + return 0; + } + }; + static char buf1[64]; + ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker("Here we append \"..\" each time Tab is pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf2[64]; + ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback); + ImGui::SameLine(); HelpMarker("Here we replace and select text each time Up/Down are pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback."); + + static char buf3[64]; + static int edit_count = 0; + ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count); + ImGui::SameLine(); HelpMarker("Here we toggle the casing of the first character on every edits + count edits."); + ImGui::SameLine(); ImGui::Text("(%d)", edit_count); + + ImGui::TreePop(); + } + if (ImGui::TreeNode("Resize Callback")) { // To wire InputText() with std::string or any other custom string type, diff --git a/imgui_internal.h b/imgui_internal.h index 1e4384d0..58224444 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -858,6 +858,7 @@ 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 + bool Edited; // edited this frame ImGuiInputTextFlags UserFlags; // Temporarily set while we call user's callback ImGuiInputTextCallback UserCallback; // " void* UserCallbackData; // " diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 188bb882..eee4d0f3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3514,6 +3514,7 @@ static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) ImWchar* dst = obj->TextW.Data + pos; // We maintain our buffer length in both UTF-8 and wchar formats + obj->Edited = true; obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; @@ -3548,6 +3549,7 @@ static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const Im memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + obj->Edited = true; obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; obj->TextW[obj->CurLenW] = '\0'; @@ -3946,6 +3948,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { IM_ASSERT(state != NULL); backup_current_text_length = state->CurLenA; + state->Edited = false; state->BufCapacityA = buf_size; state->UserFlags = flags; state->UserCallback = callback; @@ -4183,7 +4186,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } // User callback - if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0) { IM_ASSERT(callback != NULL); @@ -4205,8 +4208,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } + else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited) + { + event_flag = ImGuiInputTextFlags_CallbackEdit; + } else if (flags & ImGuiInputTextFlags_CallbackAlways) + { event_flag = ImGuiInputTextFlags_CallbackAlways; + } if (event_flag) { From 05a25e5f36a0735592efbfc7b4930db4f79d5443 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 16:19:53 +0200 Subject: [PATCH 207/223] BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. --- 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 5479abb6..2126be29 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Other Changes: underlying buffer while focus is active). - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) +- BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), + so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eee4d0f3..03ff7e10 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6416,7 +6416,8 @@ bool ImGui::BeginMenuBar() clip_rect.ClipWith(window->OuterRectClipped); PushClipRect(clip_rect.Min, clip_rect.Max, false); - window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); + // We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analoguous here, maybe a BeginGroupEx() with flags). + window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); window->DC.LayoutType = ImGuiLayoutType_Horizontal; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); From 9262609eafd915931afa9012cd393a63da53c0e7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 12:19:39 +0200 Subject: [PATCH 208/223] Version 1.79 WIP --- 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 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/README.txt b/examples/README.txt index 9f0977ae..e2577edb 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.78 + dear imgui, v1.79 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 bb620003..eea7bd81 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 07058278..8f76e93a 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (headers) // Help: @@ -59,8 +59,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.78" -#define IMGUI_VERSION_NUM 17801 +#define IMGUI_VERSION "1.79 WIP" +#define IMGUI_VERSION_NUM 17802 #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 f9d1a9eb..625bf1aa 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 487cdbd0..bb300e00 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 58224444..999641ae 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 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 03ff7e10..3d2bfe40 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (widgets code) /* From 97dad665166e23473d2be0b6390cc2bab099040e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 16:49:11 +0200 Subject: [PATCH 209/223] Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 48 +++++++++++++++++++++++++++++++++------------- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2126be29..28d1139f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other Changes: where v_min == v_max. (#3361) - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. +- Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). diff --git a/imgui.cpp b/imgui.cpp index eea7bd81..797d0a08 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10413,7 +10413,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) { if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) return; - for (int i = 0; i < windows.Size; i++) + ImGui::Text("(In front-to-back order:)"); + for (int i = windows.Size - 1; i >= 0; i--) // Iterate front to back { ImGui::PushID(windows[i]); Funcs::NodeWindow(windows[i], "Window"); @@ -10429,14 +10430,18 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::BulletText("%s: NULL", label); return; } - bool open = ImGui::TreeNode(label, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window); - if (ImGui::IsItemHovered() && window->WasActive) - ImGui::GetForegroundDrawList()->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + + ImGuiContext& g = *GImGui; + const bool is_active = window->WasActive; + ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + const bool open = ImGui::TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*"); + if (!is_active) { PopStyleColor(); } + if (ImGui::IsItemHovered() && is_active) + ImGui::GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!open) return; - if (!window->WasActive) - ImGui::TextDisabled("Note: window is not currently visible."); if (window->MemoryCompacted) ImGui::TextDisabled("Note: some memory buffers have been compacted/freed."); @@ -10481,9 +10486,13 @@ void ImGui::ShowMetricsWindow(bool* p_open) 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*" : ""); + const bool is_active = (tab_bar->PrevFrameVisible >= ImGui::GetFrameCount() - 2); + p += ImFormatString(p, buf_end - p, "Tab Bar 0x%08X (%d tabs)%s", tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); IM_UNUSED(p); - if (ImGui::TreeNode(tab_bar, "%s", buf)) + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = ImGui::TreeNode(tab_bar, "%s", buf); + if (!is_active) { PopStyleColor(); } + if (open) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { @@ -10635,8 +10644,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { - char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); - ImGui::InputTextMultiline("##Ini", buf, g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly); + ImGui::InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly); ImGui::TreePop(); } ImGui::TreePop(); @@ -10646,21 +10654,35 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); + + ImGui::Text("WINDOWING"); + ImGui::Indent(); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); - ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + ImGui::Unindent(); + + ImGui::Text("ITEMS"); + ImGui::Indent(); ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); - ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + ImGui::Unindent(); + + ImGui::Text("NAV,FOCUS"); + ImGui::Indent(); ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]); ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); + ImGui::Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId); ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); - ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + ImGui::Unindent(); + ImGui::TreePop(); } From 9b50e691edcc6469685965c1eb928c436dbc4808 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 22:26:10 +0200 Subject: [PATCH 210/223] TreeNode: Made clicking on arrow toggle toggle the open state on the Mouse Down event. Amend 05420ea2c. --- docs/CHANGELOG.txt | 4 ++++ imgui.h | 2 +- imgui_widgets.cpp | 11 ++++------- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 28d1139f..3f2a0474 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,10 @@ Other Changes: where v_min == v_max. (#3361) - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. +- TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event + rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior + and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. + (This is also necessary to support full multi/range-select/drag and drop operations.) - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). diff --git a/imgui.h b/imgui.h index 8f76e93a..65a1e304 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,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.79 WIP" -#define IMGUI_VERSION_NUM 17802 +#define IMGUI_VERSION_NUM 17803 #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_widgets.cpp b/imgui_widgets.cpp index 3d2bfe40..3f929f32 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5644,17 +5644,14 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. - // - Single-click on label = Toggle on MouseUp (default) - // - Single-click on arrow = Toggle on MouseUp (when _OpenOnArrow=0) + // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) + // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0) // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1) // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1) // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0) - // This makes _OpenOnArrow have a subtle effect on _OpenOnDoubleClick: arrow click reacts on Down rather than Up. - // It is rather standard that arrow click react on Down rather than Up and we'd be tempted to make it the default - // (by removing the _OpenOnArrow test below), however this would have a perhaps surprising effect on CollapsingHeader()? - // So right now we are making this optional. May evolve later. + // It is rather standard that arrow click react on Down rather than Up. // We set ImGuiButtonFlags_PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work. - if (is_mouse_x_over_arrow && (flags & ImGuiTreeNodeFlags_OpenOnArrow)) + if (is_mouse_x_over_arrow) button_flags |= ImGuiButtonFlags_PressedOnClick; else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; From 9d20a5f0a515dba3ade46cfcf90953133e34dcbc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 16:21:48 +0200 Subject: [PATCH 211/223] Docking: DockSpace() emits ItemSize() properly + dockspace demo (works now since 05a25e5f3) --- imgui.cpp | 2 ++ imgui_demo.cpp | 33 +++++++++++++++++++++------------ 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 51699b0c..5babd781 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14183,6 +14183,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla char title[256]; ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id); + // FIXME-DOCK: What is the reason for not simply calling BeginChild()? if (node->Windows.Size > 0 || node->IsSplitNode()) PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0)); PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f); @@ -14213,6 +14214,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla g.WithinEndChild = true; End(); + ItemSize(size); g.WithinEndChild = false; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2d6bc7a8..45553465 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -5303,8 +5303,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) // DockSpace() is only useful to construct to a central location for your application. void ShowExampleAppDockSpace(bool* p_open) { - static bool opt_fullscreen_persistant = true; - bool opt_fullscreen = opt_fullscreen_persistant; + static bool opt_fullscreen = true; + static bool opt_padding = false; static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, @@ -5321,6 +5321,10 @@ void ShowExampleAppDockSpace(bool* p_open) window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } + else + { + dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; + } // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background // and handle the pass-thru hole, so we ask Begin() to not render a background. @@ -5332,9 +5336,11 @@ void ShowExampleAppDockSpace(bool* p_open) // 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)); + if (!opt_padding) + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", p_open, window_flags); - ImGui::PopStyleVar(); + if (!opt_padding) + ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); @@ -5353,19 +5359,22 @@ void ShowExampleAppDockSpace(bool* p_open) if (ImGui::BeginMenuBar()) { - if (ImGui::BeginMenu("Docking")) + if (ImGui::BeginMenu("Options")) { // Disabling fullscreen would allow the window to be moved to the front of other windows, // which we can't undo at the moment without finer window depth/z control. - //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant); + ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen); + ImGui::MenuItem("Padding", NULL, &opt_padding); + ImGui::Separator(); - if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; - if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoResize; - 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; + if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; } + if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoResize; } + if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; } + if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; } + if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0, opt_fullscreen)) { dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; } ImGui::Separator(); - if (ImGui::MenuItem("Close DockSpace", NULL, false, p_open != NULL)) + + if (ImGui::MenuItem("Close", NULL, false, p_open != NULL)) *p_open = false; ImGui::EndMenu(); } From d6f3a8848d005e00748b8e8f9a93ba84620160a3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 15:02:52 +0200 Subject: [PATCH 212/223] Viewports: Backends: DirectX9: Allow D3DERR_DEVICELOST on secondary viewports. (#3424) --- examples/imgui_impl_dx9.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 6d726af8..f8abc61a 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -408,7 +408,8 @@ static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*) { ImGuiViewportDataDx9* data = (ImGuiViewportDataDx9*)viewport->RendererUserData; HRESULT hr = data->SwapChain->Present(NULL, NULL, data->d3dpp.hDeviceWindow, NULL, NULL); - IM_ASSERT(hr == D3D_OK); + // Let main application handle D3DERR_DEVICELOST by resetting the device. + IM_ASSERT(hr == D3D_OK || hr == D3DERR_DEVICELOST); } static void ImGui_ImplDX9_InitPlatformInterface() From df89a16d265c3f02f403afefc0e60b5d227d94fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Aug 2020 15:34:25 +0200 Subject: [PATCH 213/223] Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) --- docs/CHANGELOG.txt | 1 + examples/example_glfw_vulkan/main.cpp | 18 ++++++++---------- examples/example_sdl_vulkan/main.cpp | 19 ++++++++----------- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3f2a0474..a25f469c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: (This is also necessary to support full multi/range-select/drag and drop operations.) - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). +- Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] ----------------------------------------------------------------------- diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 58d0ab7f..8e75abbf 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -310,7 +310,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) } } -static void FramePresent(ImGui_ImplVulkanH_Window* wd) +static void FramePresent(ImGui_ImplVulkanH_Window* wd, GLFWwindow* window) { VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; @@ -321,6 +321,12 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); + if (err == VK_ERROR_OUT_OF_DATE_KHR) + { + glfwGetFramebufferSize(window, &g_SwapChainResizeWidth, &g_SwapChainResizeHeight); + g_SwapChainRebuild = true; + return; + } check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } @@ -330,13 +336,6 @@ static void glfw_error_callback(int error, const char* description) fprintf(stderr, "Glfw Error %d: %s\n", error, description); } -static void glfw_resize_callback(GLFWwindow*, int w, int h) -{ - g_SwapChainRebuild = true; - g_SwapChainResizeWidth = w; - g_SwapChainResizeHeight = h; -} - int main(int, char**) { // Setup GLFW window @@ -365,7 +364,6 @@ int main(int, char**) // Create Framebuffers int w, h; glfwGetFramebufferSize(window, &w, &h); - glfwSetFramebufferSizeCallback(window, glfw_resize_callback); ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; SetupVulkanWindow(wd, surface, w, h); @@ -515,7 +513,7 @@ int main(int, char**) { memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); - FramePresent(wd); + FramePresent(wd, window); } } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 6de7afab..c0a98088 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -302,7 +302,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) } } -static void FramePresent(ImGui_ImplVulkanH_Window* wd) +static void FramePresent(ImGui_ImplVulkanH_Window* wd, SDL_Window* window) { VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; @@ -313,6 +313,12 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); + if (err == VK_ERROR_OUT_OF_DATE_KHR) + { + SDL_GetWindowSize(window, &g_SwapChainResizeWidth, &g_SwapChainResizeHeight); + g_SwapChainRebuild = true; + return; + } check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } @@ -445,15 +451,6 @@ int main(int, char**) ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; - if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) - { - // Note: your own application may rely on SDL_WINDOWEVENT_MINIMIZED/SDL_WINDOWEVENT_RESTORED to skip updating all-together. - // Here ImGui_ImplSDL2_NewFrame() will set io.DisplaySize to zero which will disable rendering but let application run. - // Please note that you can't Present into a minimized window. - g_SwapChainResizeWidth = (int)event.window.data1; - g_SwapChainResizeHeight = (int)event.window.data2; - g_SwapChainRebuild = true; - } } // Resize swap chain? @@ -515,7 +512,7 @@ int main(int, char**) { memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); - FramePresent(wd); + FramePresent(wd, window); } } From cf312545e87146000bd96a1827d94a97ca7b17a0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 16:21:51 +0200 Subject: [PATCH 214/223] Docking: Fixed docking while hovering a child window. (#3420) broken by 85a661d27. Improve metrics debugging. --- imgui.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5babd781..ac94fc2e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11912,10 +11912,10 @@ void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) g.HoveredDockNode = NULL; if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow) { - if (hovered_window->DockNode) - g.HoveredDockNode = hovered_window->DockNode; - else if (hovered_window->DockNodeAsHost) + if (hovered_window->DockNodeAsHost) g.HoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); + else if (hovered_window->RootWindowDockStop->DockNode) + g.HoveredDockNode = hovered_window->RootWindowDockStop->DockNode; } // Process Docking requests @@ -14872,6 +14872,7 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); if (!g.DragDropActive) return; + //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!BeginDragDropTargetCustom(window->Rect(), window->ID)) return; @@ -15662,11 +15663,17 @@ void ImGui::ShowMetricsWindow(bool* p_open) static void NodeDockNode(ImGuiDockNode* node, const char* label) { ImGuiContext& g = *GImGui; + const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly + const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted + if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } 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 (!is_alive) { PopStyleColor(); } + if (is_active && ImGui::IsItemHovered()) + GetForegroundDrawList(node->HostWindow ? node->HostWindow : node->VisibleWindow)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); if (open) { IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); @@ -15679,8 +15686,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::BulletText("Misc:%s%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", - (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", - (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : "", + is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->WantLockSizeOnce ? " WantLockSizeOnce" : ""); if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) { @@ -15854,7 +15860,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ImGui::SameLine(); if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } - ImGui::Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (!root_nodes_only || node->IsRootNode()) @@ -15946,6 +15951,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); + ImGui::Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); ImGui::Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); ImGui::Unindent(); From 831e2c920edf62b1254587418a4f1968de3dc37e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 18:44:56 +0200 Subject: [PATCH 215/223] Docking, Viewport: Fixed a rare edge-case if the window targetted by CTRL+Tab stops being rendered. --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index ac94fc2e..110b73d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4386,9 +4386,10 @@ static void ImGui::EndFrameDrawDimmedBackgrounds() } // Draw modal whitening background between CTRL-TAB list - if (dim_bg_for_window_list) + if (dim_bg_for_window_list && g.NavWindowingTargetAnim->Active) { // Choose a draw list that will be front-most across all our children + // In the unlikely case that the window wasn't made active we can't rely on its drawlist and skip rendering all-together. ImGuiWindow* window = g.NavWindowingTargetAnim; ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindow)->DrawList; draw_list->PushClipRectFullScreen(); From fdf952108dd92897fabcba59b834a2ce9241b4ed Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 19:16:59 +0200 Subject: [PATCH 216/223] Drags, Sliders: internal ReadOnly flag gets forwarded properly to temp InputText(). --- imgui_internal.h | 2 +- imgui_widgets.cpp | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 999641ae..ec5bde09 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2006,7 +2006,7 @@ 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 TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL, ImGuiInputTextFlags flags = 0); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3f929f32..a0810a18 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2230,7 +2230,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); } // Draw frame @@ -2833,7 +2834,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); } // Draw frame @@ -3164,7 +3166,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* // ImGuiSliderFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. -bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max, ImGuiInputTextFlags flags) { ImGuiContext& g = *GImGui; @@ -3174,8 +3176,9 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format); ImStrTrimBlanks(data_buf); - ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; + flags |= ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); + bool value_changed = false; if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) { From 7b0570d6bac96ed64d379d240907f8fee319d57b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 20:15:07 +0200 Subject: [PATCH 217/223] Revert "Drags, Sliders: internal ReadOnly flag gets forwarded properly to temp InputText()." This reverts commit 640d1f60ce140e4c2bf858ac2f2e8a96d432e6a4. --- imgui_internal.h | 2 +- imgui_widgets.cpp | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ec5bde09..999641ae 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2006,7 +2006,7 @@ 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 TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL, ImGuiInputTextFlags flags = 0); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a0810a18..3f929f32 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2230,8 +2230,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); - const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } // Draw frame @@ -2834,8 +2833,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; - const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } // Draw frame @@ -3166,7 +3164,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* // ImGuiSliderFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. -bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max, ImGuiInputTextFlags flags) +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) { ImGuiContext& g = *GImGui; @@ -3176,9 +3174,8 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format); ImStrTrimBlanks(data_buf); - flags |= ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; + ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); - bool value_changed = false; if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) { From d451f6cc30d83e1dcb49c10ffe57b4f881b30de4 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 24 Aug 2020 14:13:18 +0200 Subject: [PATCH 218/223] Nav tweaks. Demo: Fixed drag and drop demo state (broken by f152fac4f1). Fixed incorrect format string (which would work without IMGUI_DISABLE_OBSOLETE_FUNCTIONS). --- imgui.cpp | 15 ++++++++++----- imgui_demo.cpp | 4 ++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 797d0a08..53864293 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3622,16 +3622,17 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. + bool clear_hovered_windows = false; FindHoveredWindow(); // Modal windows prevents mouse from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) - g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; + clear_hovered_windows = true; // Disabled mouse? if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) - g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; + clear_hovered_windows = true; // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward. int mouse_earliest_button_down = -1; @@ -3651,6 +3652,9 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) + clear_hovered_windows = true; + + if (clear_hovered_windows) g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app) @@ -9116,10 +9120,11 @@ static void ImGui::NavUpdateWindowing() if (move_delta.x != 0.0f || move_delta.y != 0.0f) { 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 - SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always); + const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well + ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow; + SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always); + MarkIniSettingsDirty(moving_window); g.NavDisableMouseHover = true; - MarkIniSettingsDirty(g.NavWindowingTarget); } } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 625bf1aa..efb83a4d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1575,7 +1575,7 @@ static void ShowDemoWindowWidgets() static int slider_i = 50; ImGui::Text("Underlying float value: %f", slider_f); ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags); - ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags); ImGui::TreePop(); } @@ -1820,7 +1820,7 @@ static void ShowDemoWindowWidgets() if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } - const char* names[9] = + static const char* names[9] = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", From 2e50d0706bf18ee2fe21cf8eb7dc680f64a6fea0 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 24 Aug 2020 16:26:47 +0200 Subject: [PATCH 219/223] Selectable: Tweaks. Added internal ImGuiSelectableFlags_NoPadWithHalfSpacing. --- imgui_internal.h | 13 +++++++------ imgui_widgets.cpp | 47 +++++++++++++++++++++++++---------------------- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 999641ae..b4083d2b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -642,12 +642,13 @@ enum ImGuiSliderFlagsPrivate_ enum ImGuiSelectableFlagsPrivate_ { // NB: need to be in sync with last value of ImGuiSelectableFlags_ - ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, - ImGuiSelectableFlags_SelectOnClick = 1 << 21, // Override button behavior to react on Click (default is Click+Release) - ImGuiSelectableFlags_SelectOnRelease = 1 << 22, // Override button behavior to react on Release (default is Click+Release) - ImGuiSelectableFlags_SpanAvailWidth = 1 << 23, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) - ImGuiSelectableFlags_DrawHoveredWhenHeld= 1 << 24, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. - ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25 + ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, + ImGuiSelectableFlags_SelectOnClick = 1 << 21, // Override button behavior to react on Click (default is Click+Release) + ImGuiSelectableFlags_SelectOnRelease = 1 << 22, // Override button behavior to react on Release (default is Click+Release) + ImGuiSelectableFlags_SpanAvailWidth = 1 << 23, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) + ImGuiSelectableFlags_DrawHoveredWhenHeld = 1 << 24, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. + ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25, // Set Nav/Focus ID on mouse hover (used by MenuItem) + ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26 // Disable padding each side with ItemSpacing * 0.5f }; // Extend ImGuiTreeNodeFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3f929f32..2ae40d98 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5889,7 +5889,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped. + const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0; + if (span_all_columns && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped. PushColumnsBackground(); // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. @@ -5901,8 +5902,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ItemSize(size, 0.0f); // Fill horizontal space - const float min_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Min.x : pos.x; - const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; + const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x; + const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) size.x = ImMax(label_size.x, max_x - min_x); @@ -5911,33 +5912,35 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const ImVec2 text_max(min_x + size.x, pos.y + size.y); // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable. - ImRect bb_enlarged(min_x, pos.y, text_max.x, text_max.y); - const float spacing_x = style.ItemSpacing.x; - const float spacing_y = style.ItemSpacing.y; - const float spacing_L = IM_FLOOR(spacing_x * 0.50f); - const float spacing_U = IM_FLOOR(spacing_y * 0.50f); - bb_enlarged.Min.x -= spacing_L; - bb_enlarged.Min.y -= spacing_U; - bb_enlarged.Max.x += (spacing_x - spacing_L); - bb_enlarged.Max.y += (spacing_y - spacing_U); - //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb_align.Min, bb_align.Max, IM_COL32(255, 0, 0, 255)); } - //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb_enlarged.Min, bb_enlarged.Max, IM_COL32(0, 255, 0, 255)); } + ImRect bb(min_x, pos.y, text_max.x, text_max.y); + if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) + { + const float spacing_x = style.ItemSpacing.x; + const float spacing_y = style.ItemSpacing.y; + const float spacing_L = IM_FLOOR(spacing_x * 0.50f); + const float spacing_U = IM_FLOOR(spacing_y * 0.50f); + bb.Min.x -= spacing_L; + bb.Min.y -= spacing_U; + bb.Max.x += (spacing_x - spacing_L); + bb.Max.y += (spacing_y - spacing_U); + } + //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); } bool item_add; if (flags & ImGuiSelectableFlags_Disabled) { ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus; - item_add = ItemAdd(bb_enlarged, id); + item_add = ItemAdd(bb, id); window->DC.ItemFlags = backup_item_flags; } else { - item_add = ItemAdd(bb_enlarged, id); + item_add = ItemAdd(bb, id); } if (!item_add) { - if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) + if (span_all_columns && window->DC.CurrentColumns) PopColumnsBackground(); return false; } @@ -5956,7 +5959,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const bool was_selected = selected; bool hovered, held; - bool pressed = ButtonBehavior(bb_enlarged, id, &hovered, &held, button_flags); + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); // 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))) @@ -5983,15 +5986,15 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (hovered || selected) { const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); - RenderFrame(bb_enlarged.Min, bb_enlarged.Max, col, false, 0.0f); - RenderNavHighlight(bb_enlarged, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); + RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); } - if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) + if (span_all_columns && window->DC.CurrentColumns) PopColumnsBackground(); if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); - RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb_enlarged); + RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); // Automatically close popups From 08108cf9ee352b9e868d3d7b59ece88b4d4a6d90 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Aug 2020 11:49:16 +0200 Subject: [PATCH 220/223] Tab Bar: Hide tab item close button while dragging a tab. --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 1 - imgui_widgets.cpp | 5 +++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a25f469c..5092f144 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,7 @@ Other Changes: rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) +- Tab Bar: Hide tab item close button while dragging a tab. - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] diff --git a/docs/TODO.txt b/docs/TODO.txt index ca026df0..e1b1f3e3 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -169,7 +169,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tabs: "there is currently a problem because TabItem() will try to submit their own tooltip after 0.50 second, and this will have the effect of making your tooltip flicker once." -> tooltip priority work - tabs: close button tends to overlap unsaved-document star - tabs: consider showing the star at the same spot as the close button, like VS Code does. - - tabs: while dragging/reordering a tab, close button decoration shouldn't appear on other tabs - 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) - tabs: TabItem could honor SetNextItemWidth()? diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ae40d98..6dd2eff1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7453,7 +7453,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, SetItemAllowOverlap(); // Drag and drop: re-order tabs - if (held && !tab_appearing && IsMouseDragging(0)) + const bool is_dragging = (held && !tab_appearing && IsMouseDragging(0)); + if (is_dragging) { if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) { @@ -7496,7 +7497,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; // Render tab label, process close button - const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; + const ImGuiID close_button_id = (p_open && !is_dragging) ? window->GetID((void*)((intptr_t)id + 1)) : 0; bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); if (just_closed && p_open != NULL) { From 021c28ae39594b0d6dc78ab8581f35cb8776012c Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Tue, 25 Aug 2020 13:13:03 +0300 Subject: [PATCH 221/223] Nav: Fix ScrollToBringRectIntoView() not bringing entire item into view when nav moves to the left. Correct some comments. --- imgui.cpp | 2 +- imgui_internal.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 53864293..bd25ed1c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7392,7 +7392,7 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_ 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); + 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) diff --git a/imgui_internal.h b/imgui_internal.h index b4083d2b..2cb5dfa3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1191,11 +1191,11 @@ struct ImGuiContext ImGuiKeyModFlags NavJustMovedToKeyMods; 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 NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring. + ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring. int NavScoringCount; // Metrics for debugging ImGuiNavLayer NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later. int NavIdTabCounter; // == NavWindow->DC.FocusIdxTabCounter at time of NavId processing - bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRefRectRel is valid + bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel is valid bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default) bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover) bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again. From 30f0900b1c5c840b817f73d0dadd1511e21f224c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Aug 2020 19:03:08 +0200 Subject: [PATCH 222/223] Docking: Fix honoring payload filter with overlapping nodes. (we incorrectly over-relied on g.HoveredDockNode when making change for #3398) Essentially undo part of 85a661d (#3398) + ref cf31254 (#3420) --- imgui.cpp | 28 ++++++++++++++++++---------- imgui_internal.h | 2 +- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 110b73d2..15749d3a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14890,18 +14890,26 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { // Select target node - // (we should not assume that g.HoveredDockNode is != NULL when window is a host dock node: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos) - ImGuiDockNode* node = g.HoveredDockNode; - const bool allow_null_target_node = window->DockNode == NULL && window->DockNodeAsHost == NULL; + // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) + bool dock_into_floating_window = false; + ImGuiDockNode* node = NULL; + if (window->DockNodeAsHost) + { + // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). + node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); - // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) - // In this case we need to fallback into any leaf mode, possibly the central node. - if (window->DockNodeAsHost && node && node->IsDockSpace() && node->IsRootNode()) + // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + if (node && node->IsDockSpace() && node->IsRootNode()) + node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node); + } + else { - if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. - node = node->CentralNode; + if (window->DockNode) + node = window->DockNode; else - node = DockNodeTreeFindFallbackLeafNode(node); + dock_into_floating_window = true; // Dock into a regular window } 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())); @@ -14910,7 +14918,7 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) // 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 && (node != NULL || allow_null_target_node)) + if (do_preview && (node != NULL || dock_into_floating_window)) { ImGuiDockPreviewData split_inner; ImGuiDockPreviewData split_outer; diff --git a/imgui_internal.h b/imgui_internal.h index 0105add4..5ccf0581 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1296,7 +1296,7 @@ struct ImGuiContext ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. ImGuiWindow* HoveredRootWindow; // == HoveredWindow ? HoveredWindow->RootWindow : NULL, merely a shortcut to avoid null test in some situation. ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. - ImGuiDockNode* HoveredDockNode; + ImGuiDockNode* HoveredDockNode; // Hovered dock node. ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; From 5919a6fa89e077e0b94f93036a2cef690790b06b Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Aug 2020 19:28:20 +0200 Subject: [PATCH 223/223] Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). Improve 08108cf --- docs/CHANGELOG.txt | 2 +- imgui_widgets.cpp | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5092f144..573b813a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,7 +49,7 @@ Other Changes: rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) -- Tab Bar: Hide tab item close button while dragging a tab. +- Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6dd2eff1..2ee4c191 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7453,8 +7453,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, SetItemAllowOverlap(); // Drag and drop: re-order tabs - const bool is_dragging = (held && !tab_appearing && IsMouseDragging(0)); - if (is_dragging) + if (held && !tab_appearing && IsMouseDragging(0)) { if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) { @@ -7497,7 +7496,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; // Render tab label, process close button - const ImGuiID close_button_id = (p_open && !is_dragging) ? window->GetID((void*)((intptr_t)id + 1)) : 0; + const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); if (just_closed && p_open != NULL) { @@ -7609,7 +7608,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, bool close_button_visible = false; if (close_button_id != 0) if (is_contents_visible || bb.GetWidth() >= g.Style.TabMinWidthForUnselectedCloseButton) - if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id) + if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id) close_button_visible = true; if (close_button_visible) {