1// dear imgui, v1.90.0
2// (main code and documentation)
3
4// Help:
5// - See links below.
6// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7// - Read top of imgui.cpp for more details, links and comments.
8
9// Resources:
10// - FAQ https://dearimgui.com/faq
11// - Getting Started https://dearimgui.com/getting-started
12// - Homepage https://github.com/ocornut/imgui
13// - Releases & changelog https://github.com/ocornut/imgui/releases
14// - Gallery https://github.com/ocornut/imgui/issues/6897 (please post your screenshots/video there!)
15// - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
17// - Issues & support https://github.com/ocornut/imgui/issues
18// - Tests & Automation https://github.com/ocornut/imgui_test_engine
19
20// For first-time users having issues compiling/linking/running/loading fonts:
21// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
23
24// Copyright (c) 2014-2023 Omar Cornut
25// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
26// See LICENSE.txt for copyright and licensing details (standard MIT License).
27// This library is free but needs your support to sustain development and maintenance.
28// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
29// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Sponsors
30// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
31
32// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
33// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
34// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
35// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
36// to a better solution or official support for them.
37
38/*
39
40Index of this file:
41
42DOCUMENTATION
43
44- MISSION STATEMENT
45- CONTROLS GUIDE
46- PROGRAMMER GUIDE
47 - READ FIRST
48 - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
49 - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
50 - HOW A SIMPLE APPLICATION MAY LOOK LIKE
51 - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
52- API BREAKING CHANGES (read me when you update!)
53- FREQUENTLY ASKED QUESTIONS (FAQ)
54 - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
55
56CODE
57(search for "[SECTION]" in the code to find them)
58
59// [SECTION] INCLUDES
60// [SECTION] FORWARD DECLARATIONS
61// [SECTION] CONTEXT AND MEMORY ALLOCATORS
62// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
63// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
64// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
65// [SECTION] MISC HELPERS/UTILITIES (File functions)
66// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
67// [SECTION] MISC HELPERS/UTILITIES (Color functions)
68// [SECTION] ImGuiStorage
69// [SECTION] ImGuiTextFilter
70// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
71// [SECTION] ImGuiListClipper
72// [SECTION] STYLING
73// [SECTION] RENDER HELPERS
74// [SECTION] INITIALIZATION, SHUTDOWN
75// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
76// [SECTION] INPUTS
77// [SECTION] ERROR CHECKING
78// [SECTION] LAYOUT
79// [SECTION] SCROLLING
80// [SECTION] TOOLTIPS
81// [SECTION] POPUPS
82// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
83// [SECTION] DRAG AND DROP
84// [SECTION] LOGGING/CAPTURING
85// [SECTION] SETTINGS
86// [SECTION] LOCALIZATION
87// [SECTION] VIEWPORTS, PLATFORM WINDOWS
88// [SECTION] PLATFORM DEPENDENT HELPERS
89// [SECTION] METRICS/DEBUGGER WINDOW
90// [SECTION] DEBUG LOG WINDOW
91// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
92
93*/
94
95//-----------------------------------------------------------------------------
96// DOCUMENTATION
97//-----------------------------------------------------------------------------
98
99/*
100
101 MISSION STATEMENT
102 =================
103
104 - Easy to use to create code-driven and data-driven tools.
105 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
106 - Easy to hack and improve.
107 - Minimize setup and maintenance.
108 - Minimize state storage on user side.
109 - Minimize state synchronization.
110 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
111 - Efficient runtime and memory consumption.
112
113 Designed primarily for developers and content-creators, not the typical end-user!
114 Some of the current weaknesses (which we aim to address in the future) includes:
115
116 - Doesn't look fancy.
117 - Limited layout features, intricate layouts are typically crafted in code.
118
119
120 CONTROLS GUIDE
121 ==============
122
123 - MOUSE CONTROLS
124 - Mouse wheel: Scroll vertically.
125 - SHIFT+Mouse wheel: Scroll horizontally.
126 - Click [X]: Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
127 - Click ^, Double-Click title: Collapse window.
128 - Drag on corner/border: Resize window (double-click to auto fit window to its contents).
129 - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
130 - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack).
131
132 - TEXT EDITOR
133 - Hold SHIFT or Drag Mouse: Select text.
134 - CTRL+Left/Right: Word jump.
135 - CTRL+Shift+Left/Right: Select words.
136 - CTRL+A or Double-Click: Select All.
137 - CTRL+X, CTRL+C, CTRL+V: Use OS clipboard.
138 - CTRL+Z, CTRL+Y: Undo, Redo.
139 - ESCAPE: Revert text to its original value.
140 - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
141
142 - KEYBOARD CONTROLS
143 - Basic:
144 - Tab, SHIFT+Tab Cycle through text editable fields.
145 - CTRL+Tab, CTRL+Shift+Tab Cycle through windows.
146 - CTRL+Click Input text into a Slider or Drag widget.
147 - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
148 - Tab, SHIFT+Tab: Cycle through every items.
149 - Arrow keys Move through items using directional navigation. Tweak value.
150 - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys).
151 - Enter Activate item (prefer text input when possible).
152 - Space Activate item (prefer tweaking with arrows when possible).
153 - Escape Deactivate item, leave child window, close popup.
154 - Page Up, Page Down Previous page, next page.
155 - Home, End Scroll to top, scroll to bottom.
156 - Alt Toggle between scrolling layer and menu layer.
157 - CTRL+Tab then Ctrl+Arrows Move window. Hold SHIFT to resize instead of moving.
158 - Output when ImGuiConfigFlags_NavEnableKeyboard set,
159 - io.WantCaptureKeyboard flag is set when keyboard is claimed.
160 - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
161 - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
162
163 - GAMEPAD CONTROLS
164 - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
165 - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
166 - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
167 - Backend support: backend needs to:
168 - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
169 - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
170 Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
171 - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
172 - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
173 with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
174
175 - REMOTE INPUTS SHARING & MOUSE EMULATION
176 - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
177 - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
178 in order to share your PC mouse/keyboard.
179 - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
180 - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
181 Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
182 When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
183 When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
184 (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
185 (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
186 to set a boolean to ignore your other external mouse positions until the external source is moved again.)
187
188
189 PROGRAMMER GUIDE
190 ================
191
192 READ FIRST
193 ----------
194 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
195 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
196 The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
197 data retention on your side, less state duplication, less state synchronization, fewer bugs.
198 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
199 Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
200 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
201 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
202 You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
203 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
204 For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
205 where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
206 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
207 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
208 If you get an assert, read the messages and comments around the assert.
209 - This codebase aims to be highly optimized:
210 - A typical idle frame should never call malloc/free.
211 - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
212 - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
213 Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
214 - This codebase aims to be both highly opinionated and highly flexible:
215 - This code works because of the things it choose to solve or not solve.
216 - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
217 and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
218 This is to increase compatibility, increase maintainability and facilitate use from other languages.
219 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
220 See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
221 We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
222 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
223 (so don't use ImVector in your code or at our own risk!).
224 - Building: We don't use nor mandate a build system for the main library.
225 This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
226 This is also because providing a build system for the main library would be of little-value.
227 The build problems are almost never coming from the main library but from specific backends.
228
229
230 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
231 ----------------------------------------------
232 - Update submodule or copy/overwrite every file.
233 - About imconfig.h:
234 - You may modify your copy of imconfig.h, in this case don't overwrite it.
235 - or you may locally branch to modify imconfig.h and merge/rebase latest.
236 - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
237 specify a custom path for your imconfig.h file and instead not have to modify the default one.
238
239 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
240 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
241 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
242 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
243 If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
244 from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
245 likely be a comment about it. Please report any issue to the GitHub page!
246 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
247 - Try to keep your copy of Dear ImGui reasonably up to date!
248
249
250 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
251 ---------------------------------------------------------------
252 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
253 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
254 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
255 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
256 It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
257 - 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.
258 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
259 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
260 Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
261 phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
262 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
263 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
264
265
266 HOW A SIMPLE APPLICATION MAY LOOK LIKE
267 --------------------------------------
268 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
269 The sub-folders in examples/ contain examples applications following this structure.
270
271 // Application init: create a dear imgui context, setup some options, load fonts
272 ImGui::CreateContext();
273 ImGuiIO& io = ImGui::GetIO();
274 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
275 // TODO: Fill optional fields of the io structure later.
276 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
277
278 // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
279 ImGui_ImplWin32_Init(hwnd);
280 ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
281
282 // Application main loop
283 while (true)
284 {
285 // Feed inputs to dear imgui, start new frame
286 ImGui_ImplDX11_NewFrame();
287 ImGui_ImplWin32_NewFrame();
288 ImGui::NewFrame();
289
290 // Any application code here
291 ImGui::Text("Hello, world!");
292
293 // Render dear imgui into screen
294 ImGui::Render();
295 ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
296 g_pSwapChain->Present(1, 0);
297 }
298
299 // Shutdown
300 ImGui_ImplDX11_Shutdown();
301 ImGui_ImplWin32_Shutdown();
302 ImGui::DestroyContext();
303
304 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
305
306 // Application init: create a dear imgui context, setup some options, load fonts
307 ImGui::CreateContext();
308 ImGuiIO& io = ImGui::GetIO();
309 // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
310 // TODO: Fill optional fields of the io structure later.
311 // TODO: Load TTF/OTF fonts if you don't want to use the default font.
312
313 // Build and load the texture atlas into a texture
314 // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
315 int width, height;
316 unsigned char* pixels = nullptr;
317 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
318
319 // At this point you've got the texture data and you need to upload that to your graphic system:
320 // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
321 // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
322 MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
323 io.Fonts->SetTexID((void*)texture);
324
325 // Application main loop
326 while (true)
327 {
328 // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
329 // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
330 io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
331 io.DisplaySize.x = 1920.0f; // set the current display width
332 io.DisplaySize.y = 1280.0f; // set the current display height here
333 io.AddMousePosEvent(mouse_x, mouse_y); // update mouse position
334 io.AddMouseButtonEvent(0, mouse_b[0]); // update mouse button states
335 io.AddMouseButtonEvent(1, mouse_b[1]); // update mouse button states
336
337 // Call NewFrame(), after this point you can use ImGui::* functions anytime
338 // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
339 ImGui::NewFrame();
340
341 // Most of your application code here
342 ImGui::Text("Hello, world!");
343 MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
344 MyGameRender(); // may use any Dear ImGui functions as well!
345
346 // Render dear imgui, swap buffers
347 // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
348 ImGui::EndFrame();
349 ImGui::Render();
350 ImDrawData* draw_data = ImGui::GetDrawData();
351 MyImGuiRenderFunction(draw_data);
352 SwapBuffers();
353 }
354
355 // Shutdown
356 ImGui::DestroyContext();
357
358 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
359 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
360 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
361
362
363 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
364 ---------------------------------------------
365 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
366
367 void MyImGuiRenderFunction(ImDrawData* draw_data)
368 {
369 // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
370 // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
371 // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
372 // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
373 // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
374 ImVec2 clip_off = draw_data->DisplayPos;
375 for (int n = 0; n < draw_data->CmdListsCount; n++)
376 {
377 const ImDrawList* cmd_list = draw_data->CmdLists[n];
378 const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
379 const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui
380 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
381 {
382 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
383 if (pcmd->UserCallback)
384 {
385 pcmd->UserCallback(cmd_list, pcmd);
386 }
387 else
388 {
389 // Project scissor/clipping rectangles into framebuffer space
390 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
391 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
392 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
393 continue;
394
395 // We are using scissoring to clip some objects. All low-level graphics API should support it.
396 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
397 // (some elements visible outside their bounds) but you can fix that once everything else works!
398 // - Clipping coordinates are provided in imgui coordinates space:
399 // - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
400 // - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
401 // - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
402 // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
403 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
404 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
405
406 // The texture for the draw call is specified by pcmd->GetTexID().
407 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
408 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
409
410 // Render 'pcmd->ElemCount/3' indexed triangles.
411 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
412 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
413 }
414 }
415 }
416 }
417
418
419 API BREAKING CHANGES
420 ====================
421
422 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
423 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
424 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
425 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
426
427 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
428 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
429 those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
430 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
431 - old: BeginChild("Name", size, true)
432 - new: BeginChild("Name", size, ImGuiChildFlags_Border)
433 - old: BeginChild("Name", size, false)
434 - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
435 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
436 - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
437 - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
438 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
439 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
440 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
441 - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
442 - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
443 - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
444 - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
445 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
446 - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
447 - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
448 - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
449 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
450 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
451 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
452 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
453 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
454 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
455 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
456 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
457 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
458 - ListBoxHeader() -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
459 - ListBoxFooter() -> use EndListBox()
460 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
461 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
462 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
463 - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp
464 - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
465 - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic()
466 - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo()
467 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
468 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
469 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
470 Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
471 it has been frequently requested by people to use our own. We had an opt-in define which was
472 previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
473 - OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
474 - Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
475 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
476 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
477 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
478 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
479 - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl
480 - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
481 - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt
482 - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
483 the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
484 the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
485 exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
486 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
487 this will require uses of legacy backend-dependent indices to be casted, e.g.
488 - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
489 - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A')
490 - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
491 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
492 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
493 - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
494 - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
495 - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
496 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
497 this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
498 - previously this would make the window content size ~200x200:
499 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
500 - instead, please submit an item:
501 Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
502 - alternative:
503 Begin(...) + Dummy(ImVec2(200,200)) + End();
504 - content size is now only extended when submitting an item!
505 - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
506 - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
507 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
508 - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
509 - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
510 - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
511 - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
512 - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
513 - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
514 - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
515 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
516 - Official backends from 1.87+ -> no issue.
517 - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
518 - Custom backends not writing to io.NavInputs[] -> no issue.
519 - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
520 - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
521 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
522 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
523 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
524 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
525 - Backend writing to io.NavInputs[] -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
526 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
527 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
528 - Backend writing to io.MousePos -> backend should call io.AddMousePosEvent()
529 - Backend writing to io.MouseDown[] -> backend should call io.AddMouseButtonEvent()
530 - Backend writing to io.MouseWheel -> backend should call io.AddMouseWheelEvent()
531 - Backend writing to io.MouseHoveredViewport -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
532 note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
533 read https://github.com/ocornut/imgui/issues/4921 for details.
534 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
535 - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX)
536 - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
537 - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
538 - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
539 - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
540 - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
541 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
542 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
543 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
544 - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen()
545 - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
546 - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
547 - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect
548 - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
549 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
550 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
551 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
552 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
553 - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
554 - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
555 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
556 - if you are using official backends from the source tree: you have nothing to do.
557 - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
558 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
559 - ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
560 - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
561 - ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
562 flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
563 breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
564 - rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
565 - rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
566 - rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
567 - rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
568 this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
569 the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
570 legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
571 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
572 - ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
573 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
574 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
575 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
576 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
577 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
578 - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
579 - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
580 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
581 - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
582 - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
583 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
584 - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
585 - ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
586 - ImGuiInputTextCallback -> use ImGuiTextEditCallback
587 - ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
588 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
589 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
590 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
591 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
592 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
593 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
594 - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
595 - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
596 - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
597 - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
598 - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
599 - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
600 - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
601 - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
602 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
603 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
604 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
605 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
606 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
607 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
608 - 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().
609 replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
610 worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
611 - if you omitted the 'power' parameter (likely!), you are not affected.
612 - 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.
613 - 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.
614 see https://github.com/ocornut/imgui/issues/3361 for all details.
615 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.
616 for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
617 - 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.
618 - 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.
619 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
620 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
621 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
622 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
623 - 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.
624 - 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.
625 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
626 - ShowTestWindow() -> use ShowDemoWindow()
627 - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
628 - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
629 - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
630 - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
631 - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
632 - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
633 - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
634 - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
635 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
636 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
637 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
638 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
639 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
640 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
641 - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
642 - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
643 - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
644 - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
645 - ImFont::Glyph -> use ImFontGlyph
646 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
647 if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
648 The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
649 If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
650 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
651 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
652 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
653 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
654 overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
655 This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
656 Please reach out if you are affected.
657 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
658 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
659 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
660 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
661 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
662 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
663 - 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 arbitrarily small value!
664 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
665 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
666 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
667 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
668 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
669 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
670 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
671 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
672 If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
673 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
674 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
675 NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
676 Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
677 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
678 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
679 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
680 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
681 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
682 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
683 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
684 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
685 old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
686 when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
687 in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
688 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
689 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
690 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
691 If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
692 To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
693 If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
694 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
695 consistent with other functions. Kept redirection functions (will obsolete).
696 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
697 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
698 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
699 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
700 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
701 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
702 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
703 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
704 - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
705 - removed Shutdown() function, as DestroyContext() serve this purpose.
706 - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
707 - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
708 - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
709 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
710 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
711 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
712 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
713 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
714 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
715 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
716 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
717 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
718 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
719 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
720 - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
721 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
722 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
723 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
724 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
725 Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
726 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
727 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
728 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
729 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
730 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
731 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
732 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
733 removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
734 IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
735 IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
736 IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
737 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
738 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
739 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
740 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
741 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
742 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
743 - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
744 - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
745 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
746 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
747 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
748 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
749 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
750 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
751 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
752 - 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.
753 - 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.
754 - 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))'
755 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
756 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
757 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
758 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
759 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
760 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
761 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
762 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
763 If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
764 This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
765 ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
766 If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
767 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
768 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
769 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
770 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
771 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
772 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
773 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
774 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
775 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
776 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
777 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
778 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
779 GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
780 GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
781 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
782 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
783 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
784 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
785 you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
786 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
787 this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
788 - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
789 - the signature of the io.RenderDrawListsFn handler has changed!
790 old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
791 new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
792 parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
793 ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
794 ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
795 - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
796 - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
797 - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
798 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
799 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
800 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
801 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
802 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
803 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
804 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
805 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
806 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
807 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
808 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
809 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
810 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
811 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
812 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
813 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
814 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
815 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
816 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
817 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
818 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
819 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
820 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
821 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
822 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
823 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
824 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
825 - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
826 - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
827 you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
828 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
829 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
830 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
831 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
832 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
833 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
834 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
835 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
836 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
837 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
838 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
839 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
840 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
841 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
842
843
844 FREQUENTLY ASKED QUESTIONS (FAQ)
845 ================================
846
847 Read all answers online:
848 https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
849 Read all answers locally (with a text editor or ideally a Markdown viewer):
850 docs/FAQ.md
851 Some answers are copied down here to facilitate searching in code.
852
853 Q&A: Basics
854 ===========
855
856 Q: Where is the documentation?
857 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
858 - Run the examples/ applications and explore them.
859 - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
860 - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
861 - The demo covers most features of Dear ImGui, so you can read the code and see its output.
862 - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
863 - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
864 examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
865 - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
866 - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
867 - Your programming IDE is your friend, find the type or function declaration to find comments
868 associated with it.
869
870 Q: What is this library called?
871 Q: Which version should I get?
872 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
873 >> See https://www.dearimgui.com/faq for details.
874
875 Q&A: Integration
876 ================
877
878 Q: How to get started?
879 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
880
881 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
882 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
883 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
884
885 Q. How can I enable keyboard or gamepad controls?
886 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
887 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
888 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
889 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
890 >> See https://www.dearimgui.com/faq
891
892 Q&A: Usage
893 ----------
894
895 Q: About the ID Stack system..
896 - Why is my widget not reacting when I click on it?
897 - How can I have widgets with an empty label?
898 - How can I have multiple widgets with the same label?
899 - How can I have multiple windows with the same label?
900 Q: How can I display an image? What is ImTextureID, how does it work?
901 Q: How can I use my own math types instead of ImVec2?
902 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
903 Q: How can I display custom shapes? (using low-level ImDrawList API)
904 >> See https://www.dearimgui.com/faq
905
906 Q&A: Fonts, Text
907 ================
908
909 Q: How should I handle DPI in my application?
910 Q: How can I load a different font than the default?
911 Q: How can I easily use icons in my application?
912 Q: How can I load multiple fonts?
913 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
914 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
915
916 Q&A: Concerns
917 =============
918
919 Q: Who uses Dear ImGui?
920 Q: Can you create elaborate/serious tools with Dear ImGui?
921 Q: Can you reskin the look of Dear ImGui?
922 Q: Why using C++ (as opposed to C)?
923 >> See https://www.dearimgui.com/faq
924
925 Q&A: Community
926 ==============
927
928 Q: How can I help?
929 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
930 We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
931 This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
932 Also see https://github.com/ocornut/imgui/wiki/Sponsors
933 - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
934 - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
935 - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
936 You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
937 But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
938 - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
939
940*/
941
942//-------------------------------------------------------------------------
943// [SECTION] INCLUDES
944//-------------------------------------------------------------------------
945
946#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
947#define _CRT_SECURE_NO_WARNINGS
948#endif
949
950#ifndef IMGUI_DEFINE_MATH_OPERATORS
951#define IMGUI_DEFINE_MATH_OPERATORS
952#endif
953
954#include "imgui.h"
955#ifndef IMGUI_DISABLE
956#include "imgui_internal.h"
957
958// System includes
959#include <stdio.h> // vsnprintf, sscanf, printf
960#include <stdint.h> // intptr_t
961
962// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
963#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
964#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
965#endif
966
967// [Windows] OS specific includes (optional)
968#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
969#define IMGUI_DISABLE_WIN32_FUNCTIONS
970#endif
971#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
972#ifndef WIN32_LEAN_AND_MEAN
973#define WIN32_LEAN_AND_MEAN
974#endif
975#ifndef NOMINMAX
976#define NOMINMAX
977#endif
978#ifndef __MINGW32__
979#include <Windows.h> // _wfopen, OpenClipboard
980#else
981#include <windows.h>
982#endif
983#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
984#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
985#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
986#endif
987#endif
988
989// [Apple] OS specific includes
990#if defined(__APPLE__)
991#include <TargetConditionals.h>
992#endif
993
994// Visual Studio warnings
995#ifdef _MSC_VER
996#pragma warning (disable: 4127) // condition expression is constant
997#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
998#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
999#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
1000#endif
1001#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1002#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1003#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1004#endif
1005
1006// Clang/GCC warnings with -Weverything
1007#if defined(__clang__)
1008#if __has_warning("-Wunknown-warning-option")
1009#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!
1010#endif
1011#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
1012#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
1013#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.
1014#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.
1015#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.
1016#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
1017#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
1018#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.
1019#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int'
1020#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
1021#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.
1022#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
1023#elif defined(__GNUC__)
1024// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1025#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
1026#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
1027#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
1028#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1029#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
1030#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1031#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
1032#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1033#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
1034#endif
1035
1036// Debug options
1037#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1038#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
1039
1040// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1041static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
1042static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
1043
1044// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1045static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1046static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
1047static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1048
1049// Tooltip offset
1050static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10); // Multiplied by g.Style.MouseCursorScale
1051
1052//-------------------------------------------------------------------------
1053// [SECTION] FORWARD DECLARATIONS
1054//-------------------------------------------------------------------------
1055
1056static void SetCurrentWindow(ImGuiWindow* window);
1057static void FindHoveredWindow();
1058static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1059static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1060
1061static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1062
1063// Settings
1064static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1065static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1066static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1067static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1068static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1069
1070// Platform Dependents default implementation for IO functions
1071static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1072static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1073static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1074
1075namespace ImGui
1076{
1077// Navigation
1078static void NavUpdate();
1079static void NavUpdateWindowing();
1080static void NavUpdateWindowingOverlay();
1081static void NavUpdateCancelRequest();
1082static void NavUpdateCreateMoveRequest();
1083static void NavUpdateCreateTabbingRequest();
1084static float NavUpdatePageUpPageDown();
1085static inline void NavUpdateAnyRequestFlag();
1086static void NavUpdateCreateWrappingRequest();
1087static void NavEndFrame();
1088static bool NavScoreItem(ImGuiNavItemData* result);
1089static void NavApplyItemToResult(ImGuiNavItemData* result);
1090static void NavProcessItem();
1091static void NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1092static ImVec2 NavCalcPreferredRefPos();
1093static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1094static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
1095static void NavRestoreLayer(ImGuiNavLayer layer);
1096static int FindWindowFocusIndex(ImGuiWindow* window);
1097
1098// Error Checking and Debug Tools
1099static void ErrorCheckNewFrameSanityChecks();
1100static void ErrorCheckEndFrameSanityChecks();
1101static void UpdateDebugToolItemPicker();
1102static void UpdateDebugToolStackQueries();
1103
1104// Inputs
1105static void UpdateKeyboardInputs();
1106static void UpdateMouseInputs();
1107static void UpdateMouseWheel();
1108static void UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1109
1110// Misc
1111static void UpdateSettings();
1112static int UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1113static void RenderWindowOuterBorders(ImGuiWindow* window);
1114static 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);
1115static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1116static void RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1117static void RenderDimmedBackgrounds();
1118
1119// Viewports
1120static void UpdateViewportsNewFrame();
1121
1122}
1123
1124//-----------------------------------------------------------------------------
1125// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1126//-----------------------------------------------------------------------------
1127
1128// DLL users:
1129// - Heaps and globals are not shared across DLL boundaries!
1130// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1131// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1132// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1133// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1134
1135// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1136// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1137// Change to a different context by calling ImGui::SetCurrentContext().
1138// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1139// If you want thread-safety to allow N threads to access N different contexts:
1140// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1141// struct ImGuiContext;
1142// extern thread_local ImGuiContext* MyImGuiTLS;
1143// #define GImGui MyImGuiTLS
1144// And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1145// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1146// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1147// - DLL users: read comments above.
1148#ifndef GImGui
1149ImGuiContext* GImGui = NULL;
1150#endif
1151
1152// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1153// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1154// - DLL users: read comments above.
1155#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1156static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size: size); }
1157static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr: ptr); }
1158#else
1159static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1160static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1161#endif
1162static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
1163static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
1164static void* GImAllocatorUserData = NULL;
1165
1166//-----------------------------------------------------------------------------
1167// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1168//-----------------------------------------------------------------------------
1169
1170ImGuiStyle::ImGuiStyle()
1171{
1172 Alpha = 1.0f; // Global alpha applies to everything in Dear ImGui.
1173 DisabledAlpha = 0.60f; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1174 WindowPadding = ImVec2(8,8); // Padding within a window
1175 WindowRounding = 0.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.
1176 WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1177 WindowMinSize = ImVec2(32,32); // Minimum window size
1178 WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
1179 WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1180 ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1181 ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1182 PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1183 PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1184 FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
1185 FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1186 FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1187 ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
1188 ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1189 CellPadding = ImVec2(4,2); // Padding within a table cell. CellPadding.y may be altered between different rows.
1190 TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1191 IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1192 ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1193 ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
1194 ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
1195 GrabMinSize = 12.0f; // Minimum width/height of a grab box for slider/scrollbar
1196 GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1197 LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1198 TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1199 TabBorderSize = 0.0f; // Thickness of border around tabs.
1200 TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appear 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.
1201 TabBarBorderSize = 1.0f; // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1202 TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1203 ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1204 ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1205 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.
1206 SeparatorTextBorderSize = 3.0f; // Thickkness of border in SeparatorText()
1207 SeparatorTextAlign = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1208 SeparatorTextPadding = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1209 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.
1210 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.
1211 MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1212 AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1213 AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1214 AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1215 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.
1216 CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1217
1218 // Behaviors
1219 HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1220 HoverDelayShort = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1221 HoverDelayNormal = 0.40f; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1222 HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1223 HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1224
1225 // Default theme
1226 ImGui::StyleColorsDark(dst: this);
1227}
1228
1229// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1230// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1231void ImGuiStyle::ScaleAllSizes(float scale_factor)
1232{
1233 WindowPadding = ImTrunc(v: WindowPadding * scale_factor);
1234 WindowRounding = ImTrunc(f: WindowRounding * scale_factor);
1235 WindowMinSize = ImTrunc(v: WindowMinSize * scale_factor);
1236 ChildRounding = ImTrunc(f: ChildRounding * scale_factor);
1237 PopupRounding = ImTrunc(f: PopupRounding * scale_factor);
1238 FramePadding = ImTrunc(v: FramePadding * scale_factor);
1239 FrameRounding = ImTrunc(f: FrameRounding * scale_factor);
1240 ItemSpacing = ImTrunc(v: ItemSpacing * scale_factor);
1241 ItemInnerSpacing = ImTrunc(v: ItemInnerSpacing * scale_factor);
1242 CellPadding = ImTrunc(v: CellPadding * scale_factor);
1243 TouchExtraPadding = ImTrunc(v: TouchExtraPadding * scale_factor);
1244 IndentSpacing = ImTrunc(f: IndentSpacing * scale_factor);
1245 ColumnsMinSpacing = ImTrunc(f: ColumnsMinSpacing * scale_factor);
1246 ScrollbarSize = ImTrunc(f: ScrollbarSize * scale_factor);
1247 ScrollbarRounding = ImTrunc(f: ScrollbarRounding * scale_factor);
1248 GrabMinSize = ImTrunc(f: GrabMinSize * scale_factor);
1249 GrabRounding = ImTrunc(f: GrabRounding * scale_factor);
1250 LogSliderDeadzone = ImTrunc(f: LogSliderDeadzone * scale_factor);
1251 TabRounding = ImTrunc(f: TabRounding * scale_factor);
1252 TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(f: TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1253 SeparatorTextPadding = ImTrunc(v: SeparatorTextPadding * scale_factor);
1254 DisplayWindowPadding = ImTrunc(v: DisplayWindowPadding * scale_factor);
1255 DisplaySafeAreaPadding = ImTrunc(v: DisplaySafeAreaPadding * scale_factor);
1256 MouseCursorScale = ImTrunc(f: MouseCursorScale * scale_factor);
1257}
1258
1259ImGuiIO::ImGuiIO()
1260{
1261 // Most fields are initialized with zero
1262 memset(s: this, c: 0, n: sizeof(*this));
1263 IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1264
1265 // Settings
1266 ConfigFlags = ImGuiConfigFlags_None;
1267 BackendFlags = ImGuiBackendFlags_None;
1268 DisplaySize = ImVec2(-1.0f, -1.0f);
1269 DeltaTime = 1.0f / 60.0f;
1270 IniSavingRate = 5.0f;
1271 IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1272 LogFilename = "imgui_log.txt";
1273#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1274 for (int i = 0; i < ImGuiKey_COUNT; i++)
1275 KeyMap[i] = -1;
1276#endif
1277 UserData = NULL;
1278
1279 Fonts = NULL;
1280 FontGlobalScale = 1.0f;
1281 FontDefault = NULL;
1282 FontAllowUserScaling = false;
1283 DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1284
1285 MouseDoubleClickTime = 0.30f;
1286 MouseDoubleClickMaxDist = 6.0f;
1287 MouseDragThreshold = 6.0f;
1288 KeyRepeatDelay = 0.275f;
1289 KeyRepeatRate = 0.050f;
1290
1291 // Miscellaneous options
1292 MouseDrawCursor = false;
1293#ifdef __APPLE__
1294 ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
1295#else
1296 ConfigMacOSXBehaviors = false;
1297#endif
1298 ConfigInputTrickleEventQueue = true;
1299 ConfigInputTextCursorBlink = true;
1300 ConfigInputTextEnterKeepActive = false;
1301 ConfigDragClickToInputText = false;
1302 ConfigWindowsResizeFromEdges = true;
1303 ConfigWindowsMoveFromTitleBarOnly = false;
1304 ConfigMemoryCompactTimer = 60.0f;
1305 ConfigDebugBeginReturnValueOnce = false;
1306 ConfigDebugBeginReturnValueLoop = false;
1307
1308 // Platform Functions
1309 // Note: Initialize() will setup default clipboard/ime handlers.
1310 BackendPlatformName = BackendRendererName = NULL;
1311 BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1312 PlatformLocaleDecimalPoint = '.';
1313
1314 // Input (NB: we already have memset zero the entire structure!)
1315 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1316 MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1317 MouseSource = ImGuiMouseSource_Mouse;
1318 for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1319 for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1320 AppAcceptingEvents = true;
1321 BackendUsingLegacyKeyArrays = (ImS8)-1;
1322 BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1323}
1324
1325// Pass in translated ASCII characters for text input.
1326// - with glfw you can get those from the callback set in glfwSetCharCallback()
1327// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1328// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1329void ImGuiIO::AddInputCharacter(unsigned int c)
1330{
1331 IM_ASSERT(Ctx != NULL);
1332 ImGuiContext& g = *Ctx;
1333 if (c == 0 || !AppAcceptingEvents)
1334 return;
1335
1336 ImGuiInputEvent e;
1337 e.Type = ImGuiInputEventType_Text;
1338 e.Source = ImGuiInputSource_Keyboard;
1339 e.EventId = g.InputEventsNextEventId++;
1340 e.Text.Char = c;
1341 g.InputEventsQueue.push_back(v: e);
1342}
1343
1344// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1345// we should save the high surrogate.
1346void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1347{
1348 if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1349 return;
1350
1351 if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1352 {
1353 if (InputQueueSurrogate != 0)
1354 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1355 InputQueueSurrogate = c;
1356 return;
1357 }
1358
1359 ImWchar cp = c;
1360 if (InputQueueSurrogate != 0)
1361 {
1362 if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1363 {
1364 AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1365 }
1366 else
1367 {
1368#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1369 cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1370#else
1371 cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1372#endif
1373 }
1374
1375 InputQueueSurrogate = 0;
1376 }
1377 AddInputCharacter(c: (unsigned)cp);
1378}
1379
1380void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1381{
1382 if (!AppAcceptingEvents)
1383 return;
1384 while (*utf8_chars != 0)
1385 {
1386 unsigned int c = 0;
1387 utf8_chars += ImTextCharFromUtf8(out_char: &c, in_text: utf8_chars, NULL);
1388 AddInputCharacter(c);
1389 }
1390}
1391
1392// Clear all incoming events.
1393void ImGuiIO::ClearEventsQueue()
1394{
1395 IM_ASSERT(Ctx != NULL);
1396 ImGuiContext& g = *Ctx;
1397 g.InputEventsQueue.clear();
1398}
1399
1400// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1401void ImGuiIO::ClearInputKeys()
1402{
1403#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1404 memset(s: KeysDown, c: 0, n: sizeof(KeysDown));
1405#endif
1406 for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1407 {
1408 KeysData[n].Down = false;
1409 KeysData[n].DownDuration = -1.0f;
1410 KeysData[n].DownDurationPrev = -1.0f;
1411 }
1412 KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1413 KeyMods = ImGuiMod_None;
1414 MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1415 for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1416 {
1417 MouseDown[n] = false;
1418 MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1419 }
1420 MouseWheel = MouseWheelH = 0.0f;
1421 InputQueueCharacters.resize(new_size: 0); // Behavior of old ClearInputCharacters().
1422}
1423
1424// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1425// Current frame character buffer is now also cleared by ClearInputKeys().
1426#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1427void ImGuiIO::ClearInputCharacters()
1428{
1429 InputQueueCharacters.resize(new_size: 0);
1430}
1431#endif
1432
1433static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1434{
1435 ImGuiContext& g = *ctx;
1436 for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1437 {
1438 ImGuiInputEvent* e = &g.InputEventsQueue[n];
1439 if (e->Type != type)
1440 continue;
1441 if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1442 continue;
1443 if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1444 continue;
1445 return e;
1446 }
1447 return NULL;
1448}
1449
1450// Queue a new key down/up event.
1451// - ImGuiKey key: Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1452// - bool down: Is the key down? use false to signify a key release.
1453// - float analog_value: 0.0f..1.0f
1454// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1455// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1456void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1457{
1458 //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1459 IM_ASSERT(Ctx != NULL);
1460 if (key == ImGuiKey_None || !AppAcceptingEvents)
1461 return;
1462 ImGuiContext& g = *Ctx;
1463 IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1464 IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1465 IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1466
1467 // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1468#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1469 IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1470 if (BackendUsingLegacyKeyArrays == -1)
1471 for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1472 IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1473 BackendUsingLegacyKeyArrays = 0;
1474#endif
1475 if (ImGui::IsGamepadKey(key))
1476 BackendUsingLegacyNavInputArray = false;
1477
1478 // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1479 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Key, arg: (int)key);
1480 const ImGuiKeyData* key_data = ImGui::GetKeyData(ctx: &g, key);
1481 const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1482 const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1483 if (latest_key_down == down && latest_key_analog == analog_value)
1484 return;
1485
1486 // Add event
1487 ImGuiInputEvent e;
1488 e.Type = ImGuiInputEventType_Key;
1489 e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1490 e.EventId = g.InputEventsNextEventId++;
1491 e.Key.Key = key;
1492 e.Key.Down = down;
1493 e.Key.AnalogValue = analog_value;
1494 g.InputEventsQueue.push_back(v: e);
1495}
1496
1497void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1498{
1499 if (!AppAcceptingEvents)
1500 return;
1501 AddKeyAnalogEvent(key, down, analog_value: down ? 1.0f : 0.0f);
1502}
1503
1504// [Optional] Call after AddKeyEvent().
1505// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1506// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1507void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1508{
1509 if (key == ImGuiKey_None)
1510 return;
1511 IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1512 IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1513 IM_UNUSED(native_keycode); // Yet unused
1514 IM_UNUSED(native_scancode); // Yet unused
1515
1516 // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1517#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1518 const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1519 if (!ImGui::IsLegacyKey(key: (ImGuiKey)legacy_key))
1520 return;
1521 KeyMap[legacy_key] = key;
1522 KeyMap[key] = legacy_key;
1523#else
1524 IM_UNUSED(key);
1525 IM_UNUSED(native_legacy_index);
1526#endif
1527}
1528
1529// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1530void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1531{
1532 AppAcceptingEvents = accepting_events;
1533}
1534
1535// Queue a mouse move event
1536void ImGuiIO::AddMousePosEvent(float x, float y)
1537{
1538 IM_ASSERT(Ctx != NULL);
1539 ImGuiContext& g = *Ctx;
1540 if (!AppAcceptingEvents)
1541 return;
1542
1543 // Apply same flooring as UpdateMouseInputs()
1544 ImVec2 pos((x > -FLT_MAX) ? ImFloor(f: x) : x, (y > -FLT_MAX) ? ImFloor(f: y) : y);
1545
1546 // Filter duplicate
1547 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MousePos);
1548 const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1549 if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1550 return;
1551
1552 ImGuiInputEvent e;
1553 e.Type = ImGuiInputEventType_MousePos;
1554 e.Source = ImGuiInputSource_Mouse;
1555 e.EventId = g.InputEventsNextEventId++;
1556 e.MousePos.PosX = pos.x;
1557 e.MousePos.PosY = pos.y;
1558 e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1559 g.InputEventsQueue.push_back(v: e);
1560}
1561
1562void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1563{
1564 IM_ASSERT(Ctx != NULL);
1565 ImGuiContext& g = *Ctx;
1566 IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1567 if (!AppAcceptingEvents)
1568 return;
1569
1570 // Filter duplicate
1571 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_MouseButton, arg: (int)mouse_button);
1572 const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1573 if (latest_button_down == down)
1574 return;
1575
1576 ImGuiInputEvent e;
1577 e.Type = ImGuiInputEventType_MouseButton;
1578 e.Source = ImGuiInputSource_Mouse;
1579 e.EventId = g.InputEventsNextEventId++;
1580 e.MouseButton.Button = mouse_button;
1581 e.MouseButton.Down = down;
1582 e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1583 g.InputEventsQueue.push_back(v: e);
1584}
1585
1586// Queue a mouse wheel event (some mouse/API may only have a Y component)
1587void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1588{
1589 IM_ASSERT(Ctx != NULL);
1590 ImGuiContext& g = *Ctx;
1591
1592 // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1593 if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1594 return;
1595
1596 ImGuiInputEvent e;
1597 e.Type = ImGuiInputEventType_MouseWheel;
1598 e.Source = ImGuiInputSource_Mouse;
1599 e.EventId = g.InputEventsNextEventId++;
1600 e.MouseWheel.WheelX = wheel_x;
1601 e.MouseWheel.WheelY = wheel_y;
1602 e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1603 g.InputEventsQueue.push_back(v: e);
1604}
1605
1606// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1607// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1608void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1609{
1610 IM_ASSERT(Ctx != NULL);
1611 ImGuiContext& g = *Ctx;
1612 g.InputEventsNextMouseSource = source;
1613}
1614
1615void ImGuiIO::AddFocusEvent(bool focused)
1616{
1617 IM_ASSERT(Ctx != NULL);
1618 ImGuiContext& g = *Ctx;
1619
1620 // Filter duplicate
1621 const ImGuiInputEvent* latest_event = FindLatestInputEvent(ctx: &g, type: ImGuiInputEventType_Focus);
1622 const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1623 if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1624 return;
1625
1626 ImGuiInputEvent e;
1627 e.Type = ImGuiInputEventType_Focus;
1628 e.EventId = g.InputEventsNextEventId++;
1629 e.AppFocused.Focused = focused;
1630 g.InputEventsQueue.push_back(v: e);
1631}
1632
1633//-----------------------------------------------------------------------------
1634// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1635//-----------------------------------------------------------------------------
1636
1637ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1638{
1639 IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1640 ImVec2 p_last = p1;
1641 ImVec2 p_closest;
1642 float p_closest_dist2 = FLT_MAX;
1643 float t_step = 1.0f / (float)num_segments;
1644 for (int i_step = 1; i_step <= num_segments; i_step++)
1645 {
1646 ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t: t_step * i_step);
1647 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
1648 float dist2 = ImLengthSqr(lhs: p - p_line);
1649 if (dist2 < p_closest_dist2)
1650 {
1651 p_closest = p_line;
1652 p_closest_dist2 = dist2;
1653 }
1654 p_last = p_current;
1655 }
1656 return p_closest;
1657}
1658
1659// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1660static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1661{
1662 float dx = x4 - x1;
1663 float dy = y4 - y1;
1664 float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1665 float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1666 d2 = (d2 >= 0) ? d2 : -d2;
1667 d3 = (d3 >= 0) ? d3 : -d3;
1668 if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1669 {
1670 ImVec2 p_current(x4, y4);
1671 ImVec2 p_line = ImLineClosestPoint(a: p_last, b: p_current, p);
1672 float dist2 = ImLengthSqr(lhs: p - p_line);
1673 if (dist2 < p_closest_dist2)
1674 {
1675 p_closest = p_line;
1676 p_closest_dist2 = dist2;
1677 }
1678 p_last = p_current;
1679 }
1680 else if (level < 10)
1681 {
1682 float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
1683 float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
1684 float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
1685 float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
1686 float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
1687 float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1688 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x2: x12, y2: y12, x3: x123, y3: y123, x4: x1234, y4: y1234, tess_tol, level: level + 1);
1689 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: x1234, y1: y1234, x2: x234, y2: y234, x3: x34, y3: y34, x4, y4, tess_tol, level: level + 1);
1690 }
1691}
1692
1693// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1694// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1695ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1696{
1697 IM_ASSERT(tess_tol > 0.0f);
1698 ImVec2 p_last = p1;
1699 ImVec2 p_closest;
1700 float p_closest_dist2 = FLT_MAX;
1701 ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y, x3: p3.x, y3: p3.y, x4: p4.x, y4: p4.y, tess_tol, level: 0);
1702 return p_closest;
1703}
1704
1705ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1706{
1707 ImVec2 ap = p - a;
1708 ImVec2 ab_dir = b - a;
1709 float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1710 if (dot < 0.0f)
1711 return a;
1712 float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1713 if (dot > ab_len_sqr)
1714 return b;
1715 return a + ab_dir * dot / ab_len_sqr;
1716}
1717
1718bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1719{
1720 bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1721 bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1722 bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1723 return ((b1 == b2) && (b2 == b3));
1724}
1725
1726void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1727{
1728 ImVec2 v0 = b - a;
1729 ImVec2 v1 = c - a;
1730 ImVec2 v2 = p - a;
1731 const float denom = v0.x * v1.y - v1.x * v0.y;
1732 out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1733 out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1734 out_u = 1.0f - out_v - out_w;
1735}
1736
1737ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1738{
1739 ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1740 ImVec2 proj_bc = ImLineClosestPoint(a: b, b: c, p);
1741 ImVec2 proj_ca = ImLineClosestPoint(a: c, b: a, p);
1742 float dist2_ab = ImLengthSqr(lhs: p - proj_ab);
1743 float dist2_bc = ImLengthSqr(lhs: p - proj_bc);
1744 float dist2_ca = ImLengthSqr(lhs: p - proj_ca);
1745 float m = ImMin(lhs: dist2_ab, rhs: ImMin(lhs: dist2_bc, rhs: dist2_ca));
1746 if (m == dist2_ab)
1747 return proj_ab;
1748 if (m == dist2_bc)
1749 return proj_bc;
1750 return proj_ca;
1751}
1752
1753//-----------------------------------------------------------------------------
1754// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1755//-----------------------------------------------------------------------------
1756
1757// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1758int ImStricmp(const char* str1, const char* str2)
1759{
1760 int d;
1761 while ((d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; }
1762 return d;
1763}
1764
1765int ImStrnicmp(const char* str1, const char* str2, size_t count)
1766{
1767 int d = 0;
1768 while (count > 0 && (d = ImToUpper(c: *str2) - ImToUpper(c: *str1)) == 0 && *str1) { str1++; str2++; count--; }
1769 return d;
1770}
1771
1772void ImStrncpy(char* dst, const char* src, size_t count)
1773{
1774 if (count < 1)
1775 return;
1776 if (count > 1)
1777 strncpy(dest: dst, src: src, n: count - 1);
1778 dst[count - 1] = 0;
1779}
1780
1781char* ImStrdup(const char* str)
1782{
1783 size_t len = strlen(s: str);
1784 void* buf = IM_ALLOC(len + 1);
1785 return (char*)memcpy(dest: buf, src: (const void*)str, n: len + 1);
1786}
1787
1788char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1789{
1790 size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(s: dst) + 1;
1791 size_t src_size = strlen(s: src) + 1;
1792 if (dst_buf_size < src_size)
1793 {
1794 IM_FREE(dst);
1795 dst = (char*)IM_ALLOC(src_size);
1796 if (p_dst_size)
1797 *p_dst_size = src_size;
1798 }
1799 return (char*)memcpy(dest: dst, src: (const void*)src, n: src_size);
1800}
1801
1802const char* ImStrchrRange(const char* str, const char* str_end, char c)
1803{
1804 const char* p = (const char*)memchr(s: str, c: (int)c, n: str_end - str);
1805 return p;
1806}
1807
1808int ImStrlenW(const ImWchar* str)
1809{
1810 //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
1811 int n = 0;
1812 while (*str++) n++;
1813 return n;
1814}
1815
1816// Find end-of-line. Return pointer will point to either first \n, either str_end.
1817const char* ImStreolRange(const char* str, const char* str_end)
1818{
1819 const char* p = (const char*)memchr(s: str, c: '\n', n: str_end - str);
1820 return p ? p : str_end;
1821}
1822
1823const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1824{
1825 while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1826 buf_mid_line--;
1827 return buf_mid_line;
1828}
1829
1830const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1831{
1832 if (!needle_end)
1833 needle_end = needle + strlen(s: needle);
1834
1835 const char un0 = (char)ImToUpper(c: *needle);
1836 while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1837 {
1838 if (ImToUpper(c: *haystack) == un0)
1839 {
1840 const char* b = needle + 1;
1841 for (const char* a = haystack + 1; b < needle_end; a++, b++)
1842 if (ImToUpper(c: *a) != ImToUpper(c: *b))
1843 break;
1844 if (b == needle_end)
1845 return haystack;
1846 }
1847 haystack++;
1848 }
1849 return NULL;
1850}
1851
1852// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1853void ImStrTrimBlanks(char* buf)
1854{
1855 char* p = buf;
1856 while (p[0] == ' ' || p[0] == '\t') // Leading blanks
1857 p++;
1858 char* p_start = p;
1859 while (*p != 0) // Find end of string
1860 p++;
1861 while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
1862 p--;
1863 if (p_start != buf) // Copy memory if we had leading blanks
1864 memmove(dest: buf, src: p_start, n: p - p_start);
1865 buf[p - p_start] = 0; // Zero terminate
1866}
1867
1868const char* ImStrSkipBlank(const char* str)
1869{
1870 while (str[0] == ' ' || str[0] == '\t')
1871 str++;
1872 return str;
1873}
1874
1875// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1876// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1877// B) When buf==NULL vsnprintf() will return the output size.
1878#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1879
1880// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1881// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1882// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1883// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1884#ifdef IMGUI_USE_STB_SPRINTF
1885#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1886#define STB_SPRINTF_IMPLEMENTATION
1887#endif
1888#ifdef IMGUI_STB_SPRINTF_FILENAME
1889#include IMGUI_STB_SPRINTF_FILENAME
1890#else
1891#include "stb_sprintf.h"
1892#endif
1893#endif // #ifdef IMGUI_USE_STB_SPRINTF
1894
1895#if defined(_MSC_VER) && !defined(vsnprintf)
1896#define vsnprintf _vsnprintf
1897#endif
1898
1899int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1900{
1901 va_list args;
1902 va_start(args, fmt);
1903#ifdef IMGUI_USE_STB_SPRINTF
1904 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1905#else
1906 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
1907#endif
1908 va_end(args);
1909 if (buf == NULL)
1910 return w;
1911 if (w == -1 || w >= (int)buf_size)
1912 w = (int)buf_size - 1;
1913 buf[w] = 0;
1914 return w;
1915}
1916
1917int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1918{
1919#ifdef IMGUI_USE_STB_SPRINTF
1920 int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1921#else
1922 int w = vsnprintf(s: buf, maxlen: buf_size, format: fmt, arg: args);
1923#endif
1924 if (buf == NULL)
1925 return w;
1926 if (w == -1 || w >= (int)buf_size)
1927 w = (int)buf_size - 1;
1928 buf[w] = 0;
1929 return w;
1930}
1931#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1932
1933void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1934{
1935 va_list args;
1936 va_start(args, fmt);
1937 ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
1938 va_end(args);
1939}
1940
1941void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1942{
1943 ImGuiContext& g = *GImGui;
1944 if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1945 {
1946 const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1947 *out_buf = buf;
1948 if (out_buf_end) { *out_buf_end = buf + strlen(s: buf); }
1949 }
1950 else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
1951 {
1952 int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
1953 const char* buf = va_arg(args, const char*);
1954 *out_buf = buf;
1955 *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
1956 }
1957 else
1958 {
1959 int buf_len = ImFormatStringV(buf: g.TempBuffer.Data, buf_size: g.TempBuffer.Size, fmt, args);
1960 *out_buf = g.TempBuffer.Data;
1961 if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1962 }
1963}
1964
1965// CRC32 needs a 1KB lookup table (not cache friendly)
1966// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1967// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1968static const ImU32 GCrc32LookupTable[256] =
1969{
1970 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1971 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1972 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1973 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1974 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1975 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1976 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1977 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1978 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1979 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1980 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1981 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1982 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1983 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1984 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1985 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1986};
1987
1988// Known size hash
1989// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1990// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1991ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
1992{
1993 ImU32 crc = ~seed;
1994 const unsigned char* data = (const unsigned char*)data_p;
1995 const ImU32* crc32_lut = GCrc32LookupTable;
1996 while (data_size-- != 0)
1997 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1998 return ~crc;
1999}
2000
2001// Zero-terminated string hash, with support for ### to reset back to seed value
2002// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2003// Because this syntax is rarely used we are optimizing for the common case.
2004// - If we reach ### in the string we discard the hash so far and reset to the seed.
2005// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2006// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2007ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2008{
2009 seed = ~seed;
2010 ImU32 crc = seed;
2011 const unsigned char* data = (const unsigned char*)data_p;
2012 const ImU32* crc32_lut = GCrc32LookupTable;
2013 if (data_size != 0)
2014 {
2015 while (data_size-- != 0)
2016 {
2017 unsigned char c = *data++;
2018 if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2019 crc = seed;
2020 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2021 }
2022 }
2023 else
2024 {
2025 while (unsigned char c = *data++)
2026 {
2027 if (c == '#' && data[0] == '#' && data[1] == '#')
2028 crc = seed;
2029 crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2030 }
2031 }
2032 return ~crc;
2033}
2034
2035//-----------------------------------------------------------------------------
2036// [SECTION] MISC HELPERS/UTILITIES (File functions)
2037//-----------------------------------------------------------------------------
2038
2039// Default file functions
2040#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2041
2042ImFileHandle ImFileOpen(const char* filename, const char* mode)
2043{
2044#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2045 // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2046 // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2047 const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2048 const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2049 ImGuiContext& g = *GImGui;
2050 g.TempBuffer.reserve((filename_wsize + mode_wsize) * sizeof(wchar_t));
2051 wchar_t* buf = (wchar_t*)(void*)g.TempBuffer.Data;
2052 ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2053 ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2054 return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2055#else
2056 return fopen(filename: filename, modes: mode);
2057#endif
2058}
2059
2060// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2061bool ImFileClose(ImFileHandle f) { return fclose(stream: f) == 0; }
2062ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(stream: f)) != -1 && !fseek(stream: f, off: 0, SEEK_END) && (sz = ftell(stream: f)) != -1 && !fseek(stream: f, off: off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2063ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(ptr: data, size: (size_t)sz, n: (size_t)count, stream: f); }
2064ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(ptr: data, size: (size_t)sz, n: (size_t)count, s: f); }
2065#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2066
2067// Helper: Load file content into memory
2068// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2069// This can't really be used with "rt" because fseek size won't match read size.
2070void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2071{
2072 IM_ASSERT(filename && mode);
2073 if (out_file_size)
2074 *out_file_size = 0;
2075
2076 ImFileHandle f;
2077 if ((f = ImFileOpen(filename, mode)) == NULL)
2078 return NULL;
2079
2080 size_t file_size = (size_t)ImFileGetSize(f);
2081 if (file_size == (size_t)-1)
2082 {
2083 ImFileClose(f);
2084 return NULL;
2085 }
2086
2087 void* file_data = IM_ALLOC(file_size + padding_bytes);
2088 if (file_data == NULL)
2089 {
2090 ImFileClose(f);
2091 return NULL;
2092 }
2093 if (ImFileRead(data: file_data, sz: 1, count: file_size, f) != file_size)
2094 {
2095 ImFileClose(f);
2096 IM_FREE(file_data);
2097 return NULL;
2098 }
2099 if (padding_bytes > 0)
2100 memset(s: (void*)(((char*)file_data) + file_size), c: 0, n: (size_t)padding_bytes);
2101
2102 ImFileClose(f);
2103 if (out_file_size)
2104 *out_file_size = file_size;
2105
2106 return file_data;
2107}
2108
2109//-----------------------------------------------------------------------------
2110// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2111//-----------------------------------------------------------------------------
2112
2113IM_MSVC_RUNTIME_CHECKS_OFF
2114
2115// Convert UTF-8 to 32-bit character, process single character input.
2116// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2117// We handle UTF-8 decoding error by skipping forward.
2118int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2119{
2120 static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2121 static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2122 static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2123 static const int shiftc[] = { 0, 18, 12, 6, 0 };
2124 static const int shifte[] = { 0, 6, 4, 2, 0 };
2125 int len = lengths[*(const unsigned char*)in_text >> 3];
2126 int wanted = len + (len ? 0 : 1);
2127
2128 if (in_text_end == NULL)
2129 in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2130
2131 // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2132 // so it is fast even with excessive branching.
2133 unsigned char s[4];
2134 s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2135 s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2136 s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2137 s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2138
2139 // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2140 *out_char = (uint32_t)(s[0] & masks[len]) << 18;
2141 *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2142 *out_char |= (uint32_t)(s[2] & 0x3f) << 6;
2143 *out_char |= (uint32_t)(s[3] & 0x3f) << 0;
2144 *out_char >>= shiftc[len];
2145
2146 // Accumulate the various error conditions.
2147 int e = 0;
2148 e = (*out_char < mins[len]) << 6; // non-canonical encoding
2149 e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
2150 e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
2151 e |= (s[1] & 0xc0) >> 2;
2152 e |= (s[2] & 0xc0) >> 4;
2153 e |= (s[3] ) >> 6;
2154 e ^= 0x2a; // top two bits of each tail byte correct?
2155 e >>= shifte[len];
2156
2157 if (e)
2158 {
2159 // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2160 // One byte is consumed in case of invalid first byte of in_text.
2161 // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2162 // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2163 wanted = ImMin(lhs: wanted, rhs: !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2164 *out_char = IM_UNICODE_CODEPOINT_INVALID;
2165 }
2166
2167 return wanted;
2168}
2169
2170int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2171{
2172 ImWchar* buf_out = buf;
2173 ImWchar* buf_end = buf + buf_size;
2174 while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2175 {
2176 unsigned int c;
2177 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2178 *buf_out++ = (ImWchar)c;
2179 }
2180 *buf_out = 0;
2181 if (in_text_remaining)
2182 *in_text_remaining = in_text;
2183 return (int)(buf_out - buf);
2184}
2185
2186int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2187{
2188 int char_count = 0;
2189 while ((!in_text_end || in_text < in_text_end) && *in_text)
2190 {
2191 unsigned int c;
2192 in_text += ImTextCharFromUtf8(out_char: &c, in_text, in_text_end);
2193 char_count++;
2194 }
2195 return char_count;
2196}
2197
2198// Based on stb_to_utf8() from github.com/nothings/stb/
2199static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2200{
2201 if (c < 0x80)
2202 {
2203 buf[0] = (char)c;
2204 return 1;
2205 }
2206 if (c < 0x800)
2207 {
2208 if (buf_size < 2) return 0;
2209 buf[0] = (char)(0xc0 + (c >> 6));
2210 buf[1] = (char)(0x80 + (c & 0x3f));
2211 return 2;
2212 }
2213 if (c < 0x10000)
2214 {
2215 if (buf_size < 3) return 0;
2216 buf[0] = (char)(0xe0 + (c >> 12));
2217 buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2218 buf[2] = (char)(0x80 + ((c ) & 0x3f));
2219 return 3;
2220 }
2221 if (c <= 0x10FFFF)
2222 {
2223 if (buf_size < 4) return 0;
2224 buf[0] = (char)(0xf0 + (c >> 18));
2225 buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2226 buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2227 buf[3] = (char)(0x80 + ((c ) & 0x3f));
2228 return 4;
2229 }
2230 // Invalid code point, the max unicode is 0x10FFFF
2231 return 0;
2232}
2233
2234const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2235{
2236 int count = ImTextCharToUtf8_inline(buf: out_buf, buf_size: 5, c);
2237 out_buf[count] = 0;
2238 return out_buf;
2239}
2240
2241// Not optimal but we very rarely use this function.
2242int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2243{
2244 unsigned int unused = 0;
2245 return ImTextCharFromUtf8(out_char: &unused, in_text, in_text_end);
2246}
2247
2248static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2249{
2250 if (c < 0x80) return 1;
2251 if (c < 0x800) return 2;
2252 if (c < 0x10000) return 3;
2253 if (c <= 0x10FFFF) return 4;
2254 return 3;
2255}
2256
2257int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2258{
2259 char* buf_p = out_buf;
2260 const char* buf_end = out_buf + out_buf_size;
2261 while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2262 {
2263 unsigned int c = (unsigned int)(*in_text++);
2264 if (c < 0x80)
2265 *buf_p++ = (char)c;
2266 else
2267 buf_p += ImTextCharToUtf8_inline(buf: buf_p, buf_size: (int)(buf_end - buf_p - 1), c);
2268 }
2269 *buf_p = 0;
2270 return (int)(buf_p - out_buf);
2271}
2272
2273int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2274{
2275 int bytes_count = 0;
2276 while ((!in_text_end || in_text < in_text_end) && *in_text)
2277 {
2278 unsigned int c = (unsigned int)(*in_text++);
2279 if (c < 0x80)
2280 bytes_count++;
2281 else
2282 bytes_count += ImTextCountUtf8BytesFromChar(c);
2283 }
2284 return bytes_count;
2285}
2286
2287const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2288{
2289 while (in_text_curr > in_text_start)
2290 {
2291 in_text_curr--;
2292 if ((*in_text_curr & 0xC0) != 0x80)
2293 return in_text_curr;
2294 }
2295 return in_text_start;
2296}
2297
2298IM_MSVC_RUNTIME_CHECKS_RESTORE
2299
2300//-----------------------------------------------------------------------------
2301// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2302// Note: The Convert functions are early design which are not consistent with other API.
2303//-----------------------------------------------------------------------------
2304
2305IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2306{
2307 float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2308 int r = ImLerp(a: (int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2309 int g = ImLerp(a: (int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2310 int b = ImLerp(a: (int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, b: (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2311 return IM_COL32(r, g, b, 0xFF);
2312}
2313
2314ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2315{
2316 float s = 1.0f / 255.0f;
2317 return ImVec4(
2318 ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2319 ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2320 ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2321 ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2322}
2323
2324ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2325{
2326 ImU32 out;
2327 out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2328 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2329 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2330 out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2331 return out;
2332}
2333
2334// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2335// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2336void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2337{
2338 float K = 0.f;
2339 if (g < b)
2340 {
2341 ImSwap(a&: g, b);
2342 K = -1.f;
2343 }
2344 if (r < g)
2345 {
2346 ImSwap(a&: r, b&: g);
2347 K = -2.f / 6.f - K;
2348 }
2349
2350 const float chroma = r - (g < b ? g : b);
2351 out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2352 out_s = chroma / (r + 1e-20f);
2353 out_v = r;
2354}
2355
2356// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2357// also http://en.wikipedia.org/wiki/HSL_and_HSV
2358void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2359{
2360 if (s == 0.0f)
2361 {
2362 // gray
2363 out_r = out_g = out_b = v;
2364 return;
2365 }
2366
2367 h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2368 int i = (int)h;
2369 float f = h - (float)i;
2370 float p = v * (1.0f - s);
2371 float q = v * (1.0f - s * f);
2372 float t = v * (1.0f - s * (1.0f - f));
2373
2374 switch (i)
2375 {
2376 case 0: out_r = v; out_g = t; out_b = p; break;
2377 case 1: out_r = q; out_g = v; out_b = p; break;
2378 case 2: out_r = p; out_g = v; out_b = t; break;
2379 case 3: out_r = p; out_g = q; out_b = v; break;
2380 case 4: out_r = t; out_g = p; out_b = v; break;
2381 case 5: default: out_r = v; out_g = p; out_b = q; break;
2382 }
2383}
2384
2385//-----------------------------------------------------------------------------
2386// [SECTION] ImGuiStorage
2387// Helper: Key->value storage
2388//-----------------------------------------------------------------------------
2389
2390// std::lower_bound but without the bullshit
2391static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2392{
2393 ImGuiStorage::ImGuiStoragePair* first = data.Data;
2394 ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2395 size_t count = (size_t)(last - first);
2396 while (count > 0)
2397 {
2398 size_t count2 = count >> 1;
2399 ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2400 if (mid->key < key)
2401 {
2402 first = ++mid;
2403 count -= count2 + 1;
2404 }
2405 else
2406 {
2407 count = count2;
2408 }
2409 }
2410 return first;
2411}
2412
2413// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2414void ImGuiStorage::BuildSortByKey()
2415{
2416 struct StaticFunc
2417 {
2418 static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2419 {
2420 // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2421 if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2422 if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2423 return 0;
2424 }
2425 };
2426 ImQsort(base: Data.Data, count: (size_t)Data.Size, size_of_element: sizeof(ImGuiStoragePair), compare_func: StaticFunc::PairComparerByID);
2427}
2428
2429int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2430{
2431 ImGuiStoragePair* it = LowerBound(data&: const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2432 if (it == Data.end() || it->key != key)
2433 return default_val;
2434 return it->val_i;
2435}
2436
2437bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2438{
2439 return GetInt(key, default_val: default_val ? 1 : 0) != 0;
2440}
2441
2442float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2443{
2444 ImGuiStoragePair* it = LowerBound(data&: const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2445 if (it == Data.end() || it->key != key)
2446 return default_val;
2447 return it->val_f;
2448}
2449
2450void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2451{
2452 ImGuiStoragePair* it = LowerBound(data&: const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2453 if (it == Data.end() || it->key != key)
2454 return NULL;
2455 return it->val_p;
2456}
2457
2458// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2459int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2460{
2461 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2462 if (it == Data.end() || it->key != key)
2463 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2464 return &it->val_i;
2465}
2466
2467bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2468{
2469 return (bool*)GetIntRef(key, default_val: default_val ? 1 : 0);
2470}
2471
2472float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2473{
2474 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2475 if (it == Data.end() || it->key != key)
2476 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2477 return &it->val_f;
2478}
2479
2480void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2481{
2482 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2483 if (it == Data.end() || it->key != key)
2484 it = Data.insert(it, v: ImGuiStoragePair(key, default_val));
2485 return &it->val_p;
2486}
2487
2488// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2489void ImGuiStorage::SetInt(ImGuiID key, int val)
2490{
2491 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2492 if (it == Data.end() || it->key != key)
2493 Data.insert(it, v: ImGuiStoragePair(key, val));
2494 else
2495 it->val_i = val;
2496}
2497
2498void ImGuiStorage::SetBool(ImGuiID key, bool val)
2499{
2500 SetInt(key, val: val ? 1 : 0);
2501}
2502
2503void ImGuiStorage::SetFloat(ImGuiID key, float val)
2504{
2505 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2506 if (it == Data.end() || it->key != key)
2507 Data.insert(it, v: ImGuiStoragePair(key, val));
2508 else
2509 it->val_f = val;
2510}
2511
2512void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2513{
2514 ImGuiStoragePair* it = LowerBound(data&: Data, key);
2515 if (it == Data.end() || it->key != key)
2516 Data.insert(it, v: ImGuiStoragePair(key, val));
2517 else
2518 it->val_p = val;
2519}
2520
2521void ImGuiStorage::SetAllInt(int v)
2522{
2523 for (int i = 0; i < Data.Size; i++)
2524 Data[i].val_i = v;
2525}
2526
2527//-----------------------------------------------------------------------------
2528// [SECTION] ImGuiTextFilter
2529//-----------------------------------------------------------------------------
2530
2531// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2532ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2533{
2534 InputBuf[0] = 0;
2535 CountGrep = 0;
2536 if (default_filter)
2537 {
2538 ImStrncpy(dst: InputBuf, src: default_filter, IM_ARRAYSIZE(InputBuf));
2539 Build();
2540 }
2541}
2542
2543bool ImGuiTextFilter::Draw(const char* label, float width)
2544{
2545 if (width != 0.0f)
2546 ImGui::SetNextItemWidth(width);
2547 bool value_changed = ImGui::InputText(label, buf: InputBuf, IM_ARRAYSIZE(InputBuf));
2548 if (value_changed)
2549 Build();
2550 return value_changed;
2551}
2552
2553void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2554{
2555 out->resize(new_size: 0);
2556 const char* wb = b;
2557 const char* we = wb;
2558 while (we < e)
2559 {
2560 if (*we == separator)
2561 {
2562 out->push_back(v: ImGuiTextRange(wb, we));
2563 wb = we + 1;
2564 }
2565 we++;
2566 }
2567 if (wb != we)
2568 out->push_back(v: ImGuiTextRange(wb, we));
2569}
2570
2571void ImGuiTextFilter::Build()
2572{
2573 Filters.resize(new_size: 0);
2574 ImGuiTextRange input_range(InputBuf, InputBuf + strlen(s: InputBuf));
2575 input_range.split(separator: ',', out: &Filters);
2576
2577 CountGrep = 0;
2578 for (ImGuiTextRange& f : Filters)
2579 {
2580 while (f.b < f.e && ImCharIsBlankA(c: f.b[0]))
2581 f.b++;
2582 while (f.e > f.b && ImCharIsBlankA(c: f.e[-1]))
2583 f.e--;
2584 if (f.empty())
2585 continue;
2586 if (f.b[0] != '-')
2587 CountGrep += 1;
2588 }
2589}
2590
2591bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2592{
2593 if (Filters.empty())
2594 return true;
2595
2596 if (text == NULL)
2597 text = "";
2598
2599 for (const ImGuiTextRange& f : Filters)
2600 {
2601 if (f.empty())
2602 continue;
2603 if (f.b[0] == '-')
2604 {
2605 // Subtract
2606 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b + 1, needle_end: f.e) != NULL)
2607 return false;
2608 }
2609 else
2610 {
2611 // Grep
2612 if (ImStristr(haystack: text, haystack_end: text_end, needle: f.b, needle_end: f.e) != NULL)
2613 return true;
2614 }
2615 }
2616
2617 // Implicit * grep
2618 if (CountGrep == 0)
2619 return true;
2620
2621 return false;
2622}
2623
2624//-----------------------------------------------------------------------------
2625// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2626//-----------------------------------------------------------------------------
2627
2628// On some platform vsnprintf() takes va_list by reference and modifies it.
2629// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2630#ifndef va_copy
2631#if defined(__GNUC__) || defined(__clang__)
2632#define va_copy(dest, src) __builtin_va_copy(dest, src)
2633#else
2634#define va_copy(dest, src) (dest = src)
2635#endif
2636#endif
2637
2638char ImGuiTextBuffer::EmptyString[1] = { 0 };
2639
2640void ImGuiTextBuffer::append(const char* str, const char* str_end)
2641{
2642 int len = str_end ? (int)(str_end - str) : (int)strlen(s: str);
2643
2644 // Add zero-terminator the first time
2645 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2646 const int needed_sz = write_off + len;
2647 if (write_off + len >= Buf.Capacity)
2648 {
2649 int new_capacity = Buf.Capacity * 2;
2650 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
2651 }
2652
2653 Buf.resize(new_size: needed_sz);
2654 memcpy(dest: &Buf[write_off - 1], src: str, n: (size_t)len);
2655 Buf[write_off - 1 + len] = 0;
2656}
2657
2658void ImGuiTextBuffer::appendf(const char* fmt, ...)
2659{
2660 va_list args;
2661 va_start(args, fmt);
2662 appendfv(fmt, args);
2663 va_end(args);
2664}
2665
2666// Helper: Text buffer for logging/accumulating text
2667void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2668{
2669 va_list args_copy;
2670 va_copy(args_copy, args);
2671
2672 int len = ImFormatStringV(NULL, buf_size: 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2673 if (len <= 0)
2674 {
2675 va_end(args_copy);
2676 return;
2677 }
2678
2679 // Add zero-terminator the first time
2680 const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2681 const int needed_sz = write_off + len;
2682 if (write_off + len >= Buf.Capacity)
2683 {
2684 int new_capacity = Buf.Capacity * 2;
2685 Buf.reserve(new_capacity: needed_sz > new_capacity ? needed_sz : new_capacity);
2686 }
2687
2688 Buf.resize(new_size: needed_sz);
2689 ImFormatStringV(buf: &Buf[write_off - 1], buf_size: (size_t)len + 1, fmt, args: args_copy);
2690 va_end(args_copy);
2691}
2692
2693void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2694{
2695 IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2696 if (old_size == new_size)
2697 return;
2698 if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2699 LineOffsets.push_back(v: EndOffset);
2700 const char* base_end = base + new_size;
2701 for (const char* p = base + old_size; (p = (const char*)memchr(s: p, c: '\n', n: base_end - p)) != 0; )
2702 if (++p < base_end) // Don't push a trailing offset on last \n
2703 LineOffsets.push_back(v: (int)(intptr_t)(p - base));
2704 EndOffset = ImMax(lhs: EndOffset, rhs: new_size);
2705}
2706
2707//-----------------------------------------------------------------------------
2708// [SECTION] ImGuiListClipper
2709//-----------------------------------------------------------------------------
2710
2711// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2712// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2713static bool GetSkipItemForListClipping()
2714{
2715 ImGuiContext& g = *GImGui;
2716 return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2717}
2718
2719#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2720// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2721// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2722// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2723void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2724{
2725 ImGuiContext& g = *GImGui;
2726 ImGuiWindow* window = g.CurrentWindow;
2727 if (g.LogEnabled)
2728 {
2729 // If logging is active, do not perform any clipping
2730 *out_items_display_start = 0;
2731 *out_items_display_end = items_count;
2732 return;
2733 }
2734 if (GetSkipItemForListClipping())
2735 {
2736 *out_items_display_start = *out_items_display_end = 0;
2737 return;
2738 }
2739
2740 // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2741 // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2742 ImRect rect = window->ClipRect;
2743 if (g.NavMoveScoringItems)
2744 rect.Add(r: g.NavScoringNoClipRect);
2745 if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2746 rect.Add(r: WindowRectRelToAbs(window, r: window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2747
2748 const ImVec2 pos = window->DC.CursorPos;
2749 int start = (int)((rect.Min.y - pos.y) / items_height);
2750 int end = (int)((rect.Max.y - pos.y) / items_height);
2751
2752 // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2753 // FIXME: Verify this works with tabbing
2754 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2755 if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2756 start--;
2757 if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2758 end++;
2759
2760 start = ImClamp(v: start, mn: 0, mx: items_count);
2761 end = ImClamp(v: end + 1, mn: start, mx: items_count);
2762 *out_items_display_start = start;
2763 *out_items_display_end = end;
2764}
2765#endif
2766
2767static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2768{
2769 if (ranges.Size - offset <= 1)
2770 return;
2771
2772 // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2773 for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2774 for (int i = offset; i < sort_end + offset; ++i)
2775 if (ranges[i].Min > ranges[i + 1].Min)
2776 ImSwap(a&: ranges[i], b&: ranges[i + 1]);
2777
2778 // Now fuse ranges together as much as possible.
2779 for (int i = 1 + offset; i < ranges.Size; i++)
2780 {
2781 IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2782 if (ranges[i - 1].Max < ranges[i].Min)
2783 continue;
2784 ranges[i - 1].Min = ImMin(lhs: ranges[i - 1].Min, rhs: ranges[i].Min);
2785 ranges[i - 1].Max = ImMax(lhs: ranges[i - 1].Max, rhs: ranges[i].Max);
2786 ranges.erase(it: ranges.Data + i);
2787 i--;
2788 }
2789}
2790
2791static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2792{
2793 // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2794 // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2795 // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2796 ImGuiContext& g = *GImGui;
2797 ImGuiWindow* window = g.CurrentWindow;
2798 float off_y = pos_y - window->DC.CursorPos.y;
2799 window->DC.CursorPos.y = pos_y;
2800 window->DC.CursorMaxPos.y = ImMax(lhs: window->DC.CursorMaxPos.y, rhs: pos_y - g.Style.ItemSpacing.y);
2801 window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2802 window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2803 if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2804 columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
2805 if (ImGuiTable* table = g.CurrentTable)
2806 {
2807 if (table->IsInsideRow)
2808 ImGui::TableEndRow(table);
2809 table->RowPosY2 = window->DC.CursorPos.y;
2810 const int row_increase = (int)((off_y / line_height) + 0.5f);
2811 //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2812 table->RowBgColorCounter += row_increase;
2813 }
2814}
2815
2816static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2817{
2818 // StartPosY starts from ItemsFrozen hence the subtraction
2819 // Perform the add and multiply with double to allow seeking through larger ranges
2820 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2821 float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2822 ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, line_height: clipper->ItemsHeight);
2823}
2824
2825ImGuiListClipper::ImGuiListClipper()
2826{
2827 memset(s: this, c: 0, n: sizeof(*this));
2828}
2829
2830ImGuiListClipper::~ImGuiListClipper()
2831{
2832 End();
2833}
2834
2835void ImGuiListClipper::Begin(int items_count, float items_height)
2836{
2837 if (Ctx == NULL)
2838 Ctx = ImGui::GetCurrentContext();
2839
2840 ImGuiContext& g = *Ctx;
2841 ImGuiWindow* window = g.CurrentWindow;
2842 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2843
2844 if (ImGuiTable* table = g.CurrentTable)
2845 if (table->IsInsideRow)
2846 ImGui::TableEndRow(table);
2847
2848 StartPosY = window->DC.CursorPos.y;
2849 ItemsHeight = items_height;
2850 ItemsCount = items_count;
2851 DisplayStart = -1;
2852 DisplayEnd = 0;
2853
2854 // Acquire temporary buffer
2855 if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2856 g.ClipperTempData.resize(new_size: g.ClipperTempDataStacked, v: ImGuiListClipperData());
2857 ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2858 data->Reset(clipper: this);
2859 data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2860 TempData = data;
2861}
2862
2863void ImGuiListClipper::End()
2864{
2865 if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2866 {
2867 // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2868 ImGuiContext& g = *Ctx;
2869 IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2870 if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2871 ImGuiListClipper_SeekCursorForItem(clipper: this, item_n: ItemsCount);
2872
2873 // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2874 IM_ASSERT(data->ListClipper == this);
2875 data->StepNo = data->Ranges.Size;
2876 if (--g.ClipperTempDataStacked > 0)
2877 {
2878 data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2879 data->ListClipper->TempData = data;
2880 }
2881 TempData = NULL;
2882 }
2883 ItemsCount = -1;
2884}
2885
2886void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2887{
2888 ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2889 IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2890 IM_ASSERT(item_begin <= item_end);
2891 if (item_begin < item_end)
2892 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: item_begin, max: item_end));
2893}
2894
2895static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2896{
2897 ImGuiContext& g = *clipper->Ctx;
2898 ImGuiWindow* window = g.CurrentWindow;
2899 ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2900 IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2901
2902 ImGuiTable* table = g.CurrentTable;
2903 if (table && table->IsInsideRow)
2904 ImGui::TableEndRow(table);
2905
2906 // No items
2907 if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2908 return false;
2909
2910 // While we are in frozen row state, keep displaying items one by one, unclipped
2911 // FIXME: Could be stored as a table-agnostic state.
2912 if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2913 {
2914 clipper->DisplayStart = data->ItemsFrozen;
2915 clipper->DisplayEnd = ImMin(lhs: data->ItemsFrozen + 1, rhs: clipper->ItemsCount);
2916 if (clipper->DisplayStart < clipper->DisplayEnd)
2917 data->ItemsFrozen++;
2918 return true;
2919 }
2920
2921 // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2922 bool calc_clipping = false;
2923 if (data->StepNo == 0)
2924 {
2925 clipper->StartPosY = window->DC.CursorPos.y;
2926 if (clipper->ItemsHeight <= 0.0f)
2927 {
2928 // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2929 data->Ranges.push_front(v: ImGuiListClipperRange::FromIndices(min: data->ItemsFrozen, max: data->ItemsFrozen + 1));
2930 clipper->DisplayStart = ImMax(lhs: data->Ranges[0].Min, rhs: data->ItemsFrozen);
2931 clipper->DisplayEnd = ImMin(lhs: data->Ranges[0].Max, rhs: clipper->ItemsCount);
2932 data->StepNo = 1;
2933 return true;
2934 }
2935 calc_clipping = true; // If on the first step with known item height, calculate clipping.
2936 }
2937
2938 // Step 1: Let the clipper infer height from first range
2939 if (clipper->ItemsHeight <= 0.0f)
2940 {
2941 IM_ASSERT(data->StepNo == 1);
2942 if (table)
2943 IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2944
2945 clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2946 bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(f: clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(f: window->DC.CursorPos.y);
2947 if (affected_by_floating_point_precision)
2948 clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2949
2950 IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2951 calc_clipping = true; // If item height had to be calculated, calculate clipping afterwards.
2952 }
2953
2954 // Step 0 or 1: Calculate the actual ranges of visible elements.
2955 const int already_submitted = clipper->DisplayEnd;
2956 if (calc_clipping)
2957 {
2958 if (g.LogEnabled)
2959 {
2960 // If logging is active, do not perform any clipping
2961 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: 0, max: clipper->ItemsCount));
2962 }
2963 else
2964 {
2965 // Add range selected to be included for navigation
2966 const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2967 if (is_nav_request)
2968 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: g.NavScoringNoClipRect.Min.y, y2: g.NavScoringNoClipRect.Max.y, off_min: 0, off_max: 0));
2969 if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
2970 data->Ranges.push_back(v: ImGuiListClipperRange::FromIndices(min: clipper->ItemsCount - 1, max: clipper->ItemsCount));
2971
2972 // Add focused/active item
2973 ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, r: window->NavRectRel[0]);
2974 if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2975 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: nav_rect_abs.Min.y, y2: nav_rect_abs.Max.y, off_min: 0, off_max: 0));
2976
2977 // Add visible range
2978 const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2979 const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2980 data->Ranges.push_back(v: ImGuiListClipperRange::FromPositions(y1: window->ClipRect.Min.y, y2: window->ClipRect.Max.y, off_min, off_max));
2981 }
2982
2983 // Convert position ranges to item index ranges
2984 // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2985 // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2986 // which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2987 for (ImGuiListClipperRange& range : data->Ranges)
2988 if (range.PosToIndexConvert)
2989 {
2990 int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2991 int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2992 range.Min = ImClamp(v: already_submitted + m1 + range.PosToIndexOffsetMin, mn: already_submitted, mx: clipper->ItemsCount - 1);
2993 range.Max = ImClamp(v: already_submitted + m2 + range.PosToIndexOffsetMax, mn: range.Min + 1, mx: clipper->ItemsCount);
2994 range.PosToIndexConvert = false;
2995 }
2996 ImGuiListClipper_SortAndFuseRanges(ranges&: data->Ranges, offset: data->StepNo);
2997 }
2998
2999 // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3000 while (data->StepNo < data->Ranges.Size)
3001 {
3002 clipper->DisplayStart = ImMax(lhs: data->Ranges[data->StepNo].Min, rhs: already_submitted);
3003 clipper->DisplayEnd = ImMin(lhs: data->Ranges[data->StepNo].Max, rhs: clipper->ItemsCount);
3004 if (clipper->DisplayStart > already_submitted) //-V1051
3005 ImGuiListClipper_SeekCursorForItem(clipper, item_n: clipper->DisplayStart);
3006 data->StepNo++;
3007 if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3008 continue;
3009 return true;
3010 }
3011
3012 // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3013 // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3014 if (clipper->ItemsCount < INT_MAX)
3015 ImGuiListClipper_SeekCursorForItem(clipper, item_n: clipper->ItemsCount);
3016
3017 return false;
3018}
3019
3020bool ImGuiListClipper::Step()
3021{
3022 ImGuiContext& g = *Ctx;
3023 bool need_items_height = (ItemsHeight <= 0.0f);
3024 bool ret = ImGuiListClipper_StepInternal(clipper: this);
3025 if (ret && (DisplayStart == DisplayEnd))
3026 ret = false;
3027 if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3028 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3029 if (need_items_height && ItemsHeight > 0.0f)
3030 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3031 if (ret)
3032 {
3033 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3034 }
3035 else
3036 {
3037 IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3038 End();
3039 }
3040 return ret;
3041}
3042
3043//-----------------------------------------------------------------------------
3044// [SECTION] STYLING
3045//-----------------------------------------------------------------------------
3046
3047ImGuiStyle& ImGui::GetStyle()
3048{
3049 IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3050 return GImGui->Style;
3051}
3052
3053ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3054{
3055 ImGuiStyle& style = GImGui->Style;
3056 ImVec4 c = style.Colors[idx];
3057 c.w *= style.Alpha * alpha_mul;
3058 return ColorConvertFloat4ToU32(in: c);
3059}
3060
3061ImU32 ImGui::GetColorU32(const ImVec4& col)
3062{
3063 ImGuiStyle& style = GImGui->Style;
3064 ImVec4 c = col;
3065 c.w *= style.Alpha;
3066 return ColorConvertFloat4ToU32(in: c);
3067}
3068
3069const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3070{
3071 ImGuiStyle& style = GImGui->Style;
3072 return style.Colors[idx];
3073}
3074
3075ImU32 ImGui::GetColorU32(ImU32 col)
3076{
3077 ImGuiStyle& style = GImGui->Style;
3078 if (style.Alpha >= 1.0f)
3079 return col;
3080 ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3081 a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3082 return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3083}
3084
3085// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3086void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3087{
3088 ImGuiContext& g = *GImGui;
3089 ImGuiColorMod backup;
3090 backup.Col = idx;
3091 backup.BackupValue = g.Style.Colors[idx];
3092 g.ColorStack.push_back(v: backup);
3093 g.Style.Colors[idx] = ColorConvertU32ToFloat4(in: col);
3094}
3095
3096void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3097{
3098 ImGuiContext& g = *GImGui;
3099 ImGuiColorMod backup;
3100 backup.Col = idx;
3101 backup.BackupValue = g.Style.Colors[idx];
3102 g.ColorStack.push_back(v: backup);
3103 g.Style.Colors[idx] = col;
3104}
3105
3106void ImGui::PopStyleColor(int count)
3107{
3108 ImGuiContext& g = *GImGui;
3109 if (g.ColorStack.Size < count)
3110 {
3111 IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3112 count = g.ColorStack.Size;
3113 }
3114 while (count > 0)
3115 {
3116 ImGuiColorMod& backup = g.ColorStack.back();
3117 g.Style.Colors[backup.Col] = backup.BackupValue;
3118 g.ColorStack.pop_back();
3119 count--;
3120 }
3121}
3122
3123static const ImGuiDataVarInfo GStyleVarInfo[] =
3124{
3125 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
3126 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, DisabledAlpha) }, // ImGuiStyleVar_DisabledAlpha
3127 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
3128 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
3129 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
3130 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
3131 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
3132 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
3133 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
3134 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
3135 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
3136 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
3137 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
3138 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
3139 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
3140 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
3141 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
3142 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
3143 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
3144 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
3145 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
3146 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
3147 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
3148 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) }, // ImGuiStyleVar_TabBarBorderSize
3149 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
3150 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3151 { .Type: ImGuiDataType_Float, .Count: 1, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)},// ImGuiStyleVar_SeparatorTextBorderSize
3152 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) }, // ImGuiStyleVar_SeparatorTextAlign
3153 { .Type: ImGuiDataType_Float, .Count: 2, .Offset: (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) }, // ImGuiStyleVar_SeparatorTextPadding
3154};
3155
3156const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3157{
3158 IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3159 IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3160 return &GStyleVarInfo[idx];
3161}
3162
3163void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3164{
3165 ImGuiContext& g = *GImGui;
3166 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3167 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3168 {
3169 float* pvar = (float*)var_info->GetVarPtr(parent: &g.Style);
3170 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3171 *pvar = val;
3172 return;
3173 }
3174 IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3175}
3176
3177void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3178{
3179 ImGuiContext& g = *GImGui;
3180 const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3181 if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3182 {
3183 ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(parent: &g.Style);
3184 g.StyleVarStack.push_back(v: ImGuiStyleMod(idx, *pvar));
3185 *pvar = val;
3186 return;
3187 }
3188 IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3189}
3190
3191void ImGui::PopStyleVar(int count)
3192{
3193 ImGuiContext& g = *GImGui;
3194 if (g.StyleVarStack.Size < count)
3195 {
3196 IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3197 count = g.StyleVarStack.Size;
3198 }
3199 while (count > 0)
3200 {
3201 // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3202 ImGuiStyleMod& backup = g.StyleVarStack.back();
3203 const ImGuiDataVarInfo* info = GetStyleVarInfo(idx: backup.VarIdx);
3204 void* data = info->GetVarPtr(parent: &g.Style);
3205 if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
3206 else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3207 g.StyleVarStack.pop_back();
3208 count--;
3209 }
3210}
3211
3212const char* ImGui::GetStyleColorName(ImGuiCol idx)
3213{
3214 // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3215 switch (idx)
3216 {
3217 case ImGuiCol_Text: return "Text";
3218 case ImGuiCol_TextDisabled: return "TextDisabled";
3219 case ImGuiCol_WindowBg: return "WindowBg";
3220 case ImGuiCol_ChildBg: return "ChildBg";
3221 case ImGuiCol_PopupBg: return "PopupBg";
3222 case ImGuiCol_Border: return "Border";
3223 case ImGuiCol_BorderShadow: return "BorderShadow";
3224 case ImGuiCol_FrameBg: return "FrameBg";
3225 case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3226 case ImGuiCol_FrameBgActive: return "FrameBgActive";
3227 case ImGuiCol_TitleBg: return "TitleBg";
3228 case ImGuiCol_TitleBgActive: return "TitleBgActive";
3229 case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3230 case ImGuiCol_MenuBarBg: return "MenuBarBg";
3231 case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3232 case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3233 case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3234 case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3235 case ImGuiCol_CheckMark: return "CheckMark";
3236 case ImGuiCol_SliderGrab: return "SliderGrab";
3237 case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3238 case ImGuiCol_Button: return "Button";
3239 case ImGuiCol_ButtonHovered: return "ButtonHovered";
3240 case ImGuiCol_ButtonActive: return "ButtonActive";
3241 case ImGuiCol_Header: return "Header";
3242 case ImGuiCol_HeaderHovered: return "HeaderHovered";
3243 case ImGuiCol_HeaderActive: return "HeaderActive";
3244 case ImGuiCol_Separator: return "Separator";
3245 case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3246 case ImGuiCol_SeparatorActive: return "SeparatorActive";
3247 case ImGuiCol_ResizeGrip: return "ResizeGrip";
3248 case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3249 case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3250 case ImGuiCol_Tab: return "Tab";
3251 case ImGuiCol_TabHovered: return "TabHovered";
3252 case ImGuiCol_TabActive: return "TabActive";
3253 case ImGuiCol_TabUnfocused: return "TabUnfocused";
3254 case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3255 case ImGuiCol_PlotLines: return "PlotLines";
3256 case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3257 case ImGuiCol_PlotHistogram: return "PlotHistogram";
3258 case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3259 case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3260 case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3261 case ImGuiCol_TableBorderLight: return "TableBorderLight";
3262 case ImGuiCol_TableRowBg: return "TableRowBg";
3263 case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3264 case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3265 case ImGuiCol_DragDropTarget: return "DragDropTarget";
3266 case ImGuiCol_NavHighlight: return "NavHighlight";
3267 case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3268 case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3269 case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3270 }
3271 IM_ASSERT(0);
3272 return "Unknown";
3273}
3274
3275
3276//-----------------------------------------------------------------------------
3277// [SECTION] RENDER HELPERS
3278// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3279// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3280// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3281//-----------------------------------------------------------------------------
3282
3283const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3284{
3285 const char* text_display_end = text;
3286 if (!text_end)
3287 text_end = (const char*)-1;
3288
3289 while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3290 text_display_end++;
3291 return text_display_end;
3292}
3293
3294// Internal ImGui functions to render text
3295// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3296void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3297{
3298 ImGuiContext& g = *GImGui;
3299 ImGuiWindow* window = g.CurrentWindow;
3300
3301 // Hide anything after a '##' string
3302 const char* text_display_end;
3303 if (hide_text_after_hash)
3304 {
3305 text_display_end = FindRenderedTextEnd(text, text_end);
3306 }
3307 else
3308 {
3309 if (!text_end)
3310 text_end = text + strlen(s: text); // FIXME-OPT
3311 text_display_end = text_end;
3312 }
3313
3314 if (text != text_display_end)
3315 {
3316 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end);
3317 if (g.LogEnabled)
3318 LogRenderedText(ref_pos: &pos, text, text_end: text_display_end);
3319 }
3320}
3321
3322void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3323{
3324 ImGuiContext& g = *GImGui;
3325 ImGuiWindow* window = g.CurrentWindow;
3326
3327 if (!text_end)
3328 text_end = text + strlen(s: text); // FIXME-OPT
3329
3330 if (text != text_end)
3331 {
3332 window->DrawList->AddText(font: g.Font, font_size: g.FontSize, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end, wrap_width);
3333 if (g.LogEnabled)
3334 LogRenderedText(ref_pos: &pos, text, text_end);
3335 }
3336}
3337
3338// Default clip_rect uses (pos_min,pos_max)
3339// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3340// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3341// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3342// better advantage of the render function taking size into account for coarse clipping.
3343void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3344{
3345 // Perform CPU side clipping for single clipped element to avoid using scissor state
3346 ImVec2 pos = pos_min;
3347 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_display_end, hide_text_after_double_hash: false, wrap_width: 0.0f);
3348
3349 const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3350 const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3351 bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3352 if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3353 need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3354
3355 // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3356 if (align.x > 0.0f) pos.x = ImMax(lhs: pos.x, rhs: pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3357 if (align.y > 0.0f) pos.y = ImMax(lhs: pos.y, rhs: pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3358
3359 // Render
3360 if (need_clipping)
3361 {
3362 ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3363 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, cpu_fine_clip_rect: &fine_clip_rect);
3364 }
3365 else
3366 {
3367 draw_list->AddText(NULL, font_size: 0.0f, pos, col: GetColorU32(idx: ImGuiCol_Text), text_begin: text, text_end: text_display_end, wrap_width: 0.0f, NULL);
3368 }
3369}
3370
3371void ImGui::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, const ImRect* clip_rect)
3372{
3373 // Hide anything after a '##' string
3374 const char* text_display_end = FindRenderedTextEnd(text, text_end);
3375 const int text_len = (int)(text_display_end - text);
3376 if (text_len == 0)
3377 return;
3378
3379 ImGuiContext& g = *GImGui;
3380 ImGuiWindow* window = g.CurrentWindow;
3381 RenderTextClippedEx(draw_list: window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3382 if (g.LogEnabled)
3383 LogRenderedText(ref_pos: &pos_min, text, text_end: text_display_end);
3384}
3385
3386// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3387// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3388// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3389void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3390{
3391 ImGuiContext& g = *GImGui;
3392 if (text_end_full == NULL)
3393 text_end_full = FindRenderedTextEnd(text);
3394 const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end: text_end_full, hide_text_after_double_hash: false, wrap_width: 0.0f);
3395
3396 //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3397 //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3398 //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3399 // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3400 if (text_size.x > pos_max.x - pos_min.x)
3401 {
3402 // Hello wo...
3403 // | | |
3404 // min max ellipsis_max
3405 // <-> this is generally some padding value
3406
3407 const ImFont* font = draw_list->_Data->Font;
3408 const float font_size = draw_list->_Data->FontSize;
3409 const float font_scale = font_size / font->FontSize;
3410 const char* text_end_ellipsis = NULL;
3411 const float ellipsis_width = font->EllipsisWidth * font_scale;
3412
3413 // We can now claim the space between pos_max.x and ellipsis_max.x
3414 const float text_avail_width = ImMax(lhs: (ImMax(lhs: pos_max.x, rhs: ellipsis_max_x) - ellipsis_width) - pos_min.x, rhs: 1.0f);
3415 float text_size_clipped_x = font->CalcTextSizeA(size: font_size, max_width: text_avail_width, wrap_width: 0.0f, text_begin: text, text_end: text_end_full, remaining: &text_end_ellipsis).x;
3416 if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3417 {
3418 // Always display at least 1 character if there's no room for character + ellipsis
3419 text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(in_text: text, in_text_end: text_end_full);
3420 text_size_clipped_x = font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width: 0.0f, text_begin: text, text_end: text_end_ellipsis).x;
3421 }
3422 while (text_end_ellipsis > text && ImCharIsBlankA(c: text_end_ellipsis[-1]))
3423 {
3424 // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3425 text_end_ellipsis--;
3426 text_size_clipped_x -= font->CalcTextSizeA(size: font_size, FLT_MAX, wrap_width: 0.0f, text_begin: text_end_ellipsis, text_end: text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3427 }
3428
3429 // Render text, render ellipsis
3430 RenderTextClippedEx(draw_list, pos_min, pos_max: ImVec2(clip_max_x, pos_max.y), text, text_display_end: text_end_ellipsis, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3431 ImVec2 ellipsis_pos = ImTrunc(v: ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3432 if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3433 for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3434 font->RenderChar(draw_list, size: font_size, pos: ellipsis_pos, col: GetColorU32(idx: ImGuiCol_Text), c: font->EllipsisChar);
3435 }
3436 else
3437 {
3438 RenderTextClippedEx(draw_list, pos_min, pos_max: ImVec2(clip_max_x, pos_max.y), text, text_display_end: text_end_full, text_size_if_known: &text_size, align: ImVec2(0.0f, 0.0f));
3439 }
3440
3441 if (g.LogEnabled)
3442 LogRenderedText(ref_pos: &pos_min, text, text_end: text_end_full);
3443}
3444
3445// Render a rectangle shaped with optional rounding and borders
3446void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3447{
3448 ImGuiContext& g = *GImGui;
3449 ImGuiWindow* window = g.CurrentWindow;
3450 window->DrawList->AddRectFilled(p_min, p_max, col: fill_col, rounding);
3451 const float border_size = g.Style.FrameBorderSize;
3452 if (border && border_size > 0.0f)
3453 {
3454 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3455 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3456 }
3457}
3458
3459void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3460{
3461 ImGuiContext& g = *GImGui;
3462 ImGuiWindow* window = g.CurrentWindow;
3463 const float border_size = g.Style.FrameBorderSize;
3464 if (border_size > 0.0f)
3465 {
3466 window->DrawList->AddRect(p_min: p_min + ImVec2(1, 1), p_max: p_max + ImVec2(1, 1), col: GetColorU32(idx: ImGuiCol_BorderShadow), rounding, flags: 0, thickness: border_size);
3467 window->DrawList->AddRect(p_min, p_max, col: GetColorU32(idx: ImGuiCol_Border), rounding, flags: 0, thickness: border_size);
3468 }
3469}
3470
3471void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3472{
3473 ImGuiContext& g = *GImGui;
3474 if (id != g.NavId)
3475 return;
3476 if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3477 return;
3478 ImGuiWindow* window = g.CurrentWindow;
3479 if (window->DC.NavHideHighlightOneFrame)
3480 return;
3481
3482 float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3483 ImRect display_rect = bb;
3484 display_rect.ClipWith(r: window->ClipRect);
3485 if (flags & ImGuiNavHighlightFlags_TypeDefault)
3486 {
3487 const float THICKNESS = 2.0f;
3488 const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3489 display_rect.Expand(amount: ImVec2(DISTANCE, DISTANCE));
3490 bool fully_visible = window->ClipRect.Contains(r: display_rect);
3491 if (!fully_visible)
3492 window->DrawList->PushClipRect(clip_rect_min: display_rect.Min, clip_rect_max: display_rect.Max);
3493 window->DrawList->AddRect(p_min: display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), p_max: display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), col: GetColorU32(idx: ImGuiCol_NavHighlight), rounding, flags: 0, thickness: THICKNESS);
3494 if (!fully_visible)
3495 window->DrawList->PopClipRect();
3496 }
3497 if (flags & ImGuiNavHighlightFlags_TypeThin)
3498 {
3499 window->DrawList->AddRect(p_min: display_rect.Min, p_max: display_rect.Max, col: GetColorU32(idx: ImGuiCol_NavHighlight), rounding, flags: 0, thickness: 1.0f);
3500 }
3501}
3502
3503void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3504{
3505 ImGuiContext& g = *GImGui;
3506 IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3507 ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3508 for (ImGuiViewportP* viewport : g.Viewports)
3509 {
3510 // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3511 ImVec2 offset, size, uv[4];
3512 if (!font_atlas->GetMouseCursorTexData(cursor: mouse_cursor, out_offset: &offset, out_size: &size, out_uv_border: &uv[0], out_uv_fill: &uv[2]))
3513 continue;
3514 const ImVec2 pos = base_pos - offset;
3515 const float scale = base_scale;
3516 if (!viewport->GetMainRect().Overlaps(r: ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3517 continue;
3518 ImDrawList* draw_list = GetForegroundDrawList(viewport);
3519 ImTextureID tex_id = font_atlas->TexID;
3520 draw_list->PushTextureID(texture_id: tex_id);
3521 draw_list->AddImage(user_texture_id: tex_id, p_min: pos + ImVec2(1, 0) * scale, p_max: pos + (ImVec2(1, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3522 draw_list->AddImage(user_texture_id: tex_id, p_min: pos + ImVec2(2, 0) * scale, p_max: pos + (ImVec2(2, 0) + size) * scale, uv_min: uv[2], uv_max: uv[3], col: col_shadow);
3523 draw_list->AddImage(user_texture_id: tex_id, p_min: pos, p_max: pos + size * scale, uv_min: uv[2], uv_max: uv[3], col: col_border);
3524 draw_list->AddImage(user_texture_id: tex_id, p_min: pos, p_max: pos + size * scale, uv_min: uv[0], uv_max: uv[1], col: col_fill);
3525 draw_list->PopTextureID();
3526 }
3527}
3528
3529//-----------------------------------------------------------------------------
3530// [SECTION] INITIALIZATION, SHUTDOWN
3531//-----------------------------------------------------------------------------
3532
3533// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3534// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3535ImGuiContext* ImGui::GetCurrentContext()
3536{
3537 return GImGui;
3538}
3539
3540void ImGui::SetCurrentContext(ImGuiContext* ctx)
3541{
3542#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3543 IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3544#else
3545 GImGui = ctx;
3546#endif
3547}
3548
3549void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3550{
3551 GImAllocatorAllocFunc = alloc_func;
3552 GImAllocatorFreeFunc = free_func;
3553 GImAllocatorUserData = user_data;
3554}
3555
3556// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3557void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3558{
3559 *p_alloc_func = GImAllocatorAllocFunc;
3560 *p_free_func = GImAllocatorFreeFunc;
3561 *p_user_data = GImAllocatorUserData;
3562}
3563
3564ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3565{
3566 ImGuiContext* prev_ctx = GetCurrentContext();
3567 ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3568 SetCurrentContext(ctx);
3569 Initialize();
3570 if (prev_ctx != NULL)
3571 SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3572 return ctx;
3573}
3574
3575void ImGui::DestroyContext(ImGuiContext* ctx)
3576{
3577 ImGuiContext* prev_ctx = GetCurrentContext();
3578 if (ctx == NULL) //-V1051
3579 ctx = prev_ctx;
3580 SetCurrentContext(ctx);
3581 Shutdown();
3582 SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3583 IM_DELETE(p: ctx);
3584}
3585
3586// IMPORTANT: ###xxx suffixes must be same in ALL languages
3587static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3588{
3589 { .Key: ImGuiLocKey_VersionStr, .Text: "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3590 { .Key: ImGuiLocKey_TableSizeOne, .Text: "Size column to fit###SizeOne" },
3591 { .Key: ImGuiLocKey_TableSizeAllFit, .Text: "Size all columns to fit###SizeAll" },
3592 { .Key: ImGuiLocKey_TableSizeAllDefault, .Text: "Size all columns to default###SizeAll" },
3593 { .Key: ImGuiLocKey_TableResetOrder, .Text: "Reset order###ResetOrder" },
3594 { .Key: ImGuiLocKey_WindowingMainMenuBar, .Text: "(Main menu bar)" },
3595 { .Key: ImGuiLocKey_WindowingPopup, .Text: "(Popup)" },
3596 { .Key: ImGuiLocKey_WindowingUntitled, .Text: "(Untitled)" },
3597};
3598
3599void ImGui::Initialize()
3600{
3601 ImGuiContext& g = *GImGui;
3602 IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3603
3604 // Add .ini handle for ImGuiWindow and ImGuiTable types
3605 {
3606 ImGuiSettingsHandler ini_handler;
3607 ini_handler.TypeName = "Window";
3608 ini_handler.TypeHash = ImHashStr(data_p: "Window");
3609 ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3610 ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3611 ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3612 ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3613 ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3614 AddSettingsHandler(handler: &ini_handler);
3615 }
3616 TableSettingsAddSettingsHandler();
3617
3618 // Setup default localization table
3619 LocalizeRegisterEntries(entries: GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3620
3621 // Setup default platform clipboard/IME handlers.
3622 g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
3623 g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3624 g.IO.ClipboardUserData = (void*)&g; // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3625 g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3626
3627 // Create default viewport
3628 ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3629 g.Viewports.push_back(v: viewport);
3630 g.TempBuffer.resize(new_size: 1024 * 3 + 1, v: 0);
3631
3632#ifdef IMGUI_HAS_DOCK
3633#endif